コード例 #1
0
def Transaction_out(private_key, toaddr, value, gas, gasprice):
    print(private_key)
    acct = Account.privateKeyToAccount(private_key)
    print(acct)
    public_key = acct.address
    print(public_key)
    nonce = requests.get(
        "https://waltonchain.net:18950/api/getSendTransactionNonce/"+public_key).json()["send_nonce"]
    print(nonce)
    transaction = {
        'to': toaddr,
        'value': int(float(value) * (10 ** 18)),
        'gas': int(gas),
        'gasPrice': int(float(gasprice) * (10 ** 18)),
        'nonce': nonce,
        'chainId': 15
    }
    print(transaction)
    #key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318'
    signed = w3.eth.account.signTransaction(transaction, private_key)
    print(w3.toHex(signed.rawTransaction))
    tx_hash = requests.get(
        "https://waltonchain.net:18950/api/sendRawTransaction/" + w3.toHex(signed.rawTransaction)).json()
    print(tx_hash)

    return (1, tx_hash['tx_hash'])
コード例 #2
0
    def raw_txn(self, addr, txn_data, action):
        nonce = self.web3_obj.eth.getTransactionCount(self.pub_key)
        gas = self.web3_obj.eth.gasPrice
        base_trans = {
            'to': addr,
            'from': self.pub_key,
            'data': txn_data,
            'gasPrice': gas,
            'chainId': 1,
            'value': 0,
            'nonce': nonce
        }
        gas_limit = self.web3_obj.eth.estimateGas(base_trans)
        base_trans['gas'] = gas_limit
        base_trans.pop('from', 0)

        signed = w3.eth.account.signTransaction(base_trans, self.priv_key)
        ret = self.web3_obj.eth.sendRawTransaction(signed.rawTransaction)
        print('https://etherscan.io/tx/%s' % w3.toHex(ret))
        outrow = [
            dt.datetime.now().strftime('%c'), action,
            'https://etherscan.io/tx/%s' % w3.toHex(ret)
        ]
        with open(self.actionlog_path, 'a', newline='') as f:
            writer = csv.writer(f)
            writer.writerow(outrow)
コード例 #3
0
ファイル: approveTest.py プロジェクト: fcgiin/NaturalDAO
def approve():
    path = dirname(dirname(abspath(__file__))) + '/abi/NDAOToken.json'
    contract_abi = loads(open(path).read())
    path = dirname(dirname(abspath(__file__))) + '/address/address.json'
    allAddress = loads(open(path).read())
    contract_address = allAddress['NDAOToken.py']
    ndaoContract = w3.eth.contract(address=contract_address, abi=contract_abi)
    path = dirname(dirname(abspath(__file__))) + '/abi/Ico.json'
    contract_abi = loads(open(path).read())
    tokenContract = w3.eth.contract(address=token_address, abi=contract_abi)
    nonce = w3.eth.getTransactionCount(my_address)
    unicorn_txn = ndaoContract.functions.approve(exchange_address, approve_amount).buildTransaction({
        'nonce': nonce,
        'gas': 200000

    })
    signed_txn = w3.eth.account.signTransaction(
        unicorn_txn, private_key=private_key)
    hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
    print("稳定币授权交易已经发送,请耐心等待并查询,hash值为:", w3.toHex(hash))
    nonce = nonce + 1
    unicorn_txn = tokenContract.functions.approve(exchange_address, approve_amount).buildTransaction({
        'nonce': nonce,
        'gas': 200000

    })
    signed_txn = w3.eth.account.signTransaction(
        unicorn_txn, private_key=private_key)
    hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
    print("ICO代币授权交易已经发送,请耐心等待并查询,hash值为:", w3.toHex(hash))
