示例#1
0
 def to_snapshot(self, root_only=False, no_prevblocks=False):
     snapshot = {}
     if root_only:
         # Smaller snapshot format that only includes the state root
         # (requires original DB to re-initialize)
         snapshot["state_root"] = "0x" + encode_hex(self.trie.root_hash)
     else:
         # "Full" snapshot
         snapshot["alloc"] = self.to_dict()
     # Save non-state-root variables
     for k, default in STATE_DEFAULTS.items():
         default = copy.copy(default)
         v = getattr(self, k)
         if is_numeric(default):
             snapshot[k] = str(v)
         elif isinstance(default, (str, bytes)):
             snapshot[k] = "0x" + encode_hex(v)
         elif k == "prev_headers" and not no_prevblocks:
             snapshot[k] = [
                 prev_header_to_dict(h)
                 for h in v[:self.config["PREV_HEADER_DEPTH"]]
             ]
         elif k == "recent_uncles" and not no_prevblocks:
             snapshot[k] = {
                 str(n): ["0x" + encode_hex(h) for h in headers]
                 for n, headers in v.items()
             }
     return snapshot
示例#2
0
 def to_dict(self):
     d = {}
     for name, _ in self.__class__._meta.fields:
         d[name] = getattr(self, name)
         if name in ("to", "data"):
             d[name] = "0x" + encode_hex(d[name])
     d["sender"] = "0x" + encode_hex(self.sender)
     d["hash"] = "0x" + encode_hex(self.hash)
     return d
示例#3
0
 def to_dict(self):
     d = {}
     for name, _ in self.__class__.fields:
         d[name] = getattr(self, name)
         if name in ('to', 'data'):
             d[name] = '0x' + encode_hex(d[name])
     d['sender'] = '0x' + encode_hex(self.sender)
     d['hash'] = '0x' + encode_hex(self.hash)
     return d
示例#4
0
def prev_header_to_dict(h):
    return {
        "hash": "0x" + encode_hex(h.hash),
        "number": str(h.number),
        "timestamp": str(h.timestamp),
        "difficulty": str(h.difficulty),
        "gas_used": str(h.gas_used),
        "gas_limit": str(h.gas_limit),
        "uncles_hash": "0x" + encode_hex(h.uncles_hash),
    }
示例#5
0
 def to_dict(self):
     odict = self.storage_trie.to_dict()
     for k, v in self.storage_cache.items():
         odict[utils.encode_int(k)] = rlp.encode(utils.encode_int(v))
     return {
         'balance': str(self.balance),
         'nonce': str(self.nonce),
         'code': '0x' + encode_hex(self.code),
         'storage': {
             '0x' + encode_hex(key.lstrip(b'\x00') or b'\x00'):
             '0x' + encode_hex(rlp.decode(val))
             for key, val in odict.items()
         }
     }
示例#6
0
 def to_dict(self):
     odict = self.storage_trie.to_dict()
     for k, v in self.storage_cache.items():
         odict[utils.encode_int(k)] = rlp.encode(utils.encode_int(v))
     return {
         "balance": str(self.balance),
         "nonce": str(self.nonce),
         "code": "0x" + encode_hex(self.code),
         "storage": {
             "0x" + encode_hex(key.lstrip(b"\x00") or b"\x00"):
             "0x" + encode_hex(rlp.decode(val))
             for key, val in odict.items()
         },
     }
示例#7
0
 def to_dict(self):
     for addr in self.trie.to_dict().keys():
         self.get_and_cache_account(addr)
     return {
         encode_hex(addr): acct.to_dict()
         for addr, acct in self.cache.items()
     }
