def EtherTxn(self, to_Address, value, nonce, gasPrice, gas):  #乙太幣交易
        if self.wt.PrivateKey(self.password):
            privateKey = self.wt.private
        else:
            return 'Password error'

        address = w3.toChecksumAddress(self.wt.Address())
        try:
            to_Address = w3.toChecksumAddress(to_Address)
        except:
            return "Address error"
        value = int(value * 10**18)
        try:
            txn = {#gas * price + value really means MAXGas * price.
            'from':address,
            'to':to_Address,
            'value':int(value),
            'gas':int(gas),
            'gasPrice':int(gasPrice),  # = gas*price+value
            'nonce':int(nonce),
            }
            # 簽名 送tmp回去給手機
            signed_txn = w3.eth.account.signTransaction(txn,
                                                        private_key=privateKey)
            tmp = signed_txn.rawTransaction
            print('type of tmp: ', type(tmp))
            # 加密存下來
            txhasg = w3.toHex(w3.sha3(signed_txn.rawTransaction))
        except:
            return "Value Error"
        return tmp.hex()
예제 #2
0
def build_receipt_proof(w3, txn_hash):
    receipt_trie = Trie(db={})
    receipt = w3.eth.getTransactionReceipt(txn_hash)
    block = w3.eth.getBlock(receipt.blockHash)
    for i, tr in enumerate(block.transactions):
        path = rlp.encode(i)
        sibling_receipt = w3.eth.getTransactionReceipt(tr.hex())
        value = get_rlp_receipt(sibling_receipt)
        receipt_trie.set(path, value)
        if i == receipt.transactionIndex:
            rlp_txn_receipt = value  # We are interested in this txn

    txn_path = rlp.encode(receipt.transactionIndex)
    parent_nodes = []
    t = receipt_trie
    parent_nodes.append(t.root_node)
    node = t.root_node
    nibs = nibbles.bytes_to_nibbles(txn_path)
    for nib in nibs:
        if len(node) == 2:  # Leaf node. We are done.
            break
        next_node = rlp.decode(t.db[node[nib]])
        parent_nodes.append(next_node)
        node = next_node

    rlp_parent_nodes = rlp.encode(parent_nodes)
    print('Calculated hash = %s' %
          HexBytes(w3.sha3(rlp.encode(t.root_node))).hex())
    print('Receipts root = %s' % HexBytes(block.receiptsRoot).hex())

    return rlp_txn_receipt, receipt.blockHash, txn_path, rlp_parent_nodes
예제 #3
0
def sign_state(state, private_key):
    def to_32byte_hex(val):
        return web3.toHex(web3.toBytes(val).rjust(32, b'\0'))

    state_hash = to_32byte_hex(web3.sha3(hexstr=state))
    state_hash = defunct_hash_message(hexstr=state_hash)
    sig = web3.eth.account.signHash((state_hash), private_key=private_key)

    return {
        'r': web3.toHex(sig.r),
        'v': sig.v,
        's': web3.toHex(sig.s),
        'state': state
    }
예제 #4
0
def check_packet(rules):
    tv = input("Message to verify\r\n")
    json1 = json.loads(tv)
    senderAddress = w3.eth.account.recoverHash(
        w3.sha3(text=str(json1['message'])),
        vrs=(json1['v'], json1['r'], json1['s']))

    print(senderAddress)
    print(rules)
    for rule in rules:
        if (rule[0] == senderAddress and rule[1] == localAccount.address
                and rule[2] == json1['message']['actionToExecute']):
            print("Action Accepted")
        else:
            print("Action Refused")
예제 #5
0
def index():
    get_info = contract_instance.get_ballance_of_depo()
    print(get_info)

    balance = token_instance.functions.balanceOf(default_account).call()
    symbol = token_instance.functions.symbol().call()
    print(balance)
    print(web3.toWei('10000','ether'))
    print(symbol)
    nonce = eth_provider.getTransactionCount(default_account)
    print(nonce)
    print('Ether to wei:',w3.toWei('1','ether'))
    print('Balance of contract:',token_instance.functions.balanceOf(contract_address).call())
    contract_address_from = web3.toChecksumAddress(contract_address)
    own_address = web3.toChecksumAddress(default_account)
    # address to '0x4776e07A2A155410F601e3e0bfBbA7242a35493a' 0x3143ae291f6f04d22affc9f66578eff22f47aef3

    txn = token_instance.functions.transfer(contract_address_from,w3.toWei('598.999','ether')).buildTransaction(
                                                              {
                                                               'chainId': 5777,
                                                               'gas': 1000000,
                                                               'gasPrice': w3.toWei('43', 'wei'),
                                                               'nonce': nonce, })
    print(txn)

    if 'private_key' in dict_values.keys():
        privat_key = dict_values['private_key']
    else:
        try:
            private_key_file = open('./private_key','r')
            privat_key = private_key.read()
        except:
            pass

    signed_txn = w3.eth.account.signTransaction(txn, private_key=privat_key)
    print(signed_txn)

    result = eth_provider.sendRawTransaction(signed_txn.rawTransaction)
    print(result)
    result_txn = w3.toHex(w3.sha3(signed_txn.rawTransaction))
    print(result_txn)


    return render_template('index.html', owner=default_account,token = token_address,smartAddress = contract_address)