コード例 #4
0
def Transaction_out(private_key, toaddr, value, gas, gasprice, nonce):
    toaddr = w3.toChecksumAddress(toaddr)
    acct = Account.privateKeyToAccount(private_key)
    #public_key = acct.address
    transaction = {
        'to': toaddr,
        'value': int(Decimal(value) * (10 ** 18)),
        'gas': int(gas),
        'gasPrice': int(Decimal(gasprice) * (10 ** 18)),
        'nonce': nonce,
        'chainId': 15
    }
    print(transaction)
    #key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318'
    try:
        signed = w3.eth.account.signTransaction(transaction, private_key)
        print("sendData :" + w3.toHex(signed.rawTransaction))
    except Exception as err:
        print("signTransaction Error : " + str(err))
        return (False, nonce, "")

    try:
        print("jjjjjjjjjjjjjjnonce : " + str(nonce))
        tx_hash = requests.get("https://waltonchain.net:18950/api/sendRawTransaction/" + w3.toHex(signed.rawTransaction)).json()
    except Exception as err:
        print("sendRawTransaction Error : " + str(err))
        return (False,nonce,str(err))

    #判断如果是nonce too low的错误,则将nonce的值自动+1 再请求
    if "error" in tx_hash.keys():
        try:
            while tx_hash["error"] == "nonce too low":
                nonce += 1
                transaction = {
                    'to': toaddr,
                    'value': int(Decimal(value) * (10 ** 18)),
                    'gas': int(gas),
                    'gasPrice': int(Decimal(gasprice) * (10 ** 18)),
                    'nonce': nonce,
                    'chainId': 15
                }
                signed = w3.eth.account.signTransaction(transaction, private_key)
                newtx_hash = requests.get(
                    "https://waltonchain.net:18950/api/sendRawTransaction/" + w3.toHex(signed.rawTransaction)).json()
                if "error" not in newtx_hash.keys():
                    return (True, nonce, newtx_hash["tx_hash"])
        except Exception as err:
            print("re Transaction error : " + str(err))
            return (False, nonce, str(err))
        return (False, nonce, tx_hash["error"])
    return  (True,nonce,tx_hash["tx_hash"])
コード例 #5
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
    }
コード例 #6
0
def cancel():
    path = dirname(dirname(abspath(__file__))) + '/abi/Ico.json'
    contract_abi = loads(open(path).read())
    myContract = w3.eth.contract(address=icoAddress, abi=contract_abi)
    nonce = w3.eth.getTransactionCount(my_address)
    if isCancel:
        unicorn_txn = myContract.functions.cancelICO().buildTransaction({
            'nonce':
            nonce,
            'gas':
            400000
        })
    else:
        unicorn_txn = myContract.functions.submitICO().buildTransaction({
            'nonce':
            nonce,
            'gas':
            400000
        })
    try:
        signed_txn = w3.eth.account.signTransaction(unicorn_txn,
                                                    private_key=private_key)
        hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
        print("取消ICO交易已经发送,请耐心等待并查询,hash值为:", w3.toHex(hash))
    except Exception:
        print("交易失败")
コード例 #7
0
def buildsignedOrder(orderId):
    message_hashOrder = defunct_hash_message(hexstr=orderId)
    signed_msgOrder = w3.eth.account.signHash(message_hashOrder,
                                              private_key=private_key)
    signed_msgOrder = signed_msgOrder.signature
    signatureOrder = w3.toHex(signed_msgOrder)
    return signatureOrder
コード例 #8
0
def test():
    path = dirname(dirname(abspath(__file__))) + '/abi/Exchange.json'
    contract_abi = loads(open(path).read())
    myContract = w3.eth.contract(address=exchange1_address, abi=contract_abi)
    nonce = w3.eth.getTransactionCount(my_address)
    deadline = math.floor(time.time()) + 10 * 60
    if isTransfer:
        unicorn_txn = myContract.functions.tokenToExchangeTransferInput(
            5 * 10**3, 1, 1, deadline, transfer_address,
            exchange2_address).buildTransaction({
                'nonce': nonce,
                'gas': 400000
            })
    else:
        unicorn_txn = myContract.functions.tokenToExchangeSwapInput(
            5 * 10**3, 1, 1, deadline, exchange2_address).buildTransaction({
                'nonce':
                nonce,
                'gas':
                400000
            })

    signed_txn = w3.eth.account.signTransaction(unicorn_txn,
                                                private_key=private_key)
    hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
    print("币币交易已经发送,请耐心等待并查询,hash值为:", w3.toHex(hash))
