lib.rs 19.3 KB
Newer Older
WuEcho's avatar
WuEcho committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
//! ewasm_api is a library used to interface with Ethereum's EEI in [Ewasm](https://github.com/ewasm/design), a set of enhancements to
//! the Ethereum smart contract platform.
//! ewasm_api exposes both a set of unsafe "native" functions representing the actual EEI
//! functions, and a set of safe wrappers around them. It is recommended not to use the native
//! functions as they do not perform bounds-checking.
//!
//! To use ewasm_api, simply include it as a dependency in your project.
//! ewasm_api can be built with various feature sets:
//! - `default`: Builds with `wee_alloc` as the global allocator and with the Rust standard
//! library.
//! - `qimalloc`: Builds with [qimalloc](https://github.com/wasmx/qimalloc) as the global
//! allocator.
//! - `debug`: Exposes the debugging interface.
//! - `experimental`: Exposes the experimental bignum system library API.
//!
//! # Examples
//! ```ignore
//! extern crate ewasm_api;
//!
//! use ewasm_api::{Hash, block_hash, finish_data};
//!
//! #[cfg(target_arch = "wasm32")]
//! #[no_mangle]
//! pub extern "C" fn main() {
//!     let a: Hash = block_hash(1);
//!     finish_data(&a.bytes);
//! }
//! ```

#[macro_use]
extern crate cfg_if;

cfg_if! {
    if #[cfg(feature = "wee_alloc")] {
        extern crate wee_alloc;
        #[global_allocator]
        static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
    } else if #[cfg(feature = "qimalloc")] {
        extern crate qimalloc;
        #[global_allocator]
        static ALLOC: qimalloc::QIMalloc = qimalloc::QIMalloc::INIT;
    }
}

mod native;
mod utils;

pub extern crate ethabi as metavmabi;

//pub extern crate rustc_hex;
pub mod metavm;
pub mod types;

#[cfg(feature = "debug")]
pub mod debug;

#[cfg(feature = "experimental")]
pub mod bignum;

#[cfg(not(feature = "std"))]
pub mod convert;

#[cfg(feature = "std")]
use std::vec::Vec;

use types::*;
use utils::*;

/// Re-export of all the basic features.
pub mod prelude {
    pub use crate::*;

    pub use crate::types::*;

    #[cfg(not(feature = "std"))]
    pub use crate::convert::*;

    #[cfg(feature = "debug")]
    pub use crate::debug;

    #[cfg(feature = "experimental")]
    pub use crate::bignum;
}

/// Enum representing an error code for EEI calls. Currently used by `codeCopy`, `callDataCopy`,
/// `externalCodeCopy`, and `returnDataCopy`.
pub enum Error {
    OutOfBoundsCopy,
}

/// Enum describing the result of a call. Used by `call`, `callCode`, `callDelegate`, and
/// `callStatic`.
pub enum CallResult {
    Successful,
    Failure,
    Revert,
    Unknown,
}

/// Enum describing the result of `create`. On success, the data contained is the address of the
/// newly created contract.
pub enum CreateResult {
    Successful(Address),
    Failure,
    Revert,
    Unknown,
}

/// Subtracts the given amount from the VM's gas counter. This is usually injected by the metering
/// contract at deployment time, and hence is unneeded in most cases.
pub fn consume_gas(amount: u64) {
    unsafe {
        native::ethereum_useGas(amount);
    }
}

/// Returns the gas left in the current call.
pub fn gas_left() -> u64 {
    unsafe { native::ethereum_getGasLeft() }
}

/// Returns the executing address.
pub fn current_address() -> Address {
    let mut ret = Address::default();

    unsafe {
        native::ethereum_getAddress(ret.bytes.as_mut_ptr() as *const u32);
    }

    ret
}

/// Returns the balance of the address given.
pub fn external_balance(address: &Address) -> EtherValue {
    let mut ret = EtherValue::default();

    unsafe {
        native::ethereum_getExternalBalance(
            address.bytes.as_ptr() as *const u32,
            ret.bytes.as_mut_ptr() as *const u32,
        );
    }

    ret
}

/// Returns the beneficiary address for the block this transaction is in (current block)
pub fn block_coinbase() -> Address {
    let mut ret = Address::default();

    unsafe {
        native::ethereum_getBlockCoinbase(ret.bytes.as_mut_ptr() as *const u32);
    }

    ret
}

