def verify_eth_get_proof(proof, root):
    trie_root = Binary.fixed_length(32, allow_empty=True)
    hash32 = Binary.fixed_length(32)

    class _Account(rlp.Serializable):
        fields = [('nonce', big_endian_int), ('balance', big_endian_int),
                  ('storage', trie_root), ('code_hash', hash32)]

    acc = _Account(proof.nonce, proof.balance,
                   w3.toBytes(hexstr=w3.toHex(proof.storageHash)),
                   w3.toBytes(hexstr=w3.toHex(proof.codeHash)))
    rlp_account = rlp.encode(acc)
    trie_key = keccak(w3.toBytes(hexstr=proof.address))
    trie_proof = format_proof_nodes(proof.accountProof)

    leaf = HexaryTrie.get_from_proof(root, trie_key, trie_proof)

    if acc == b'':
        print("Verify that the account does not exist")
    else:
        assert rlp_account == leaf, "Failed to verify account proof {}".format(
            proof.address)
        print("Succeed to verify account proof {}".format(proof.address))
    return True
Transactions = Sequence[_Transaction]
TrieRootAndData = Tuple[Hash32, Dict[Hash32, bytes]]

block = w3.eth.getBlock(8290728)
trie = HexaryTrie(db={})
assert trie.root_hash == BLANK_ROOT_HASH
print(w3.toHex(trie.root_hash))

# Generate Merkle tree
txs = []
B = len(block.transactions)
print("The block has %d transactions" % B)
for key in range(B):
    tx = w3.eth.getTransaction(block.transactions[key])
    raw_tx = _Transaction(tx.nonce, tx.gasPrice, tx.gas,
                          w3.toBytes(hexstr=tx.to), tx.value,
                          w3.toBytes(hexstr=w3.toHex(hexstr=tx.input)), tx.v,
                          w3.toInt(tx.r), w3.toInt(tx.s))
    rlp_tx = rlp.encode(raw_tx)
    assert tx.hash == keccak(rlp_tx)
    txs.append(raw_tx)
    trie.set(rlp.encode(key), rlp_tx)
    # print(rlp_tx)
assert block.transactionsRoot == trie.root_hash
print(w3.toHex(trie.root_hash))

# Generate Merkle tree proof for per each node
proofs = []
for key in range(B):
    proof = trie.get_proof(rlp.encode(key))
    proofs.append(proof)
示例#3
0
def fund_PAC_(
    signer: str,
    total: float,
    escrow: float,
    funder_pubkey: str,
    funder_privkey: str,
    nonce: int,
) -> str:
    print(f"Funding PAC  signer: {signer}, total: {total}, escrow: {escrow} ")

    lottery_addr = w3.toChecksumAddress(os.environ['LOTTERY'])
    token_addr = w3.toChecksumAddress(os.environ['TOKEN'])
    verifier_addr = w3.toChecksumAddress(os.environ['VERIFIER'])

    lottery_main = w3.eth.contract(
        abi=lottery_abi,
        address=lottery_addr,
    )
    token_main = w3.eth.contract(
        abi=token_abi,
        address=token_addr,
    )

    print(f"Funder nonce: {nonce}")

    print(f"Assembling approve transaction:")
    approve_txn = token_main.functions.approve(
        lottery_addr,
        total,
    ).buildTransaction(
        {
            'chainId': 1,
            'from': funder_pubkey,
            'gas': 50000,
            'gasPrice': w3.toWei('8', 'gwei'),
            'nonce': nonce,
        }
    )
    print(approve_txn)

    print(f"Funder signed transaction:")
    approve_txn_signed = w3.eth.account.sign_transaction(
        approve_txn, private_key=funder_privkey)
    print(approve_txn_signed)

    print(f"Submitting approve transaction:")

    approve_txn_hash = w3.eth.sendRawTransaction(
        approve_txn_signed.rawTransaction)
    print(f"Submitted approve transaction with hash: {approve_txn_hash.hex()}")

    nonce = nonce + 1
    print(f"Funder nonce: {nonce}")

    print(f"Assembling bind transaction:")
    bind_txn = lottery_main.functions.bind(signer, verifier_addr, w3.toBytes(0)
        ).buildTransaction({'chainId': 1, 'from': funder_pubkey, 'gas': 200000, 'gasPrice': w3.toWei('8', 'gwei'), 'nonce': nonce,}
    )
    print(bind_txn)

    print(f"Funder signed transaction:")
    bind_txn_signed = w3.eth.account.sign_transaction(bind_txn, private_key=funder_privkey)
    print(bind_txn_signed)

    print(f"Submitting bind transaction:")
    bind_txn_hash = w3.eth.sendRawTransaction(bind_txn_signed.rawTransaction)
    print(f"Submitted bind transaction with hash: {bind_txn_hash.hex()}")

    nonce = nonce + 1
    print(f"Funder nonce: {nonce}")

    print(f"Assembling funding transaction:")
    funding_txn = lottery_main.functions.push(
        signer,
        total,
        escrow
    ).buildTransaction(
        {
            'chainId': 1,
            'from': funder_pubkey,
            'gas': 200000,
            'gasPrice': w3.toWei('8', 'gwei'),
            'nonce': nonce,
        }
    )
    print(funding_txn)

    print(f"Funder signed transaction:")
    funding_txn_signed = w3.eth.account.sign_transaction(
        funding_txn, private_key=funder_privkey)
    print(funding_txn_signed)

    print(f"Submitting funding transaction:")
    txn_hash: str = w3.eth.sendRawTransaction(
        funding_txn_signed.rawTransaction).hex()
    print(f"Submitted funding transaction with hash: {txn_hash}")
    return txn_hash