コード例 #9
0
ファイル: withdraw.py プロジェクト: fcgiin/NaturalDAO
def withdraw():
    path = dirname(dirname(abspath(__file__))) + '/abi/Ico.json'
    contract_abi = loads(open(path).read())
    myContract = w3.eth.contract(address=icoAddress, abi=contract_abi)
    myDeposit = myContract.functions.depositBalanceOfUser(my_address).call()
    print("我的投资金额度为:", myDeposit)
    nonce = w3.eth.getTransactionCount(my_address)
    unicorn_txn = myContract.functions.safeWithdrawal().buildTransaction({
        'nonce':
        nonce,
        'gasPrice':
        w3.toWei(10, 'gwei'),
        'gas':
        400000
    })
    try:
        signed_txn = w3.eth.account.signTransaction(unicorn_txn,
                                                    private_key=private_key)
        hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
        print("提币交易已经发送,请耐心等待并查询,hash值为:", w3.toHex(hash))
        myDeposit = myContract.functions.depositBalanceOfUser(
            my_address).call()
        print("我的投资金额度为:", myDeposit)
    except Exception:
        print("交易失败")
コード例 #10
0
def buildUnsignedOrder(message):
    #print("message: ", message)
    message_hash = defunct_hash_message(text=message)
    signed_msg = w3.eth.account.signHash(message_hash, private_key=private_key)
    signed_msg = signed_msg.signature
    signature = w3.toHex(signed_msg)
    return signature
コード例 #11
0
ファイル: app.py プロジェクト: xoolo-eng/airdrop
def show_block(block):
    transactions = block.get("transactions")
    transactions_template = ""
    for transaction_hash in transactions:
        transactions_template += show_transaction(transaction_hash)
    block_template = """
        \r#############  Block {0} ####################
        \rTime Stamp: . {1}
        \rHash: ....... {2}
        \rAuthor: ..... {3}
        \rSize: ....... {4}
        \rGas Limit: .. {5}
        \rGas Used: ... {6}
        \rTransactions:
            {7}
        \r##############  End {0}   ###################
    """.format(
        block.get("number"),
        time.ctime(block.get("timestamp")),
        parity.toHex(block.get("hash")),
        block.get("author"),
        block.get("size"),
        block.get("gasLimit"),
        block.get("gasUsed"),
        transactions_template
    )
    print(block_template)
コード例 #12
0
ファイル: app.py プロジェクト: xoolo-eng/airdrop
def show_transaction(hash_transaction):
    transaction = get_transaction_by_hash(hash_transaction)
    isContract = False
    isCreated = False
    try:
        if parity.eth.getCode(str(transaction.get("to"))):
            isContract = True
    except Exception:
        isCreated = True
        isContract = True
    transaction_template = """
        _____________________________________________
        Hash: ......... {0}
        Block Number: . {1}
        From: ......... {2}
        To: ........... {3} {9}
        Value: ........ {4}
        Gas Limit: .... {5}
        Gas Used: ..... {6}
        Gas Prise: .... {7}
        Input Data: ... {8}
        _____________________________________________
    """.format(
        parity.toHex(transaction.get("hash")),
        transaction.get("blockNumber"),
        transaction.get("from"),
        transaction.get("to") if not isCreated else "Created {} ".format(transaction.get("to")),
        transaction.get("value"),
        transaction.get("gasLimit"),
        transaction.get("gas"),
        transaction.get("gasPrice"),
        transaction.get("input"),
        "Contract" if isContract else ""
    )
    return transaction_template