/// Returns the difficulty of the most recent block.
pub fn block_difficulty() -> Difficulty {
    let mut ret = Difficulty::default();

    unsafe {
        native::ethereum_getBlockDifficulty(ret.bytes.as_mut_ptr() as *const u32);
    }

    ret
}

/// Returns the gas limit of the most recent block.
pub fn block_gas_limit() -> u64 {
    unsafe { native::ethereum_getBlockGasLimit() }
}

/// Returns the hash of the `number`th most recent block.
pub fn block_hash(number: u64) -> Hash {
    let mut ret = Hash::default();

    unsafe {
        native::ethereum_getBlockHash(number, ret.bytes.as_mut_ptr() as *const u32);
    }

    ret
}

/// Returns the number of the most recent block.
pub fn block_number() -> u64 {
    unsafe { native::ethereum_getBlockNumber() }
}

/// Returns the timestamp of the most recent block.
pub fn block_timestamp() -> u64 {
    unsafe { native::ethereum_getBlockTimestamp() }
}

/// Returns the gas price of the currently executing call.
pub fn tx_gas_price() -> EtherValue {
    let mut ret = EtherValue::default();

    unsafe {
        native::ethereum_getTxGasPrice(ret.bytes.as_mut_ptr() as *const u32);
    }

    ret
}

/// Returns the address of the original transaction sender.
pub fn tx_origin() -> Address {
    let mut ret = Address::default();

    unsafe {
        native::ethereum_getTxOrigin(ret.bytes.as_mut_ptr() as *const u32);
    }

    ret
}

/// Appends log data to the transaction receipt, with a variable number of topics.
fn log(
    data: &[u8],
    topic_count: usize,
    topic1: *const u8,
    topic2: *const u8,
    topic3: *const u8,
    topic4: *const u8,
) {
    unsafe {
        native::ethereum_log(
            data.as_ptr() as *const u32,
            data.len() as u32,
            topic_count as u32,
            topic1 as *const u32,
            topic2 as *const u32,
            topic3 as *const u32,
            topic4 as *const u32,
        );
    }
}

/// Appends log data without a topic.
pub fn log0(data: &[u8]) {
    log(
        data,
        0,
        0 as *const u8,
        0 as *const u8,
        0 as *const u8,
        0 as *const u8,
    )
}

/// Appends log data with one topic.
pub fn log1(data: &[u8], topic1: &LogTopic) {
    log(
        data,
        1,
        topic1.bytes.as_ptr() as *const u8,
        0 as *const u8,
        0 as *const u8,
        0 as *const u8,
    )
}

/// Appends log data with two topics.
pub fn log2(data: &[u8], topic1: &LogTopic, topic2: &LogTopic) {
    log(
        data,
        2,
        topic1.bytes.as_ptr() as *const u8,
        topic2.bytes.as_ptr() as *const u8,
        0 as *const u8,
        0 as *const u8,
    )
}

/// Appends log data with three topics.
pub fn log3(data: &[u8], topic1: &LogTopic, topic2: &LogTopic, topic3: &LogTopic) {
    log(
        data,
        3,
        topic1.bytes.as_ptr() as *const u8,
        topic2.bytes.as_ptr() as *const u8,
        topic3.bytes.as_ptr() as *const u8,
        0 as *const u8,
    )
}

/// Appends log data with four topics.
pub fn log4(
    data: &[u8],
    topic1: &LogTopic,
    topic2: &LogTopic,
    topic3: &LogTopic,
    topic4: &LogTopic,
) {
    log(
        data,
        4,
        topic1.bytes.as_ptr() as *const u8,
        topic2.bytes.as_ptr() as *const u8,
        topic3.bytes.as_ptr() as *const u8,
        topic4.bytes.as_ptr() as *const u8,
    )
}

/// Executes a standard call to the specified address with the given gas limit, ether value, and
/// data.
pub fn call_mutable(
    gas_limit: u64,
    address: &Address,
    value: &EtherValue,
    data: &[u8],
) -> CallResult {
    let ret = unsafe {
        native::ethereum_call(
            gas_limit,
            address.bytes.as_ptr() as *const u32,
            value.bytes.as_ptr() as *const u32,
            data.as_ptr() as *const u32,
            data.len() as u32,
        )
    };

    match ret {
        0 => CallResult::Successful,
        1 => CallResult::Failure,
        2 => CallResult::Revert,
        _ => CallResult::Unknown,
    }
}