示例#4
0
def fund_PAC_(signer, total, escrow, funder_pubkey, funder_privkey):


	print(f"Funding PAC  signer: {signer}, total: {total}, escrow: {escrow} ");

	print("Creating Token contract object from abi.");
	Token = w3.eth.contract(abi=token_abi)

	print("Creating Lottery contract object from abi.");
	Lottery = w3.eth.contract(abi=lottery_abi)

	print("Lottery functions:");
	print( Lottery.all_functions() )

	lottery_address = '0xb02396f06CC894834b7934ecF8c8E5Ab5C1d12F1'
	verifier_address = '0x5D18Fe86BF42a3b2DdaEbDF7FD8Bc0578EAB71f7';
	token_main = Token(address = '0x4575f41308EC1483f3d399aa9a2826d74Da13Deb')
	lottery_main = Lottery(address = lottery_address)


	#funder.privateKey

	#nonce = w3.eth.getTransactionCount('0x464e537a24C76887599a9a9F96cE56d14505f93A')

	nonce = w3.eth.getTransactionCount(funder_pubkey);
	print(f"Funder nonce: {nonce}");

	print(f"Assembling approve transaction:");
	approve_txn = token_main.functions.approve(lottery_address, total
		).buildTransaction({'chainId': 1, 'from': funder_pubkey, 'gas': 50000, 'gasPrice': w3.toWei('8', 'gwei'), 'nonce': nonce,}
	)
	print(approve_txn);

	print(f"Funder signed transaction:");
	approve_txn_signed = w3.eth.account.sign_transaction(approve_txn, private_key=funder_privkey)
	print(approve_txn_signed);

	print(f"Submitting approve transaction:");	

	txn_hash = w3.eth.sendRawTransaction(approve_txn_signed.rawTransaction);
	print(f"Submitted transaction with hash: {txn_hash.hex()}");

	"""
	txn_receipt = None
	count = 0
	while txn_receipt is None and (count < 30):
		try:
			txn_receipt = w3.eth.getTransactionReceipt(txn_hash)
		except web3.exceptions.TransactionNotFound:
			time.sleep(10)

	print(txn_receipt)
	if txn_receipt is None:
		print("Failed to get txn receipt!");
	"""


	nonce = nonce + 1;
	print(f"Funder nonce: {nonce}");

	print(f"Assembling bind transaction:");
	funding_txn = lottery_main.functions.bind(signer, verifier_address, w3.toBytes(0)
		).buildTransaction({'chainId': 1, 'from': funder_pubkey, 'gas': 200000, 'gasPrice': w3.toWei('8', 'gwei'), 'nonce': nonce,}
	)
	print(funding_txn);

	print(f"Funder signed transaction:");
	funding_txn_signed = w3.eth.account.sign_transaction(funding_txn, private_key=funder_privkey)
	print(funding_txn_signed);

	print(f"Submitting transaction:");
	txn_hash = w3.eth.sendRawTransaction(funding_txn_signed.rawTransaction);
	print(f"Submitted transaction with hash: {txn_hash.hex()}");





	nonce = nonce + 1;
	print(f"Funder nonce: {nonce}");

	print(f"Assembling funding transaction:");
	funding_txn = lottery_main.functions.push(signer, total, escrow
		).buildTransaction({'chainId': 1, 'from': funder_pubkey, 'gas': 200000, 'gasPrice': w3.toWei('8', 'gwei'), 'nonce': nonce,}
	)
	print(funding_txn);

	print(f"Funder signed transaction:");
	funding_txn_signed = w3.eth.account.sign_transaction(funding_txn, private_key=funder_privkey)
	print(funding_txn_signed);

	print(f"Submitting funding transaction:");
	txn_hash = w3.eth.sendRawTransaction(funding_txn_signed.rawTransaction);
	print(f"Submitted transaction with hash: {txn_hash.hex()}");

class _BlockHeader(rlp.Serializable):
    fields = [('parent_hash', hash32), ('uncles_hash', hash32),
              ('coinbase', address), ('state_root', trie_root),
              ('transaction_root', trie_root), ('receipt_root', trie_root),
              ('bloom', uint256), ('difficulty', big_endian_int),
              ('block_number', big_endian_int), ('gas_limit', big_endian_int),
              ('gas_used', big_endian_int), ('timestamp', big_endian_int),
              ('extra_data', binary), ('mix_hash', binary),
              ('nonce', Binary(8, allow_empty=True))]


block = w3.eth.getBlock(8290728)

raw_block = _BlockHeader(w3.toBytes(hexstr=w3.toHex(block.parentHash)),
                         w3.toBytes(hexstr=w3.toHex(block.sha3Uncles)),
                         w3.toBytes(hexstr=block.miner),
                         w3.toBytes(hexstr=w3.toHex(block.stateRoot)),
                         w3.toBytes(hexstr=w3.toHex(block.transactionsRoot)),
                         w3.toBytes(hexstr=w3.toHex(block.receiptsRoot)),
                         w3.toInt(block.logsBloom), block.difficulty,
                         block.number, block.gasLimit, block.gasUsed,
                         block.timestamp, block.extraData, block.mixHash,
                         block.nonce)

rlp_block = rlp.encode(raw_block)

assert keccak(rlp_block) == block.hash

print(True)
def format_proof_nodes(proof):
    trie_proof = []
    for rlp_node in proof:
        trie_proof.append(rlp.decode(w3.toBytes(hexstr=w3.toHex(rlp_node))))
    return trie_proof