コード例 #13
0
def Generate_Three_Key(password1, password2):
    if password1 == password2:
        pass1 = password1
        pass2 = password2
        if len(pass1) < 6:
            print('less than 6')
            return (0, 10000)
        else:
            acct = Account.create(password1)
            public_key = acct.address
            private_key = acct.privateKey
            encrypted = Account.encrypt(private_key, password1)
            # cmd = 'ma -genkey ' + '-pass ' + password2
            # a = subprocess.getstatusoutput(cmd)
            # if a[0] == 0:
            #     ret = (a[1].split('{')[1].split('}')[0], a[1].split('{')[2].split('}')[0])
            #     # return ret      
            #     acct = Account.privateKeyToAccount(ret[1])
            #     public_key = acct.address
            #     encrypted = Account.encrypt(ret[1], password2)
            #     return (1, [public_key, ret[1], json.dumps(encrypted),ret[0]])
            return (1, [public_key, w3.toHex(private_key), json.dumps(encrypted)])
    else:
        print('wrong')
        return (0, 10001)
コード例 #14
0
    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()
コード例 #15
0
 def signMessage(self, message):
     try:
         hashedMessage = dhm(text=message)
         signedMessage = w3.eth.account.signHash(hashedMessage, private_key=self.privateKey)
         signature = w3.toHex(signedMessage.signature)
         return signature
     except Exception as e:
         print(e)
コード例 #16
0
 def signOrder(self, orderId):
     try:
         hashedOrder = dhm(hexstr=orderId)
         signedOrder = w3.eth.account.signHash(hashedOrder, private_key=self.privateKey)
         signature = w3.toHex(signedOrder.signature)
         return signature
     except Exception as e:
         print(e)
コード例 #17
0
    def write(self):
        with open(self.path, 'w+') as f:
            f.write(json.dumps({
                'address': self.account.address,
                'privkey': w3.toHex(self.account.privateKey)
            }, indent=4))

        if self.debug:
            fmt_debug(INFO='Wallet created', PATH=self.path)
