Example #1
0
    def test_respond_message(self):
        tx_hash = Web3.keccak(text="some_bytes")
        tx_signature = Web3.keccak(text="tx_signature")

        tx_message = TransactionMessage(
            performative=TransactionMessage.Performative.PROPOSE_FOR_SIGNING,
            skill_callback_ids=[PublicId(AUTHOR, "a_skill", "0.1.0")],
            tx_id=self.tx_id,
            tx_sender_addr=self.tx_sender_addr,
            tx_counterparty_addr=self.tx_counterparty_addr,
            tx_amount_by_currency_id={"FET": -20},
            tx_sender_fee=0,
            tx_counterparty_fee=0,
            tx_quantities_by_good_id={"good_id": 0},
            ledger_id=self.ledger_id,
            info=self.info,
            signing_payload={"tx_hash": tx_hash},
        )

        tx_message_response = TransactionMessage.respond_signing(
            tx_message,
            performative=TransactionMessage.Performative.SUCCESSFUL_SIGNING,
            signed_payload={"tx_signature": tx_signature},
        )
        assert tx_message_response.signed_payload.get(
            "tx_signature") == tx_signature
Example #2
0
    def __init__(self, config):
        self.config = config

        # Get the ETH Key
        self.auth_key_path = config["auth"]["key_path"]

        # Get Smart contract params
        self.block_chain_provider_url = config["smart_contract"][
            "bc_provider_url"]
        self.compiled_contract_path = config["smart_contract"][
            "meeting_contract_path"]
        self.chain_id = config["smart_contract"]["chain_id"]
        self.max_gas = config["smart_contract"]["max_gas"]

        # Get the private key from the keyfile
        with open(self.auth_key_path) as keyfile:
            encrypted_key = keyfile.read()
            keyfilejson = json.loads(encrypted_key)
            self.server_private_key = w3.eth.account.decrypt(
                encrypted_key, "leet")  # TODO: Ask user for passphrase
            self.server_eth_address = keyfilejson['address']

        # Get the Meeting contract ABI from the ABI file
        with open(self.compiled_contract_path) as contract_file:
            contract_file_data = contract_file.read()
            contract_json = json.loads(contract_file_data)
            self.contract_abi = contract_json['abi']
            self.contract_bytecode = contract_json['bytecode']

        log.debug('ETH provider URL: ' + self.block_chain_provider_url)
        self.w3 = Web3(Web3.HTTPProvider(self.block_chain_provider_url))
Example #3
0
def main():
    from web3.auto import Web3
    from web3.middleware import geth_poa_middleware
    from eth_account.datastructures import SignedTransaction

    w3 = Web3(Web3.HTTPProvider("https://rpc1.newchain.newtonproject.org"))
    w3.middleware_onion.inject(geth_poa_middleware, layer=0)

    print(f'blockNumber: {w3.eth.blockNumber}')

    with open('a4d79e4efecd77ba0e1b6551388a7d7c0778824a.json') as keyfile:
        encrypted_key = keyfile.read()
        private_key = w3.eth.account.decrypt(encrypted_key, '123qwe')
        # tip: do not save the key or password anywhere, especially into a shared source file

        account = w3.eth.account.privateKeyToAccount(private_key)
        print(f'address: {account.address}')

        nonce = w3.eth.getTransactionCount(account.address)
        print(f'nonce: {nonce}')

        gas_price = w3.eth.gasPrice
        print(f"gasPrice: {gas_price}")

        chain_id = 1007

        transaction = {
            'to': '0x29e9356eC2082f447a7F747bF8D83c35E858fb86',
            'value': w3.toWei(1, "ether"),
            'gas': 21000,
            'gasPrice': gas_price,
            'nonce': nonce,
            'chainId': chain_id
        }
        signed: SignedTransaction = w3.eth.account.sign_transaction(
            transaction, private_key)
        print(signed)
        # When you run sendRawTransaction, you get back the hash of the transaction:
        w3.eth.sendRawTransaction(signed.rawTransaction)
        print(f"tx hash: {w3.toHex(signed.hash)}")

        while True:
            try:
                receipt = w3.eth.getTransactionReceipt(signed.hash)
                print("transaction is confirmed.")
                print(receipt)

                break
            except TransactionNotFound:
                print("waiting for transaction to be confirmed.")
                time.sleep(3)