示例#8
0
def compute_state_test_unit(state, txdata, indices, konfig):
    state.env.config = konfig
    s = state.snapshot()
    try:
        # Create the transaction
        tx = transactions.Transaction(
            nonce=parse_int_or_hex(txdata['nonce'] or b"0"),
            gasprice=parse_int_or_hex(txdata['gasPrice'] or b"0"),
            startgas=parse_int_or_hex(txdata['gasLimit'][indices["gas"]]
                                      or b"0"),
            to=decode_hex(remove_0x_head(txdata['to'])),
            value=parse_int_or_hex(txdata['value'][indices["value"]] or b"0"),
            data=decode_hex(remove_0x_head(txdata['data'][indices["data"]])))
        if 'secretKey' in txdata:
            tx.sign(decode_hex(remove_0x_head(txdata['secretKey'])))
        else:
            tx.v = parse_int_or_hex(txdata['v'])
        # Run it
        prev = state.to_dict()
        success, output = apply_transaction(state, tx)
        print("Applied tx")
    except InvalidTransaction as e:
        print("Exception: %r" % e)
        success, output = False, b''
    # state.set_code('0x3e180b1862f9d158abb5e519a6d8605540c23682', b'')
    state.commit()
    post = state.to_dict()
    # print('pozt', post)
    output_decl = {
        "hash": '0x' + encode_hex(state.trie.root_hash),
        "indexes": indices,
        "diff": mk_state_diff(prev, post)
    }
    state.revert(s)
    return output_decl
示例#9
0
 def to_snapshot(self, no_prevblocks=False):
     snapshot = dict()
     snapshot["state_root"] = "0x" + encode_hex(self.trie.root_hash)
     # Save non-state-root variables
     for k, default in STATE_DEFAULTS.items():
         default = copy.copy(default)
         v = getattr(self, k)
         if is_numeric(default):
             snapshot[k] = str(v)
         elif isinstance(default, (str, bytes)):
             snapshot[k] = "0x" + encode_hex(v)
         elif k == "prev_headers" and not no_prevblocks:
             snapshot[k] = [
                 prev_header_to_dict(h)
                 for h in v[:self.config["PREV_HEADER_DEPTH"]]
             ]
     return snapshot
示例#10
0
    def _make_keystore_json(self, password):
        """
        Generate the keystore json that follows the Version 3 specification:
        https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition#definition

        Uses pbkdf2 for password encryption, and AES-128-CTR as the cipher.
        """
        # Get the hash function and default parameters
        kdfparams = {
            "prf": "hmac-sha256",
            "dklen": 32,
            "c": 262144,
            "salt": encode_hex(os.urandom(16)),
        }

        # Compute derived key
        derivedkey = pbkdf2.PBKDF2(password, decode_hex(kdfparams["salt"]),
                                   kdfparams["c"],
                                   SHA256).read(kdfparams["dklen"])

        # Produce the encryption key and encrypt using AES
        enckey = derivedkey[:16]
        cipherparams = {"iv": encode_hex(os.urandom(16))}
        iv = int.from_bytes(decode_hex(cipherparams["iv"]), byteorder="big")
        ctr = Counter.new(128, initial_value=iv, allow_wraparound=True)
        encryptor = AES.new(enckey, AES.MODE_CTR, counter=ctr)
        c = encryptor.encrypt(self.identity.key)

        # Compute the MAC
        mac = sha3(derivedkey[16:32] + c)

        # Return the keystore json
        return {
            "crypto": {
                "cipher": "aes-128-ctr",
                "ciphertext": encode_hex(c),
                "cipherparams": cipherparams,
                "kdf": "pbkdf2",
                "kdfparams": kdfparams,
                "mac": encode_hex(mac),
                "version": 1,
            },
            "id": self.uuid,
            "version": 3,
        }
示例#11
0
def dict_to_prev_header(h):
    return FakeHeader(hash=parse_as_bin(h['hash']),
                      number=parse_as_int(h['number']),
                      timestamp=parse_as_int(h['timestamp']),
                      difficulty=parse_as_int(h['difficulty']),
                      gas_used=parse_as_int(h.get('gas_used', '0')),
                      gas_limit=parse_as_int(h['gas_limit']),
                      uncles_hash=parse_as_bin(
                          h.get('uncles_hash',
                                '0x' + encode_hex(BLANK_UNCLES_HASH))))