/// Executes another account's code in the context of the caller.
pub fn call_code(gas_limit: u64, address: &Address, value: &EtherValue, data: &[u8]) -> CallResult {
    let ret = unsafe {
        native::ethereum_callCode(
            gas_limit,
            address.bytes.as_ptr() as *const u32,
            value.bytes.as_ptr() as *const u32,
            data.as_ptr() as *const u32,
            data.len() as u32,
        )
    };

    match ret {
        0 => CallResult::Successful,
        1 => CallResult::Failure,
        2 => CallResult::Revert,
        _ => CallResult::Unknown,
    }
}

/// Executes a call similar to `call_code`, but retaining the currently executing call's sender
/// and value.
pub fn call_delegate(gas_limit: u64, address: &Address, data: &[u8]) -> CallResult {
    let ret = unsafe {
        native::ethereum_callDelegate(
            gas_limit,
            address.bytes.as_ptr() as *const u32,
            data.as_ptr() as *const u32,
            data.len() as u32,
        )
    };

    match ret {
        0 => CallResult::Successful,
        1 => CallResult::Failure,
        2 => CallResult::Revert,
        _ => CallResult::Unknown,
    }
}

/// Executes a static call which cannot mutate the state.
pub fn call_static(gas_limit: u64, address: &Address, data: &[u8]) -> CallResult {
    let ret = unsafe {
        native::ethereum_callStatic(
            gas_limit,
            address.bytes.as_ptr() as *const u32,
            data.as_ptr() as *const u32,
            data.len() as u32,
        )
    };

    match ret {
        0 => CallResult::Successful,
        1 => CallResult::Failure,
        2 => CallResult::Revert,
        _ => CallResult::Unknown,
    }
}

/// Creates a contract with the the given code, sending the specified ether value to its address.
pub fn create(value: &EtherValue, data: &[u8]) -> CreateResult {
    let mut address = Address::default();

    let ret = unsafe {
        native::ethereum_create(
            value.bytes.as_ptr() as *const u32,
            data.as_ptr() as *const u32,
            data.len() as u32,
            address.bytes.as_mut_ptr() as *const u32,
        )
    };

    match ret {
        0 => CreateResult::Successful(address),
        1 => CreateResult::Failure,
        2 => CreateResult::Revert,
        _ => CreateResult::Unknown,
    }
}

/// Executes callDataCopy, but does not check for overflow.
pub fn unsafe_calldata_copy(from: usize, length: usize, ret: &mut [u8]) {
    unsafe {
        native::ethereum_callDataCopy(ret.as_mut_ptr() as *const u32, from as u32, length as u32);
    }
}

#[cfg(feature = "std")]
/// Returns a vector containing all data passed with the currently executing call.
pub fn calldata_acquire() -> Vec<u8> {
    let length = calldata_size();

    let mut ret: Vec<u8> = unsafe_alloc_buffer(length);
    unsafe_calldata_copy(0, length, &mut ret);
    ret
}

/// Returns the segment of call data beginning at `from`, and continuing for `length` bytes.
pub fn calldata_copy(from: usize, length: usize, ret: &mut [u8]) -> Result<(), Error> {
    let size = calldata_size();

    if (size < from) || ((size - from) < length) || (ret.len() < length) {
        Err(Error::OutOfBoundsCopy)
    } else {
        unsafe_calldata_copy(from, length, ret);
        Ok(())
    }
}

/// Returns the length of the call data supplied with the currently executing call.
pub fn calldata_size() -> usize {
    unsafe { native::ethereum_getCallDataSize() as usize }
}

/// Returns the sender of the currently executing call.
pub fn caller() -> Address {
    let mut ret = Address::default();

    unsafe {
        native::ethereum_getCaller(ret.bytes.as_mut_ptr() as *const u32);
    }

    ret
}

/// Returns the value sent with the currently executing call.
pub fn callvalue() -> EtherValue {
    let mut ret = EtherValue::default();

    unsafe {
        native::ethereum_getCallValue(ret.bytes.as_mut_ptr() as *const u32);
    }

    ret
}