Example #4
0
 def new_meeting_contract(self, meeting: Meeting):
     """
     Deploys a new meeting contract
     :param meeting: the meeting object associated with contract
     :return: Ethereum address of the contract
     """
     contract = self.w3.eth.contract(abi=self.contract_abi,
                                     bytecode=self.contract_bytecode)
     nonce = self.w3.eth.getTransactionCount(
         self.w3.toChecksumAddress('0x' + self.server_eth_address))
     log.debug('Nonce: ' + str(nonce))
     staff_dee_ids = [
         Web3.toChecksumAddress(staff_dee_id)
         for staff_dee_id in meeting.staff
     ]
     print(staff_dee_ids)
     contract_txn = contract.constructor(meeting.id,
                                         staff_dee_ids).buildTransaction({
                                             'nonce':
                                             nonce,
                                             'chainId':
                                             self.chain_id,
                                             'gas':
                                             2000000
                                         })
     signed = self.w3.eth.account.signTransaction(
         contract_txn, private_key=self.server_private_key)
     contract_txn_hash = self.w3.eth.sendRawTransaction(
         signed.rawTransaction)
     log.debug('Waiting for contract to be mined...')
     tx_receipt = self.w3.eth.waitForTransactionReceipt(contract_txn_hash)
     return str(tx_receipt.contractAddress)
def mint(contract):
    """
    mint zombie nft
    """
    transaction = pre_transaction(account.address)
    reward_address = Web3.toChecksumAddress("0xff827d59f973bc57eec55dce2955e03e6c81db30")
    token_uri = "https://raw.githubusercontent.com/weixuefeng/tokeuri/main/zombie.png"
    gas = contract.functions.awardItem(reward_address, token_uri).estimateGas(transaction)
    transaction['gas'] = gas
    tx = contract.functions.awardItem(reward_address, token_uri).buildTransaction(transaction)
    signed_txn = account.sign_transaction(tx)
    tx_hash = w3.toHex(w3.eth.sendRawTransaction(signed_txn.rawTransaction))
    print("mint txid: %s" % tx_hash)
Example #6
0
    def setup(self) -> None:
        """
        Set up the agent.

        :return: None
        """
        self._resources = Resources.from_resource_dir(self._directory, None)
        assert self._resources is not None, "No resources initialized. Error in setup."
        self._resources.setup()

        self.w3 = Web3(Web3.HTTPProvider(
            "https://nile.dev-ocean.com"))  #"http://localhost:7545"))

        with open(
                'keystore/UTC--2019-10-19T15-13-02.082157851Z--719b682d53f15899376709fb372c98aa5a116799'
        ) as keyfile:
            encrypted_key = keyfile.read()
            self.private_key = self.w3.eth.account.decrypt(
                encrypted_key, 'submarine')

        master_contract_address = '0x7d5158372BC13D1bA316b44B9002821BE46652F5'

        master_contract_address = Web3.toChecksumAddress(
            master_contract_address)
        self.account = self.w3.eth.account.privateKeyToAccount(
            self.private_key)
        self.w3.eth.defaultAccount = self.account.address
        self.eventBehaviour = self.resources.behaviour_registry.fetch_all()[0]
        self.resultTask = self.resources.task_registry.fetch_all()[0]
        #my_address = '0x719b682d53f15899376709fb372c98aa5a116799'

        with open("abi.json") as f:
            abi = json.load(f)

        self.contract = self.w3.eth.contract(address=master_contract_address,
                                             abi=abi)
        self.address = master_contract_address

        print("master contract", self.contract)