예제 #6
0
 def EtherTxn(to_Address, value, nonce, gasPrice, gas):  #乙太幣交易
     privateKey = wt.PrivateKey()
     address = w3.toChecksumAddress(wt.PublicKey())
     to_Address = w3.toChecksumAddress(to_Address)
     txn = {#gas * price + value really means MAXGas * price.
      'from':address,
      'to':to_Address,
      'value':int(value),
      'gas':int(gas),
      'gasPrice':int(gasPrice),  # = gas*price+value
      'nonce':int(nonce),
     }
     # 簽名 送tmp回去給手機
     signed_txn = w3.eth.account.signTransaction(txn,
                                                 private_key=privateKey)
     tmp = signed_txn.rawTransaction
     # 加密存下來
     txhasg = w3.toHex(w3.sha3(signed_txn.rawTransaction))
     return tmp
예제 #7
0
파일: Manager.py 프로젝트: Topl/Heimdallr
def main():
    abi = abi_heimdall()
    bytecode = bytecode_heimdall()
    print("connected:", w3.isConnected())
    print("loading...")
    accounts = w3.eth.accounts
    w3.eth.defaultAccount = accounts[0]
    heimdall_contract = w3.eth.contract(abi=abi, bytecode=bytecode)
    with open("log.txt", "r") as f:
        if f.read() == "new deploy":
            tx_hash_heimdall_deployment = heimdall_contract.constructor(
            ).transact()
            tx_receipt_heimdall_deployment = w3.eth.waitForTransactionReceipt(
                tx_hash_heimdall_deployment)
            heimdall_contract_address = tx_receipt_heimdall_deployment.contractAddress
            with open("log.txt", "w") as fw:
                fw.write(heimdall_contract_address + "\n")
        else:
            f.seek(0)
            heimdall_contract_address = f.read(42)
            # load log data
            f.seek(0)
            for line in f.readlines()[1:]:
                clean_line = line.strip("\n")
                line_parts = line.split(" | ")
                line_parts[1] = literal_eval(line_parts[1])
                handle_log_line(line_parts, state_vars)
    print("deployment account:", w3.eth.defaultAccount)
    print("contract deployed to:", heimdall_contract_address)
    heimdall_contract = w3.eth.contract(address=heimdall_contract_address,
                                        abi=abi,
                                        bytecode=bytecode)
    # create event filters
    toggle_contract_open_event_hash = w3.sha3(
        text="ToggleContractOpenEvent(address,bool,bool)").hex()
    toggle_contract_open_event_filter = w3.eth.filter(
        filter_params={
            "address": heimdall_contract_address,
            "topics": [toggle_contract_open_event_hash]
        })
    deposit_event_hash = w3.sha3(
        text="DepositEvent(address,address,uint256,uint256,uint256)").hex()
    deposit_event_filter = w3.eth.filter(filter_params={
        "address": heimdall_contract_address,
        "topics": [deposit_event_hash]
    })
    start_withdrawal_event_hash = w3.sha3(
        text="StartWithdrawalEvent(address,address,uint256,uint256)").hex()
    start_withdrawal_event_filter = w3.eth.filter(
        filter_params={
            "address": heimdall_contract_address,
            "topics": [start_withdrawal_event_hash]
        })
    approve_withdrawal_event_hash = w3.sha3(
        text="ApproveWithdrawalEvent(address,address,uint256,uint256)").hex()
    approve_withdrawal_event_filter = w3.eth.filter(
        filter_params={
            "address": heimdall_contract_address,
            "topics": [approve_withdrawal_event_hash]
        })
    deny_withdrawal_event_hash = w3.sha3(
        text="DenyWithdrawalEvent(address,address,uint256,uint256)").hex()
    deny_withdrawal_event_filter = w3.eth.filter(
        filter_params={
            "address": heimdall_contract_address,
            "topics": [deny_withdrawal_event_hash]
        })
    set_deposit_fee_event_hash = w3.sha3(
        text="SetDepositFeeEvent(address,uint256,uint256)").hex()
    set_deposit_fee_event_filter = w3.eth.filter(
        filter_params={
            "address": heimdall_contract_address,
            "topics": [set_deposit_fee_event_hash]
        })
    set_withdrawal_fee_event_hash = w3.sha3(
        text="SetWithdrawalFeeEvent(address,uint256,uint256)").hex()
    set_withdrawal_fee_event_filter = w3.eth.filter(
        filter_params={
            "address": heimdall_contract_address,
            "topics": [set_withdrawal_fee_event_hash]
        })
    try:
        while True:
            print("\t--")
            heimdall_contract.functions.toggleContractOpen().transact()
            heimdall_contract.functions.setWithdrawalFee(50).transact()

            for event in toggle_contract_open_event_filter.get_new_entries():
                handle_toggle_contract_open_event(event["data"], state_vars)
                print("toggled", event)
            for event in deposit_event_filter.get_new_entries():
                handle_deposit_event(event["data"], state_vars)
            for event in start_withdrawal_event_filter.get_new_entries():
                handle_start_withdrawal_event(event["data"], heimdall_contract,
                                              state_vars)
            for event in approve_withdrawal_event_filter.get_new_entries():
                handle_approve_withdrawal_event(event["data"], state_vars)
            for event in deny_withdrawal_event_filter.get_new_entries():
                handle_deny_withdrawal_event(event["data"], state_vars)
            for event in set_deposit_fee_event_filter.get_new_entries():
                handle_set_deposit_fee_event(event["data"], state_vars)
            for event in set_withdrawal_fee_event_filter.get_new_entries():
                handle_set_withdrawal_fee_event(event["data"], state_vars)
            # update topl data
            time.sleep(2)
    except:
        if state_vars["contract_open"]:
            tx_toggle_contract_open(heimdall_contract)