def compute_state_test_unit(state,
                            txdata,
                            indices,
                            konfig,
                            is_qkc_state,
                            qkc_env=None):
    state.env.config = konfig
    s = state.snapshot()
    if "transferTokenId" in txdata:
        transfer_token_id = parse_int_or_hex(
            txdata["transferTokenId"][indices["transferTokenId"]])
    else:
        transfer_token_id = token_id_encode("QKC")
    try:
        # Create the transaction
        tx = transactions.Transaction(
            nonce=parse_int_or_hex(txdata["nonce"] or b"0"),
            gasprice=parse_int_or_hex(txdata["gasPrice"] or b"0"),
            startgas=parse_int_or_hex(txdata["gasLimit"][indices["gas"]]
                                      or b"0"),
            to=decode_hex(remove_0x_head(txdata["to"])),
            value=parse_int_or_hex(txdata["value"][indices["value"]] or b"0"),
            data=decode_hex(remove_0x_head(txdata["data"][indices["data"]])),
            gas_token_id=token_id_encode("QKC"),
            transfer_token_id=transfer_token_id,
            # Should not set testing flag if testing QuarkChain state
            is_testing=not is_qkc_state,
        )
        tx.set_quark_chain_config(qkc_env.quark_chain_config)
        if "secretKey" in txdata:
            tx.sign(decode_hex(remove_0x_head(txdata["secretKey"])))
        else:
            tx._in_mutable_context = True
            tx.v = parse_int_or_hex(txdata["v"])
            tx._in_mutable_context = False
        # Run it
        prev = state.to_dict()
        success, output = apply_transaction(state,
                                            tx,
                                            tx_wrapper_hash=bytes(32))
    except InvalidTransaction as e:
        print("Exception: %r" % e)
        success, output = False, b""
    # touch coinbase, make behavior consistent with go-ethereum
    state.delta_token_balance(state.block_coinbase, token_id_encode("QKC"), 0)
    state.commit()
    post = state.to_dict()
    output_decl = {
        "hash": "0x" + encode_hex(state.trie.root_hash),
        "indexes": indices,
        "diff": mk_state_diff(prev, post),
    }
    state.revert(s)
    return output_decl
示例#13
0
def dict_to_prev_header(h):
    return FakeHeader(
        hash=parse_as_bin(h["hash"]),
        number=parse_as_int(h["number"]),
        timestamp=parse_as_int(h["timestamp"]),
        difficulty=parse_as_int(h["difficulty"]),
        gas_used=parse_as_int(h.get("gas_used", "0")),
        gas_limit=parse_as_int(h["gas_limit"]),
        uncles_hash=parse_as_bin(
            h.get("uncles_hash", "0x" + encode_hex(BLANK_UNCLES_HASH))),
    )
    def get_by_address(self, address):
        """Get an account by its address.

        Note that even if an account with the given address exists, it might not be found if it is
        locked. Also, multiple accounts with the same address may exist, in which case the first
        one is returned (and a warning is logged).

        :raises: `KeyError` if no matching account can be found
        """
        assert len(address) == 20
        accounts = [
            account for account in self.accounts if account.address == address
        ]
        if len(accounts) == 0:
            raise KeyError('account with address {} not found'.format(
                encode_hex(address)))
        elif len(accounts) > 1:
            log.warning('multiple accounts with same address found',
                        address=encode_hex(address))
        return accounts[0]
 def propose_path(self, address):
     return os.path.join(self.keystore_dir, encode_hex(address))
示例#16
0
 def __structlog__(self):
     return encode_hex(self.hash)
示例#17
0
 def __repr__(self):
     return "<Transaction(%s)>" % encode_hex(self.hash)[:4]
示例#18
0
def snapshot_form(val):
    if is_numeric(val):
        return str(val)
    elif is_string(val):
        return "0x" + encode_hex(val)