Example #7
0
    def __init__(self, config):
        """
        Auth class for all authentication/singing and crypto needs
        :param config: config.Config object
        """
        self.config = config
        self.auth_key_path = config["auth"]["key_path"]
        self.block_chain_provider_url = config["smart_contract"][
            "bc_provider_url"]

        self.dee_id_abi_path = config["auth"]["deeid_abi_path"]

        with open(self.auth_key_path) as keyfile:
            encrypted_key = keyfile.read()
            keyfilejson = json.loads(encrypted_key)
            self.server_private_key = w3.eth.account.decrypt(
                encrypted_key, "leet")  # TODO: Ask user for passphrase
            self.server_eth_address = keyfilejson['address']

        with open(self.dee_id_abi_path) as f:
            self.dee_id_abi = json.load(f)

        self.w3 = Web3(Web3.HTTPProvider(self.block_chain_provider_url))
Example #8
0
def handle_event(event):
    print(w3.eth.getBlock('latest'))
    block = w3.eth.getBlock('latest')
    print("------------------------------------------")
    for xx in w3.eth.getBlock('latest')['transactions']:
        x = Web3.toHex(xx)
        print("TX: " + x)
        #x=str(xx)[11:]
        #x=x[:-3]
        #print(x)
        #print(Web3.toHex(event))
        print(w3.eth.getTransaction(x))
        print("---------------")
        rec = w3.eth.getTransactionReceipt(x)
        print(rec['logs']['topics'])
        print("-----------------")
Example #9
0
    def test_sing_tx_offchain(self):
        """Test the private function sign_tx for the offchain ledger_id."""
        tx_hash = Web3.keccak(text="some_bytes")
        tx_message = TransactionMessage(
            performative=TransactionMessage.Performative.PROPOSE_FOR_SIGNING,
            skill_callback_ids=[PublicId(AUTHOR, "a_skill", "0.1.0")],
            tx_id=self.tx_id,
            tx_sender_addr=self.tx_sender_addr,
            tx_counterparty_addr=self.tx_counterparty_addr,
            tx_amount_by_currency_id={"FET": -20},
            tx_sender_fee=0,
            tx_counterparty_fee=0,
            tx_quantities_by_good_id={"good_id": 0},
            ledger_id="off_chain",
            info=self.info,
            signing_payload={"tx_hash": tx_hash},
        )

        tx_signature = self.decision_maker_handler._sign_tx_hash(tx_message)
        assert tx_signature is not None
Example #10
0
            #oceanDid = event_args["oceanDid"]
            response = create_ocean_request({"command" : command, "did" : oceanDid})
            result = process_response(response)
            signed_txn = create_result_tx()
            w3.eth.sendRawTransaction(signed_txn.rawTransaction)
            
            length = len(event_filter.get_all_entries())#maybe dont need this

        time.sleep(2)




if __name__ == '__main__':

    w3 = Web3(Web3.HTTPProvider("http://localhost:7545"))

    with open('../keystore/UTC--2019-10-19T15-13-02.082157851Z--719b682d53f15899376709fb372c98aa5a116799') as keyfile:
        encrypted_key = keyfile.read()
        private_key = w3.eth.account.decrypt(encrypted_key, 'submarine')

    contract_address = '0x4B04928c8beEF8848920a8BA63176B7aB5Fc87e2'
    contractAddress = Web3.toChecksumAddress(contract_address)
    account =  w3.eth.account.privateKeyToAccount(private_key)
    w3.eth.defaultAccount = account.address

    with open("abi.json") as f:
        abi = json.load(f)

    contract = w3.eth.contract(address=contractAddress, abi=abi)
    contract.address = contractAddress 
Example #11
0
### CONFIG #####################################################################

ipcMiddleware = {
    "MainNet": "/home/quadrans/.quadrans/geth.ipc",
    "TestNet": "/home/quadrans/.quadrans/testnet/geth.ipc"
}
custom_fig = Figlet(font='standard')

### MAIN #######################################################################

print(custom_fig.renderText('Quadrans Node'))

try:
    for net, ipc in ipcMiddleware.items():
        web3 = Web3(IPCProvider(ipc))
        if web3.isConnected():
            print("Provider:\t\tIPC (" + net + ": " + ipc + ")")
            break
    if not web3.isConnected():
        sys.exit()