コード例 #18
0
def decode_transaction_raw(transaction_raw: str) -> dict:
    """
    Decode XinFin transaction raw.

    :param transaction_raw: XinFin transaction raw.
    :type transaction_raw: str

    :returns: dict -- XinFin decoded transaction.

    >>> from pyxdc.utils import decode_transaction_raw
    >>> decode_transaction_raw(transaction_raw="0xf90703058504a817c800831e84808080b906b0608060405234801561001057600080fd5b506040518060400160405280600581526020017f48656c6c6f0000000000000000000000000000000000000000000000000000008152506000908051906020019061005c929190610062565b50610166565b82805461006e90610105565b90600052602060002090601f01602090048101928261009057600085556100d7565b82601f106100a957805160ff19168380011785556100d7565b828001600101855582156100d7579182015b828111156100d65782518255916020019190600101906100bb565b5b5090506100e491906100e8565b5090565b5b808211156101015760008160009055506001016100e9565b5090565b6000600282049050600182168061011d57607f821691505b6020821081141561013157610130610137565b5b50919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b61053b806101756000396000f3fe608060405234801561001057600080fd5b50600436106100415760003560e01c8063a413686214610046578063cfae321714610062578063ef690cc014610080575b600080fd5b610060600480360381019061005b91906102e3565b61009e565b005b61006a6100b8565b604051610077919061035d565b60405180910390f35b61008861014a565b604051610095919061035d565b60405180910390f35b80600090805190602001906100b49291906101d8565b5050565b6060600080546100c790610433565b80601f01602080910402602001604051908101604052809291908181526020018280546100f390610433565b80156101405780601f1061011557610100808354040283529160200191610140565b820191906000526020600020905b81548152906001019060200180831161012357829003601f168201915b5050505050905090565b6000805461015790610433565b80601f016020809104026020016040519081016040528092919081815260200182805461018390610433565b80156101d05780601f106101a5576101008083540402835291602001916101d0565b820191906000526020600020905b8154815290600101906020018083116101b357829003601f168201915b505050505081565b8280546101e490610433565b90600052602060002090601f016020900481019282610206576000855561024d565b82601f1061021f57805160ff191683800117855561024d565b8280016001018555821561024d579182015b8281111561024c578251825591602001919060010190610231565b5b50905061025a919061025e565b5090565b5b8082111561027757600081600090555060010161025f565b5090565b600061028e610289846103a4565b61037f565b9050828152602081018484840111156102a657600080fd5b6102b18482856103f1565b509392505050565b600082601f8301126102ca57600080fd5b81356102da84826020860161027b565b91505092915050565b6000602082840312156102f557600080fd5b600082013567ffffffffffffffff81111561030f57600080fd5b61031b848285016102b9565b91505092915050565b600061032f826103d5565b61033981856103e0565b9350610349818560208601610400565b610352816104f4565b840191505092915050565b600060208201905081810360008301526103778184610324565b905092915050565b600061038961039a565b90506103958282610465565b919050565b6000604051905090565b600067ffffffffffffffff8211156103bf576103be6104c5565b5b6103c8826104f4565b9050602081019050919050565b600081519050919050565b600082825260208201905092915050565b82818337600083830152505050565b60005b8381101561041e578082015181840152602081019050610403565b8381111561042d576000848401525b50505050565b6000600282049050600182168061044b57607f821691505b6020821081141561045f5761045e610496565b5b50919050565b61046e826104f4565b810181811067ffffffffffffffff8211171561048d5761048c6104c5565b5b80604052505050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b6000601f19601f830116905091905056fea264697066735822122002786b5114bea14354170503b8bffe80a17bb5e4610cb41deca549935965f30864736f6c634300080300331ca0f2704e20656acf4b067c23ff6e7e2bf8e9b6f75383c408607fce7f90ef39aedba07612be142f5202b3970ee9b4c821bd95df4eb007735acc9c145b0d204d697f8c")
    {'hash': '0x57232e7e3f0e4f5f49cad5074bea10c98ee18efd4371e15c163560b8bc8ebb40', 'from': '0x68bF25F60508C2820d3D72E1806503F0955eFf94', 'to': None, 'nonce': 5, 'gas': 2000000, 'gas_price': 20000000000, 'value': 0, 'data': '0x608060405234801561001057600080fd5b506040518060400160405280600581526020017f48656c6c6f0000000000000000000000000000000000000000000000000000008152506000908051906020019061005c929190610062565b50610166565b82805461006e90610105565b90600052602060002090601f01602090048101928261009057600085556100d7565b82601f106100a957805160ff19168380011785556100d7565b828001600101855582156100d7579182015b828111156100d65782518255916020019190600101906100bb565b5b5090506100e491906100e8565b5090565b5b808211156101015760008160009055506001016100e9565b5090565b6000600282049050600182168061011d57607f821691505b6020821081141561013157610130610137565b5b50919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b61053b806101756000396000f3fe608060405234801561001057600080fd5b50600436106100415760003560e01c8063a413686214610046578063cfae321714610062578063ef690cc014610080575b600080fd5b610060600480360381019061005b91906102e3565b61009e565b005b61006a6100b8565b604051610077919061035d565b60405180910390f35b61008861014a565b604051610095919061035d565b60405180910390f35b80600090805190602001906100b49291906101d8565b5050565b6060600080546100c790610433565b80601f01602080910402602001604051908101604052809291908181526020018280546100f390610433565b80156101405780601f1061011557610100808354040283529160200191610140565b820191906000526020600020905b81548152906001019060200180831161012357829003601f168201915b5050505050905090565b6000805461015790610433565b80601f016020809104026020016040519081016040528092919081815260200182805461018390610433565b80156101d05780601f106101a5576101008083540402835291602001916101d0565b820191906000526020600020905b8154815290600101906020018083116101b357829003601f168201915b505050505081565b8280546101e490610433565b90600052602060002090601f016020900481019282610206576000855561024d565b82601f1061021f57805160ff191683800117855561024d565b8280016001018555821561024d579182015b8281111561024c578251825591602001919060010190610231565b5b50905061025a919061025e565b5090565b5b8082111561027757600081600090555060010161025f565b5090565b600061028e610289846103a4565b61037f565b9050828152602081018484840111156102a657600080fd5b6102b18482856103f1565b509392505050565b600082601f8301126102ca57600080fd5b81356102da84826020860161027b565b91505092915050565b6000602082840312156102f557600080fd5b600082013567ffffffffffffffff81111561030f57600080fd5b61031b848285016102b9565b91505092915050565b600061032f826103d5565b61033981856103e0565b9350610349818560208601610400565b610352816104f4565b840191505092915050565b600060208201905081810360008301526103778184610324565b905092915050565b600061038961039a565b90506103958282610465565b919050565b6000604051905090565b600067ffffffffffffffff8211156103bf576103be6104c5565b5b6103c8826104f4565b9050602081019050919050565b600081519050919050565b600082825260208201905092915050565b82818337600083830152505050565b60005b8381101561041e578082015181840152602081019050610403565b8381111561042d576000848401525b50505050565b6000600282049050600182168061044b57607f821691505b6020821081141561045f5761045e610496565b5b50919050565b61046e826104f4565b810181811067ffffffffffffffff8211171561048d5761048c6104c5565b5b80604052505050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b6000601f19601f830116905091905056fea264697066735822122002786b5114bea14354170503b8bffe80a17bb5e4610cb41deca549935965f30864736f6c63430008030033', 'chain_id': -4, 'r': '0xf2704e20656acf4b067c23ff6e7e2bf8e9b6f75383c408607fce7f90ef39aedb', 's': '0x7612be142f5202b3970ee9b4c821bd95df4eb007735acc9c145b0d204d697f8c', 'v': 28}
    """
    class Transaction(rlp.Serializable):
        fields: list = [
            ("nonce", big_endian_int),
            ("gas_price", big_endian_int),
            ("gas", big_endian_int),
            ("to", Binary.fixed_length(20, allow_empty=True)),
            ("value", big_endian_int),
            ("data", binary),
            ("v", big_endian_int),
            ("r", big_endian_int),
            ("s", big_endian_int),
        ]

    def hex_to_bytes(data: str) -> bytes:
        return to_bytes(hexstr=HexStr(data))

    transaction = rlp.decode(hex_to_bytes(transaction_raw), Transaction)
    decoded_transaction: dict = {
        "hash":
        Web3.toHex(keccak(hex_to_bytes(transaction_raw))),
        "from":
        w3.eth.account.recover_transaction(transaction_raw),
        "to":
        (w3.toChecksumAddress(transaction.to) if transaction.to else None),
        "nonce":
        transaction.nonce,
        "gas":
        transaction.gas,
        "gas_price":
        transaction.gas_price,
        "value":
        transaction.value,
        "data":
        w3.toHex(transaction.data),
        "chain_id": ((transaction.v - 35) // 2 if transaction.v % 2 else
                     (transaction.v - 36) // 2),
        "r":
        hex(transaction.r),
        "s":
        hex(transaction.s),
        "v":
        transaction.v
    }
    return decoded_transaction
コード例 #19
0
def Import_Keystore(passphrase, filecontent):
    try:
        # content = json.loads(filecontent)
        private_key = w3.toHex(Account.decrypt(filecontent, passphrase))
        public_key = Account.privateKeyToAccount(private_key).address
        encrypted = Account.encrypt(private_key, passphrase)
        return (1, [public_key, private_key], json.dumps(encrypted))
    except Exception as err:
        print(err)
        return (0, 10000)
コード例 #20
0
ファイル: txpoollistener.py プロジェクト: hmallen/vanderwaals
def handle_event(event):
    hexed = w3.toHex(event)
    print(hexed)
    # and whatever
    # print(w3.eth.getTransactionReceipt(event))
    # print(w3.eth.getBlock(block_identifier=hexed, full_transactions=True))
    # print(w3.eth.getTransaction(hexed))
    [
        print(f"{transaction}\n") for transaction in w3.eth.getBlock(
            hexed, full_transactions=True)["transactions"]
    ]
コード例 #21
0
ファイル: eth_tx.py プロジェクト: max-block/mb-ethereum
def decode_raw_tx(raw_tx: str) -> DecodedRawTx:
    tx: Any = rlp.decode(hex_to_bytes(raw_tx), RPLTransaction)
    tx_hash = Web3.toHex(keccak(hex_to_bytes(raw_tx)))
    from_ = w3.eth.account.recover_transaction(raw_tx)
    to = w3.toChecksumAddress(tx.to) if tx.to else None
    data = w3.toHex(tx.data)
    r = hex(tx.r)
    s = hex(tx.s)
    chain_id = (tx.v - 35) // 2 if tx.v % 2 else (tx.v - 36) // 2
    return DecodedRawTx(**md(tx_hash, from_, to, data, chain_id, r, s, tx.v,
                             tx.gas, tx.gas_price, tx.value, tx.nonce))
コード例 #22
0
def send_raw_tx(w3, to_address, from_address, from_key):
    tx = Transaction(nonce=0,
                     gasprice=w3.eth.gasPrice,
                     startgas=100000,
                     to=to_address,
                     value=12345,
                     data=b'')

    tx.sign(from_key)
    raw_tx = rlp.encode(tx)
    raw_tx_hex = w3.toHex(raw_tx)
    w3.eth.sendRawTransaction(raw_tx_hex)
コード例 #23
0
ファイル: validator.py プロジェクト: Lebski/Etheronauth
def start_listening():
    transfer_filter = authority_contract.eventFilter(
        'PermissionRequestDeployed')
    log.out.info("\033[92mStart listening!\033[0m")
    while True:
        for event in transfer_filter.get_new_entries():
            request_id_bytes = event["args"]["permissionId"]
            request_id = w3.toHex(request_id_bytes)
            log.out.debug("Event found {}".format(
                event["args"]["permissionId"]))
            verify(request_id)
        time.sleep(3)
コード例 #24
0
ファイル: safeTransform.py プロジェクト: DAism2019/Deme
def transfer():
    nonce = w3.eth.getTransactionCount(my_address)
    unicorn_txn = NFT_CONTRACT.functions.safeTransferFrom(my_address,receiver_address,1).buildTransaction({
        'nonce': nonce,
        # 'value': w3.toWei(1000, 'ether'),
        'gasPrice': w3.toWei(10, 'gwei'),
        # 'gas': 500000
    })
    signed_txn = w3.eth.account.signTransaction(
        unicorn_txn, private_key=private_key)
    hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
    print("安全交易已经发送,请耐心等待并查询,hash值为:", w3.toHex(hash))
コード例 #25
0
ファイル: genesis.py プロジェクト: unification-com/wrkchain
def pre_fund(pre_funded_accounts):
    alloc = {}

    for account in pre_funded_accounts:
        if w3.isAddress(account['address']) and int(account['balance']) > 0:
            address = account['address'][2:]

            balance_wei = w3.toWei(account['balance'], 'ether')
            alloc[address] = {
                "balance": w3.toHex(balance_wei)
            }

    return alloc
コード例 #26
0
ファイル: child_chain.py プロジェクト: LastOfOurs/Last-Nifty
    def submit_block(self):
        ''' Submit the merkle root to the chain from the authority '''
        block = self.current_block
        block.make_mutable()
        block.sign(self.key)
        block.make_immutable()
        self.current_block_number += self.child_block_interval
        merkle_hash = w3.toHex(block.merklize_transaction_set())
        self.root_chain.submit_block(merkle_hash)

        self.blocks[self.current_block_number] = self.current_block
        self.current_block = Block()
        return str(self.current_block_number)
コード例 #27
0
    def PrivateKey(self, password):
        self.password = password
        keyfile = open(
            "/home/pi/EthereumWallet_local_API/wallet/keystore/" +
            os.listdir("/home/pi/EthereumWallet_local_API/wallet/keystore")[0])
        encrypted_key = eval(keyfile.read())  #Eval = stirng to dict
        try:
            self.private = w3.eth.account.decrypt(encrypted_key, self.password)
        except:
            return False
        self.private = w3.toHex(self.private)

        return True
コード例 #28
0
ファイル: chainhandler.py プロジェクト: Lebski/Etheronauth
def submit_request(account, sub=0, aud=0, exp=0, nbf=0, iat=0, wait=False):
    log.out.debug("submit_request: \"Using contract at {}\"".format(
        authority_contract.address))

    # setting header
    alg = w3.toBytes(text="RS256")
    typ = w3.toBytes(text="JWT")
    aud = w3.toBytes(text=aud)

    # hashing request id
    try:
        request_id_bytes = w3.soliditySha3(['address', 'bytes32'],
                                           [account, aud])
    except web3.exceptions.InvalidAddress as e:
        log.out.warning(
            "\033[91mPlease make sure your address has a valid EIP cheksum. Test on etherscan.io and correct in ressources/user_info.json\033[0m"
        )
        exit()

    # casting those filthy bytes to an human-readable hexstr
    request_id = w3.toHex(request_id_bytes)
    request_id = request_id[0:20]
    # Proof that this works
    #log.out.debug(w3.toBytes(hexstr=request_id))
    #log.out.debug(request_id_bytes)

    # submit to blockchain
    txn_hash = authority_contract.functions.addPermissionRequest(
        request_id, alg, typ, aud).transact({'from': account})

    # wait for tx_receipt, could be disabled
    if (wait):
        timer = 50
        tx_receipt = None
        log.out.info(
            "Transaction sent, waiting for mining: max. {} seconds".format(
                timer))
        while (tx_receipt is None and timer > 0):
            tx_receipt = w3.eth.getTransactionReceipt(txn_hash)
            time.sleep(1)
            timer -= 1
        if tx_receipt is not None:
            log.out.info(
                "\033[92mTransaction with request id {} mined!\033[0m".format(
                    request_id))

    return request_id
コード例 #29
0
ファイル: operateIco.py プロジェクト: fcgiin/NaturalDAO
def submit():
    path = dirname(dirname(abspath(__file__))) + '/abi/Ico.json'
    contract_abi = loads(open(path).read())
    myContract = w3.eth.contract(address=_icoAddress, abi=contract_abi)
    nonce = w3.eth.getTransactionCount(my_address)
    unicorn_txn = myContract.functions.submitICO().buildTransaction({
        'nonce':
        nonce,
        'gasPrice':
        w3.toWei(10, 'gwei'),
        'gas':
        500000
    })
    signed_txn = w3.eth.account.signTransaction(unicorn_txn,
                                                private_key=private_key)
    hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
    print("提交ICO交易已经发送,请耐心等待并查询,hash值为:", w3.toHex(hash))
コード例 #30
0
def transfer():
    _icoAddress = '0x5894c675477744B59Cd79e50d301486d75209BA7'
    exchange_address = '0xb6145A721ffd64029E72796b212d13065505d31c'
    path = dirname(dirname(abspath(__file__))) + '/abi/Ico.json'
    contract_abi = loads(open(path).read())
    myContract = w3.eth.contract(address=_icoAddress, abi=contract_abi)
    nonce = w3.eth.getTransactionCount(my_address)
    unicorn_txn = myContract.functions.transfer(exchange_address, 10000 *
                                                10**18).buildTransaction({
                                                    'nonce':
                                                    nonce,
                                                    'gas':
                                                    500000
                                                })
    signed_txn = w3.eth.account.signTransaction(unicorn_txn,
                                                private_key=private_key)
    hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
    print("代币交易已经发送,请耐心等待并查询,hash值为:", w3.toHex(hash))