/// Executes codeCopy, but does not check for overflow.
pub fn unsafe_code_copy(from: usize, length: usize, ret: &mut [u8]) {
    unsafe {
        native::ethereum_codeCopy(ret.as_mut_ptr() as *const u32, from as u32, length as u32);
    }
}

#[cfg(feature = "std")]
/// Returns the currently executing code.
pub fn code_acquire() -> Vec<u8> {
    let length = code_size();

    let mut ret: Vec<u8> = unsafe_alloc_buffer(length);
    unsafe_code_copy(0, length, &mut ret);
    ret
}

/// Copies the segment of running code beginning at `from` and continuing for `length` bytes.
pub fn code_copy(from: usize, length: usize, ret: &mut [u8]) -> Result<(), Error> {
    let size = code_size();

    if (size < from) || ((size - from) < length) || (ret.len() < length) {
        Err(Error::OutOfBoundsCopy)
    } else {
        unsafe_code_copy(from, length, ret);
        Ok(())
    }
}

/// Returns the size of the currently executing code.
pub fn code_size() -> usize {
    unsafe { native::ethereum_getCodeSize() as usize }
}

/// Executes externalCodeCopy, but does not check for overflow.
pub fn unsafe_external_code_copy(address: &Address, from: usize, length: usize, ret: &mut [u8]) {
    unsafe {
        native::ethereum_externalCodeCopy(
            address.bytes.as_ptr() as *const u32,
            ret.as_mut_ptr() as *const u32,
            from as u32,
            length as u32,
        );
    }
}

#[cfg(feature = "std")]
/// Returns the code at the specified address.
pub fn external_code_acquire(address: &Address) -> Vec<u8> {
    let length = external_code_size(address);

    let mut ret: Vec<u8> = unsafe_alloc_buffer(length);
    unsafe_external_code_copy(address, 0, length, &mut ret);
    ret
}

/// Returns the segment of code at `address` beginning at `from` and continuing for `length` bytes.
pub fn external_code_copy(
    address: &Address,
    from: usize,
    length: usize,
    ret: &mut [u8],
) -> Result<(), Error> {
    let size = external_code_size(address);

    if (size < from) || ((size - from) < length) || (ret.len() < length) {
        Err(Error::OutOfBoundsCopy)
    } else {
        unsafe_external_code_copy(address, from, length, ret);
        Ok(())
    }
}

/// Returns the size of the code at the specified address.
pub fn external_code_size(address: &Address) -> usize {
    unsafe { native::ethereum_getExternalCodeSize(address.bytes.as_ptr() as *const u32) as usize }
}

/// Executes returnDataCopy, but does not check for overflow.
pub fn unsafe_returndata_copy(from: usize, length: usize, ret: &mut [u8]) {
    unsafe {
        native::ethereum_returnDataCopy(ret.as_mut_ptr() as *const u32, from as u32, length as u32);
    }
}

#[cfg(feature = "std")]
/// Returns the data in the VM's return buffer.
pub fn returndata_acquire() -> Vec<u8> {
    let length = returndata_size();

    let mut ret: Vec<u8> = unsafe_alloc_buffer(length);
    unsafe_returndata_copy(0, length, &mut ret);
    ret
}

/// Returns the segment of return buffer data beginning at `from` and continuing for `length` bytes.
pub fn returndata_copy(from: usize, length: usize, ret: &mut [u8]) -> Result<(), Error> {
    let size = returndata_size();

    if (size < from) || ((size - from) < length) || (ret.len() < length) {
        Err(Error::OutOfBoundsCopy)
    } else {
        unsafe_returndata_copy(from, length, ret);
        Ok(())
    }
}

/// Returns the length of the data in the VM's return buffer.
pub fn returndata_size() -> usize {
    unsafe { native::ethereum_getReturnDataSize() as usize }
}

/// Halts execution, reverts all changes to the state and consumes all gas.
pub fn abort() -> ! {
    // TODO: use assembly block with `unreachable`
    panic!()
}

/// Halts execution and reverts all changes to the state.
pub fn revert() -> ! {
    unsafe {
        native::ethereum_revert(0 as *const u32, 0 as u32);
    }
}