except SystemExit:
    print("Could not connect to node via providers")
    sys.exit()
except:
    print("Critical error connectiong to node")
    sys.exit()


def show(status):
Example #12
0
import json
from web3.providers.rpc import HTTPProvider
from web3.auto import Web3

import time
from time import sleep

w3 = Web3(HTTPProvider('http://localhost:7545'))
# #open("C:/Users/XXX/Documents/50_states.csv",mode='w')
# with open("C:/BlockChainSG/project_blockchain/Will_contract/project/truffleProject/build/contracts/WillContract.json", mode='r') as abi_definition:
#     abi = json.load(abi_definition)
# contractAddress = w3.toChecksumAddress('0xea56736062e3cd7bce48be94830ad112bbaca94f')
# fContract = w33.eth.contract(abi,contractAddress)
# event_signature_transfer = w3.sha3(text='Transfer(address,address,uint256)')
# event_filter = w3.eth.filter('{"topics": [event_signature_transfer]}')
# # transfer_events = w3.eth.getFilterChanges(event_filter.filter_id)
# mycontract ==
# myfilter = mycontract.eventFilter('EventName', {'fromBlock': 0,'toBlock': 'latest'});
# eventlist = myfilter.get_all_entries()


def handle_event(event):
    print(w3.eth.getBlock('latest'))
    block = w3.eth.getBlock('latest')
    print("------------------------------------------")
    for xx in w3.eth.getBlock('latest')['transactions']:
        x = Web3.toHex(xx)
        print("TX: " + x)
        #x=str(xx)[11:]
        #x=x[:-3]
        #print(x)
Example #13
0
from web3.auto import Web3
import time
from secrets import graph_token, p_key
import requests
import json
import subprocess
import random
import string

w3 = Web3(Web3.HTTPProvider("http://ethberlin02.skalenodes.com:10013"))

contract_address = '0x1f1e8f456f60b7a5435920b54da5525974ab6bfd'
contractAddress = Web3.toChecksumAddress(contract_address)
account =  w3.eth.account.from_key(p_key)
w3.eth.defaultAccount = account.address

with open("abi.json") as f:
    abi = json.load(f)

contract = w3.eth.contract(address=contractAddress, abi=abi)
contract.address = contractAddress  # THIS LINE!

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'
def transaction(tx): 

    # Web3 Entry point to contract
    web3 = Web3(IPCProvider(ipcMiddleware))
    # web3.middleware_stack.inject(geth_poa_middleware, layer=0)
    web3.middleware_onion.inject(geth_poa_middleware, layer=0)
    contract =  web3.eth.contract( address = contractAddress, abi = contractABI )
    
    # Read data from BC
    try:
        tx_receipt = web3.eth.getTransactionReceipt(tx)
    except :
        page = "<h1>Error</h1>"
        page += "There was an error retreivng transaction "+tx+"<br>"
        page += "the transaction was not found.<p>"
        page += "Probably you are searching in the wrong chain<br>"
        page += "Please make sure your node is running in the same network where the orginal transaction was made"
        page += "<p>"
        page += "Try to:"
        page += "<ul>"
        page += "<li><a href=\"https://explorer.quadrans.io/tx/"+tx+"\">look for the transaction in main net</a></li>"
        page += "<li><a href=\"https://explorer.testnet.quadrans.io/tx/"+tx+"\">loof for the transaction un test net</a></li>"
        page += "</ul>"
        return page

    tx_sent = web3.eth.getTransaction(tx)
    bl = web3.eth.getBlock(tx_receipt['blockNumber'])
    ts = bl["timestamp"]

    # Decode Data --> Encode JSON
    bdt = datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
    ce = contract.events.logData().processReceipt(tx_receipt)
    if not ce or not ce[0] or not ce[0]['args'] or not ce[0]['args']['_filehash']:
        page = "<h1>Error</h1>"
        page += "There was an error decoding the transaction "+tx+"<br>"
        page += "the transaction is not compatible with the smart contract.<p>"
        page += "Probably you submitted the wrong transaction<br>"
        return page
    
    res = {
        'blockNumber'       : tx_receipt['blockNumber'],
        'blockHash'         : '0x'+bytes(tx_receipt['blockHash']).hex(),
        'blockDateTime'     : bdt,
        'transactionHash'   : '0x'+bytes(tx_receipt['transactionHash']).hex(),
        'sender'            : tx_receipt['from'],
        'contract'          : tx_receipt['to'],
        #'rawData'           : tx_receipt['logs'][0]['data'],
        'rawData'           : tx_sent['input'],
        '_filehash'     : '0x'+ce[0]['args']['_filehash'].hex(),
        '_filename'     : ce[0]['args']['_filename'],
        '_notes'        : ce[0]['args']['_notes']
    }

    rdata =  tx_sent['input']
    rdata = rdata[2:]
    res["rawData"] = ""
    res["rawData"] += rdata[0:8]+"\n"
    rdata = rdata[8:]
    while len(rdata) >0:
        res["rawData"] += rdata[0:64]+"\n"
        rdata = rdata[64:]

    # Create qrcode
    res["qr"] = qrcreate(request.url)
    res["page"] = request.url
    
    with open(pageTemplate1, 'r', encoding='utf-8') as template_file:
        template_file_content = template_file.read()
    pageTemplate = Template(template_file_content)


    page = pageTemplate.substitute(res)
    return page