예제 #8
0
contract_source_code = None
contract_source_code_file = 'cointoss.sol'

with open(contract_source_code_file, 'r') as file:
    contract_source_code = file.read()

#contract_compiled = compile_source(contract_source_code)
project_root = os.path.dirname(os.path.dirname(__file__))
#, os.path.join(project_root,os.path.join("CTtoken.sol"))])
contract_compiled = compile_files(["/home/yq/Desktop/Blockchain/11_src/webapp/sale.sol"])
print(contract_compiled)
contract_interface = contract_compiled['/home/yq/Desktop/Blockchain/11_src/webapp/sale.sol:sale']
cointoss = w3.eth.contract(abi=contract_interface['abi'], 
                          bytecode=contract_interface['bin'])
secret_hash = w3.sha3(3)
print((secret_hash).hex())
# w3.personal.unlockAccount(w3.eth.accounts[0], '') #  Not needed with Ganache
tx_hash = cointoss.constructor(1586822400,1586822900,10).transact({'from':w3.eth.accounts[0]})
#{'from':w3.eth.accounts[0], 'value': w3.toWei(1,"ether")}
tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)

# Contract Object
cointoss = w3.eth.contract(address=tx_receipt.contractAddress, abi=contract_interface['abi'])

#w3.eth.sendTransaction({'to': "0xBa184FE4082814647520288C10b8E2a2a7E8A811", 'from':w3.eth.coinbase, 'value': w3.toWei(3,"ether")})
#w3.eth.sendTransaction({'to': "0x09E59fD3BeCa2914Ff15824E6b4Db9BE9a3a780F", 'from':w3.eth.coinbase, 'value': w3.toWei(3,"ether")})

# Web service initialization
@app.route('/')
@app.route('/index')
예제 #9
0
 def merkle_hash(self):
     return w3.sha3(rlp.encode(self))
예제 #10
0
 def hash(self) -> Keccak256:
     return w3.sha3(rlp.encode(self, UnsignedBlock))
예제 #11
0
from web3.auto import w3
import json
import base64

acct = w3.eth.account.create('ACCOUNT1')

priKey = acct.privateKey

acct2 = w3.eth.account.privateKeyToAccount(priKey)

msgDict = {}
msgDict['src'] = "src"
msgDict['dst'] = "dst"
msgDict['sct'] = "act"

message = w3.sha3(text=str(msgDict))

signatureZ = w3.eth.account.signHash(message, acct.privateKey)

print(message)
sing = signatureZ['signature'].decode("ISO-8859-1")

senderAddress = w3.eth.account.recoverHash(message,
                                           signature=sing.encode("ISO-8859-1"))

print(acct2.address)
print(senderAddress)

print(signatureZ)

r = signatureZ['r']
 def hash(self):
     if self.prev_block != 0:
         ret = w3.sha3(rlp.encode(self, UnsignedTransaction))
     else:
         ret = w3.soliditySha3(['uint64'], [self.uid])
     return ret
예제 #13
0
    authenticationSet['keystore'] = accountDump
    #ownerAddress = input("Insert the owner address\r\n")
    with open('auth-s.json', 'w') as f:
        json.dump(authenticationSet, f)
else:
    #case it exists
    with open('auth-s.json', 'r') as f:
        datastore = json.load(f)
    privateKey = w3.eth.account.decrypt(datastore['keystore'], localPassword)
    localAccount = w3.eth.account.privateKeyToAccount(privateKey)

print(localAccount.address)

packetToSend = {}
packetToSend['actionToExecute'] = input("Insert the sensed information\r\n")
packetToSend['timestamp'] = int(time.time())
packetToSend['nonce'] = random.randint(9999, 99999)

packet_string = str(packetToSend)
messageSHA3 = w3.sha3(text=packet_string)
signature = w3.eth.account.signHash(messageSHA3, localAccount.privateKey)

completePacket = {}

completePacket['message'] = packetToSend
completePacket['v'] = signature['v']
completePacket['r'] = signature['r']
completePacket['s'] = signature['s']

print(json.dumps(completePacket))
예제 #14
0
 def hash(self):
     return w3.sha3(rlp.encode(self, UnsignedBlock))