/// Fills the return buffer with the given data and halts execution, reverting all state changes.
pub fn revert_data(data: &[u8]) -> ! {
    unsafe {
        native::ethereum_revert(data.as_ptr() as *const u32, data.len() as u32);
    }
}

/// Ends execution, signalling success.
pub fn finish() -> ! {
    unsafe {
        native::ethereum_finish(0 as *const u32, 0 as u32);
    }
}

/// Fills the return buffer with the given data and halts execution, signalling success.
pub fn finish_data(data: &[u8]) -> ! {
    unsafe {
        native::ethereum_finish(data.as_ptr() as *const u32, data.len() as u32);
    }
}

/// Accesses the storage data at the specified key.
pub fn storage_load(key: &StorageKey) -> StorageValue {
    let mut ret = StorageValue::default();

    unsafe {
        native::ethereum_storageLoad(
            key.bytes.as_ptr() as *const u32,
            ret.bytes.as_mut_ptr() as *const u32,
        );
    }

    ret
}

/// Sets the storage data at the specified key.
pub fn storage_store(key: &StorageKey, value: &StorageValue) {
    unsafe {
        native::ethereum_storageStore(
            key.bytes.as_ptr() as *const u32,
            value.bytes.as_ptr() as *const u32,
        );
    }
}

/// Self-destructs the running contract, sending all its ether to a specified beneficiary address.
pub fn selfdestruct(address: &Address) -> ! {
    unsafe {
        native::ethereum_selfDestruct(address.bytes.as_ptr() as *const u32);
    }
}

/*

// add by echo : 扩展存储,以支持超过 32byte 的 key/value >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
extern "C" {
    pub fn ethereum_storageStore2(
        keyOffset: *const u32, keyLength: u32,
        valueOffset: *const u32, valueLength: u32,
    );
    pub fn ethereum_storageLoad2(
        keyOffset: *const u32, keyLength: u32,
        resultOffset: *const u32, resultType: u32,
    );
}

// PUT Key->Val
//pub fn storage_store2(key: &[u8], keyLen: u32, value: &[u8], valueLen: u32) {
pub fn storage_store2(key: &[u8], value: &[u8]) {
    let key_len = key.len();
    let value_len = value.len();
    unsafe {
        ethereum_storageStore2(
            key.as_ptr() as *const u32,
            key_len as u32,
            value.as_ptr() as *const u32,
            value_len as u32,
        );
    }
}

pub fn storage_load2(key: &[u8]) -> Vec<u8> {
    let key_len = key.len();
    let mut val_len: [u8; 32] = [0; 32];
    unsafe {
        ethereum_storageLoad2(
            key.as_ptr() as *const u32,
            key_len as u32,
            val_len.as_mut_ptr() as *const u32,
            1,
        );
    }
    //TODO 执行完上面的请求,好像有一个阻塞

    let vl = metavmutils::bytes_to_uint(&val_len[..]);
    let mut v: Vec<u8> = vec![0; vl];
    unsafe {
        ethereum_storageLoad2(
            key.as_ptr() as *const u32,
            key_len as u32,
            v.as_mut_slice().as_mut_ptr() as *const u32,
            2,
        );
    }
    v
}

pub mod metavmutils {
    pub fn bytes_to_uint(n: &[u8]) -> usize {
        let size = n.len();
        let mut r: usize = 0;
        for i in 0..size {
            let x = n[i] as usize;
            if x > 0 {
                let m = (size - 1 - i) * 8;
                r = r + (x << m);
            }
        }
        r
    }

    pub fn u32_to_bytes(i: u32) -> Vec<u8> {
        let mut r: Vec<u8> = Vec::new();
        r.insert(0, (i >> 24) as u8);
        r.insert(1, (i >> 16) as u8);
        r.insert(2, (i >> 8) as u8);
        r.insert(3, i as u8);
        r
    }

    pub fn u32_to_bytes32(i: u32) -> [u8; 32] {
        let new_b: Vec<u8> = u32_to_bytes(i);
        let mut val: [u8; 32] = [0; 32];
        val[32 - 4] = new_b[0];
        val[32 - 3] = new_b[1];
        val[32 - 2] = new_b[2];
        val[32 - 1] = new_b[3];
        val
    }
}

// add by echo : 扩展存储,以支持超过 32byte 的 key/value <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

*/