Example #15
0
import json
from typing import Optional

from django.conf import settings
from web3.auto import Web3
from web3.contract import Contract

from common.account import Account

ETHEREUM_ADDRESS_REGEX = r'^0x[a-fA-F0-9]{40}$'

w3 = Web3()


def _load_ethereum_account() -> Account:
    with open(settings.PRIVATE_KEY_PATH) as keyfile:
        private_key = w3.eth.account.decrypt(keyfile.read(),
                                             settings.PRIVATE_KEY_PASSWORD)
        acc = w3.eth.account.from_key(private_key)
        return Account(address=acc.address, private_key=private_key)


ACCOUNT = _load_ethereum_account()


def _load_contract(path: str,
                   contract_address: Optional[str] = None) -> Contract:
    with open(path) as file:
        contract_dict = json.load(file)
        address = contract_address or contract_dict['networks'][
            settings.NETWORK_ID]['address']
import sys
import json
import time
import csv

from web3.auto import Web3
from web3 import IPCProvider
from web3.middleware import geth_poa_middleware
import web3

import config as cfg

#################################################################################
# GLOBALS
NONCE = 0
WALLET = Web3.toChecksumAddress(cfg.web3["wallet"])
PASSWD = cfg.web3["password"]
CC_ADD = Web3.toChecksumAddress(cfg.web3["contract-address"])
CC_ABI = ""

web3 = False
contract = False

#################################################################################
# FUNCTIONS

def getNonce():
    '''gets the NONCE to be used for the next transaction'''
    newnonce = web3.eth.getTransactionCount(WALLET)
    n = newnonce if newnonce > (NONCE+1) else NONCE+1
    print("nonce: {}".format(NONCE))
Example #17
0
__copyright__ = """ Copyright (c) 2021 Newton Foundation. All rights reserved."""
__author__ = '*****@*****.**'
__version__ = '1.0'

import datetime

from web3.auto import Web3
from web3.middleware import geth_poa_middleware

import newchain.config as config
import newchain.utils as utils
from newchain.contracts import constant

# 构造 web3
w3 = Web3(Web3.HTTPProvider(config.RPC))
w3.middleware_onion.inject(geth_poa_middleware, layer=0)

# 获取账户信息
account = w3.eth.account.privateKeyToAccount(config.PRIVATE_KEY)
chain_id = int(w3.net.version)
gas_price = w3.eth.gasPrice

# 获取合约信息
zombie = utils.get_zombie_contract(w3)
zero_value_new = Web3.toWei("0", 'ether')


def mint(contract):
    """
    mint zombie nft