def check_block(args): def one_block_check(block_num): logger.info('recv block number: {}'.format(block_num)) try: block = gph.rpc.get_block(block_num) #witness_id = block['witness'] block_witness = gph.rpc.get_object( gph.rpc.get_object( block['witness'])['witness_account'])['name'] except Exception as e: logger.error('get_object exception. block {}, error {}'.format( block_num, repr(e))) block_time = block['timestamp'] transactions = block["transactions"] witness_sign = block['witness_signature'] trx_total = 0 ops_total = 0 transactions_id = [] if transactions: trx_total = len(transactions) for trx in transactions: transactions_id.append(trx[0]) ops_total += len(trx[1]["operations"]) block_data = { "block_num": block_num, "time": block_time, "witness": block_witness, "witness_sign": witness_sign, "transactions_total": trx_total, "transactions_id": transactions_id, "operations_total": ops_total } block_info_deque_lock.acquire() block_info_q.append(block_data) block_info_deque_lock.release() start = args[0] end = args[1] gph = Graphene(node=nodeaddress) info = gph.info() last_block_num = info['head_block_number'] #logger.info('last_block_num: {}, block start: {}, end: {}, info: {}'.format(last_block_num, start, end, info)) logger.info('last_block_num: {}, block start: {}, end: {}'.format( last_block_num, start, end)) if start > last_block_num: logger.error("start:{} < end:{}".format(start, end)) return if end > last_block_num: end = last_block_num conn = pymongo.MongoClient(mongodb_params['host'], mongodb_params['port']) conn_db = conn[mongodb_params['db_name']] for index in range(start, end + 1): result = conn_db.block.find({'block_num': index}) if result.count() == 0: logger.info('check block number: {}'.format(index)) one_block_check(index) else: logger.info('block({}) already exists in mongodb'.format(index)) sleep(0.1) conn.close()
def check_block(args): start = args[0] end = args[1] gph = Graphene(node=nodeaddress) info = gph.info() last_block_num = info['head_block_number'] logger.info('last_block_num: {}, block start: {}, end: {}'.format( last_block_num, start, end)) if start > last_block_num: logger.error("start:{} < end:{}".format(start, end)) return if end > last_block_num: end = last_block_num for block_num in range(end, start, -1): try: block_info = gph.rpc.get_block(block_num) operations_list = parse_gas_collateral_operations( gph, block_num, block_info["timestamp"], block_info["transactions"]) if operations_list: op_deque_lock.acquire() operations_deque.append(operations_list) op_deque_lock.release() except Exception as e: logger.error('parse block exception. block {}, error {}'.format( block_num, repr(e)))
def listen_block(): def on_block_callback(recv_block_id): global global_last_block_num info = gph.info() # logger.debug('info: {}'.format(info)) head_block_id = info['head_block_id'] head_block_number = info['head_block_number'] # logger.debug('head_block_num {}, recv_block_id: {}, head_block_id {}'.format(head_block_number, recv_block_id, head_block_id)) if recv_block_id == head_block_id: if head_block_number != global_last_block_num+1: if global_last_block_num > 0: logger.info('head_block_num {}, recv_block_id: {}, head_block_id {}'.format(head_block_number, recv_block_id, head_block_id)) logger.warn('current block num: {}, last block num: {}'.format(head_block_number, global_last_block_num)) #send message global_last_block_num = head_block_number else: try: logger.info('head_block_num {}, recv_block_id: {}, head_block_id {}'.format(head_block_number, recv_block_id, head_block_id)) block = gph.rpc.get_block(global_last_block_num+1) global_last_block_num = global_last_block_num+1 logger.warn('>> get_block {}, recv_block_id: {}, head_block_id: {}, get block response: {}'.format( global_last_block_num, recv_block_id, head_block_id, block['block_id'])) except Exception as e: logger.error('get_block exception. block {}, error {}'.format(global_last_block_num+1, repr(e))) gph = Graphene(node=nodeaddress) from PythonMiddleware.instance import set_shared_graphene_instance set_shared_graphene_instance(gph) notify = Notify( on_block = on_block_callback, graphene_instance = gph ) notify.listen()
def analysis_block(): gph = Graphene(node=nodeaddress) from PythonMiddleware.instance import set_shared_graphene_instance set_shared_graphene_instance(gph) while 1: if pending_block_num_q: try: pending_block_num_deque_lock.acquire() block_num = pending_block_num_q.popleft() pending_block_num_deque_lock.release() logger.debug('pop block number: {}'.format(block_num)) try: block_info = gph.rpc.get_block(block_num) time = block_info["timestamp"] transactions = block_info["transactions"] operations_list = parse_operations(gph, block_num, time, transactions) #logger.debug('block: {}, trx_list: {}'.format(block_num, operations_list)) except Exception as e: logger.error( 'parse block exception. block {}, error {}'.format( block_num, repr(e))) if operations_list: op_deque_lock.acquire() operations_q.append(operations_list) op_deque_lock.release() except Exception as e: logger.error("pending_block_num_q: {}, except: '{}'".format( pending_block_num_q, repr(e))) sleep(0.7)
def check_block(start_block, end_block=-1): global interval_blocks, block_count_result print("interval_blocks: {}".format(interval_blocks)) gph = Graphene(node=nodeaddress) if end_block == -1: info = gph.info() print("info: {}".format(info)) end_block = info['head_block_number'] print("start block: {}, end_block: {}".format(start_block, end_block)) key_block_num = str(start_block) for i in range(int(start_block), int(end_block)): try: block = gph.rpc.get_block(i) # print("block: {}".format(block)) timestamp = block["timestamp"] block_date = timestamp.split("T")[0] if i % interval_blocks == 0 or key_block_num == str(i): # print("start_block: {}, end_block: {}, block_id: {}".format(key_block_num, i, block["block_id"])) if key_block_num in block_count_result.keys(): print(">>>> {}: {}".format( key_block_num, block_count_result[key_block_num])) key_block_num = i block_count_result[key_block_num] = { "start_block": int(key_block_num), "block_total": 0, "trx_total": 0, "ops_total": 0 } block_data = block_count_result[key_block_num] block_data["block_total"] += 1 block_data["end_block"] = i transactions = block["transactions"] if transactions: block_data["trx_total"] += len(transactions) for trx in transactions: block_data["ops_total"] += len(trx[1]["operations"]) block_count_result[key_block_num] = block_data except Exception as e: print('get_object exception. block {}, error {}'.format( block_num, repr(e))) print("\n\n>>>> total result: \n{}".format(block_count_result))
def listen_block(): def on_block_callback(recv_block_id): info = gph.info() #logger.debug('info: {}'.format(info)) head_block_id = info['head_block_id'] block_num = info['head_block_number'] logger.info( 'recv_block_id: {}, head_block_id {}, head_block_num {}'.format( recv_block_id, head_block_id, block_num)) if recv_block_id == head_block_id: pending_block_num_deque_lock.acquire() pending_block_num_q.append(block_num) pending_block_num_deque_lock.release() logger.info("pending deque >>>: {}".format(pending_block_num_q)) try: block = gph.rpc.get_block(block_num) #witness_id = block['witness'] # block_witness = gph.rpc.get_object(gph.rpc.get_object(block['witness'])['witness_account'])['name'] witness_obj = gph.rpc.get_object(block['witness']) witness_account_obj = gph.rpc.get_object( witness_obj['witness_account']) except Exception as e: logger.error('get_object exception. block {}, error {}'.format( block_num, repr(e))) block_time = block['timestamp'] transactions = block["transactions"] witness_sign = block['witness_signature'] trx_total = 0 ops_total = 0 transactions_id = [] if transactions: trx_total = len(transactions) for trx in transactions: transactions_id.append(trx[0]) ops_total += len(trx[1]["operations"]) block_data = { "block_num": block_num, "time": block_time, "witness_id": witness_obj["id"], "witness_account_id": witness_account_obj['id'], "witness_account_name": witness_account_obj["name"], "witness_sign": witness_sign, "transactions_total": trx_total, "transactions_id": transactions_id, "operations_total": ops_total } block_info_deque_lock.acquire() block_info_q.append(block_data) block_info_deque_lock.release() gph = Graphene(node=nodeaddress) from PythonMiddleware.instance import set_shared_graphene_instance set_shared_graphene_instance(gph) notify = Notify(on_block=on_block_callback, graphene_instance=gph) notify.listen() # 启动监听服务
def __init__(self, **kwargs): print("kwargs:", kwargs) self.gph = Graphene(node=self.node_address, blocking=self.blocking, **kwargs) set_shared_graphene_instance(self.gph) if self.gph.wallet.created() is False: self.gph.wallet.newWallet(self.wallet_pwd) self.gph.wallet.unlock(self.wallet_pwd) try: self.gph.wallet.addPrivateKey(self.wifkey) except: pass
def check_block(): def one_block_check(block_num): logger.info('check block number: {}'.format(block_num)) try: block = gph.rpc.get_block(block_num) #witness_id = block['witness'] block_witness = gph.rpc.get_object( gph.rpc.get_object( block['witness'])['witness_account'])['name'] except Exception as e: logger.error('get_object exception. block {}, error {}'.format( block_num, repr(e))) return block_time = block['timestamp'] transactions = block["transactions"] witness_sign = block['witness_signature'] trx_total = 0 ops_total = 0 transactions_id = [] if transactions: trx_total = len(transactions) for trx in transactions: transactions_id.append(trx[0]) ops_total += len(trx[1]["operations"]) block_data = { "block_num": block_num, "time": block_time, "witness": block_witness, "witness_sign": witness_sign, "transactions_total": trx_total, "transactions_id": transactions_id, "operations_total": ops_total } block_info_deque_lock.acquire() block_info_q.append(block_data) block_info_deque_lock.release() try: gph = Graphene(node=nodeaddress) #info = gph.info() #logger.info('info: {}'.format(info)) conn = pymongo.MongoClient(mongodb_params['host'], mongodb_params['port']) conn_db = conn[mongodb_params['db_name']] sort_limit_result = conn_db.block.find().sort("block_num", -1).limit(1) db_last_block_str = jsonb.dumps(sort_limit_result) logger.info("db_last_block_str: {}".format(db_last_block_str)) db_last_block = json.loads(db_last_block_str) if len(db_last_block) != 1: logger.error( "conn_db.block.find().sort('block_num', -1).limit(1) exception" ) conn.close() return start_num = db_last_block[0]['block_num'] info = gph.info() logger.info('info: {}'.format(info)) last_block_num = info['head_block_number'] increase = int( (last_block_num - start_num) / 8) + 10 # 尽可能处理listen之前新增的区块 logger.info(">>> start: {}, end: {}, step: {}".format( start_num, last_block_num, increase)) for index in range(start_num, last_block_num + increase): result = conn_db.block.find({'block_num': index}) if result.count() != 0: logger.info( 'block({}) already exists in mongo db'.format(index)) continue one_block_check(index) conn.close() except Exception as e: logger.error("except: '{}'".format(repr(e)))
# -*- coding:utf-8 -*- from PythonMiddleware.notify import Notify from PythonMiddleware.graphene import Graphene from PythonMiddlewarebase.operationids import operations import pymongo from config import * from utils import Logging logger = Logging(console=True).getLogger() gph = Graphene(node=nodeaddress) def witness_check(): conn = pymongo.MongoClient(mongodb_params['host'], mongodb_params['port']) conn_db = conn[mongodb_params['db_name']] index = 1 witness_id_prefix = "1.6." while True: witness_id = "{}{}".format(witness_id_prefix, index) logger.info("witness_id: {}".format(witness_id)) witness_obj = gph.rpc.get_object(witness_id) if witness_obj is None: break witness_account_obj = gph.rpc.get_object( witness_obj['witness_account']) try: count = conn_db.block.count( {'witness': witness_account_obj["name"]})
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from PythonMiddleware.graphene import Graphene from PythonMiddleware.instance import set_shared_graphene_instance from pprint import pprint import time #nodeAddress = "wss://api.cocosbcx.net" nodeAddress = "ws://test.cocosbcx.net" #nodeAddress = "ws://127.0.0.1:8049" gph = Graphene(node=nodeAddress) set_shared_graphene_instance(gph) while True: print('>> info') pprint(gph.info()) time.sleep(2)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from PythonMiddleware.graphene import Graphene from PythonMiddleware.instance import set_shared_graphene_instance from pprint import pprint from PythonMiddleware.account import Account nodeAddress = "ws://127.0.0.1:8020" gph = Graphene(node=nodeAddress, blocking=True) set_shared_graphene_instance(gph) #创建钱包 #可以通过gph.wallet 直接使用钱包instance,操作钱包的接口。 if gph.wallet.created() is False: gph.newWallet("123456") #钱包解锁 if gph.wallet.locked() is True: gph.wallet.unlock("123456") #init0 ["COCOS5vzuh6YRRmCjUMeeHLsjnVCdJwqm9WZoUBDDNVp7HTwFM1ZYQT", "5JHdMwsWkEXsMozFrQAQKnKwo44CaV77H45S9PsH7QVbFQngJfw"] pub = "COCOS5vzuh6YRRmCjUMeeHLsjnVCdJwqm9WZoUBDDNVp7HTwFM1ZYQT" pprint(gph.wallet.getPrivateKeyForPublicKey(pub)) #合约创建1:单行合约 data1 = "function hello() chainhelper:log('Hello World!') end" pprint( gph.create_contract("contract.pytest.hello", data=data1, con_authority=pub,
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from PythonMiddleware.graphene import Graphene from PythonMiddleware.instance import set_shared_graphene_instance from pprint import pprint from PythonMiddleware.account import Account from PythonMiddleware.storage import configStorage as config nodeAddress = "ws://127.0.0.1:8049" gph = Graphene(node=nodeAddress, blocking=True) set_shared_graphene_instance(gph) #account info for test defaultAccount="nicotest" privateKey="5KgiWEMJPYbLpMhX6jvS9yBehhr4mWZhxX7hfxZQEo3rs8iakUQ" pub="COCOS5X4bfMnAmeWhLoiHKUNrRu7D3LTXKBZQkZvWGj9YCTDBAYaSXU" #创建钱包 if gph.wallet.created() is False: gph.newWallet("123456") #钱包解锁 if gph.wallet.locked() is True: gph.wallet.unlock("123456") #add key if gph.wallet.getAccountFromPublicKey(pub) is None: gph.wallet.addPrivateKey(privateKey) #账号私钥导入钱包 pprint(gph.wallet.getPrivateKeyForPublicKey(pub))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from PythonMiddleware.graphene import Graphene from PythonMiddleware.instance import set_shared_graphene_instance from pprint import pprint from PythonMiddleware.account import Account nodeAddress = "ws://127.0.0.1:8020" gph = Graphene(node=nodeAddress, blocking=True) set_shared_graphene_instance(gph) #创建钱包 #可以通过gph.wallet 直接使用钱包instance,操作钱包的接口。 if gph.wallet.created() is False: gph.newWallet("123456") #钱包解锁 if gph.wallet.locked() is True: gph.wallet.unlock("123456") #查看钱包导入的所有账户信息 pprint(gph.wallet.getAccounts()) #init0 ["COCOS5vzuh6YRRmCjUMeeHLsjnVCdJwqm9WZoUBDDNVp7HTwFM1ZYQT", "5JHdMwsWkEXsMozFrQAQKnKwo44CaV77H45S9PsH7QVbFQngJfw"] pub = "COCOS5vzuh6YRRmCjUMeeHLsjnVCdJwqm9WZoUBDDNVp7HTwFM1ZYQT" #获取公钥对应的私钥 pprint(gph.wallet.getPrivateKeyForPublicKey(pub)) #通过公钥获取账号信息
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from PythonMiddleware.graphene import Graphene from PythonMiddleware.instance import set_shared_graphene_instance from pprint import pprint from PythonMiddleware.account import Account from PythonMiddleware.storage import configStorage as config nodeAddress = "ws://127.0.0.1:8049" gph = Graphene(node=nodeAddress, blocking=True) set_shared_graphene_instance(gph) #account info for test defaultAccount = "test1" privateKey = "5JAt3WmMCqQvAqqq4Mr7ZisN8ztrrPZCTHCN7f8Vrx8j1cHY4hy" pub = "COCOS8m1rD2w5q2fJB89MaNJRhnYppdrkEtWB71FLMjfL2xXhCnXAqn" #创建钱包 if gph.wallet.created() is False: gph.newWallet("123456") #钱包解锁 if gph.wallet.locked() is True: gph.wallet.unlock("123456") #add key if gph.wallet.getAccountFromPublicKey(pub) is None: gph.wallet.addPrivateKey(privateKey) #账号私钥导入钱包 pprint(gph.wallet.getPrivateKeyForPublicKey(pub))
"name": "nicotest", "id": "1.2.16", "private_key": "5J2SChqa9QxrCkdMor9VC2k9NT4R4ctRrJA6odQCPkb3yL89vxo", "public_key": "COCOS56a5dTnfGpuPoWACnYj65dahcXMpTrNQkV3hHWCFkLxMF5mXpx", } ## wallet_password wallet_password = "******" ## chain-node ws config # nodeAddress = "wss://api.cocosbcx.net" nodeAddress = "wss://test.cocosbcx.net" # nodeAddress = "ws://127.0.0.1:8049" ################################ config END ################################ gph = Graphene(node=nodeAddress, blocking=True) set_shared_graphene_instance(gph) def get_account(name): try: account = Account(name) return account except Exception as e: error_msg = repr(e) print('[WARN]name {}, error: {}'.format(name, repr(e))) return None def create_account(name, owner_key, active_key, memo_key, registrar): try: response = gph.create_account(account_name=name, registrar=registrar, owner_key=owner_key, active_key=active_key, memo_key=memo_key)
from PythonMiddleware.graphene import Graphene from PythonMiddleware.storage import configStorage from PythonMiddleware.instance import set_shared_graphene_instance import time import json import string import hashlib import random import datetime from logger import logger from threading import Thread, Lock from weather_api import query_live_weather from config import register, sdk_config gph = Graphene(node=sdk_config["node_address"], blocking=True) set_shared_graphene_instance(gph) count = 0 def random_uppercases(n): return ''.join([random.choice(string.ascii_uppercase) for i in range(n)]) def random_lowercases(n): return ''.join([random.choice(string.ascii_lowercase) for i in range(n)]) def get_block_num_from_id(block_id): return int(block_id[0:8], 16)
def check_block(start_date): global last_block_date, AFTER_DAYS, result_block_data start_date = start_date gph = Graphene(node=nodeaddress) info = gph.info() logger.info("info: {}".format(info)) last_block_num = info['head_block_number'] logger.info("time: {}".format(info["time"])) current_time = info["time"] current_date = info["time"].split("T")[0] start_block_num = 1 end_block_num = last_block_num seconds = compare_time(current_date, start_date) logger.info("current_date: {}, start_date: {}, seconds: {}".format( current_date, start_date, seconds)) if seconds < 3600 * 24 * AFTER_DAYS: logger.info("before {} days".format(AFTER_DAYS)) logger.info("last_block_num: {}, delta: {}".format( last_block_num, 1800 * 24 * AFTER_DAYS)) end_block_num = last_block_num start_block_num = last_block_num - 1800 * 24 * AFTER_DAYS else: logger.info("after {} days".format(AFTER_DAYS)) start_block_num = int(last_block_num - seconds / 2) end_block_num = int(start_block_num + (1800 * 24 * AFTER_DAYS)) if last_block_num < end_block_num: end_block_num = last_block_num logger.info('[block num]start: {}, end: {}, last: {}, seconds: {}'.format( start_block_num, end_block_num, last_block_num, seconds)) for block_num in range(start_block_num, end_block_num + 1): try: block = gph.rpc.get_block(block_num) # logger.info("block: {}".format(block)) timestamp = block["timestamp"] block_date = timestamp.split("T")[0] if block_date != last_block_date: # logger.info("last_date: {}, block_num: {}, block: {}".format(last_block_date, block_num, block)) logger.info( "last_date: {}, block_num: {}, block_id: {}, block timestamp: {}" .format(last_block_date, block_num, block["block_id"], block["timestamp"])) if last_block_date in result_block_data.keys(): logger.info(">>>>>>>>>>>> {}: {}".format( last_block_date, result_block_data[last_block_date])) last_block_date = block_date result_block_data[block_date] = { "block_total": 0, "trx_total": 0, "ops_total": 0 } block_data = result_block_data[block_date] block_data["block_total"] += 1 transactions = block["transactions"] if transactions: block_data["trx_total"] += len(transactions) for trx in transactions: block_data["ops_total"] += len(trx[1]["operations"]) result_block_data[block_date] = block_data except Exception as e: logger.error('get_object exception. block {}, error {}'.format( block_num, repr(e))) logger.info("\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>> total result: \n{}".format( result_block_data))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from PythonMiddleware.graphene import Graphene from PythonMiddleware.instance import set_shared_graphene_instance from pprint import pprint from PythonMiddleware.account import Account nodeAddress = "ws://127.0.0.1:8020" gph = Graphene(node=nodeAddress, blocking=True) set_shared_graphene_instance(gph) #创建钱包1 #可以通过gph.wallet 直接使用钱包instance,操作钱包的接口。 if gph.wallet.created() is False: gph.newWallet("123456") #创建钱包2 if gph.wallet.created() is False: gph.wallet.create("123456") #钱包解锁 gph.wallet.unlock("123456") #钱包锁住 gph.wallet.lock() #查看钱包锁定状态 #返回: False 或 True pprint(gph.wallet.locked())
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from PythonMiddleware.graphene import Graphene from PythonMiddleware.instance import set_shared_graphene_instance from pprint import pprint from PythonMiddleware.account import Account from PythonMiddleware.storage import configStorage as config nodeAddress = "ws://127.0.0.1:8049" gph = Graphene(node=nodeAddress, blocking=True) set_shared_graphene_instance(gph) #account info for test defaultAccount = "nicotest" privateKey = "5KgiWEMJPYbLpMhX6jvS9yBehhr4mWZhxX7hfxZQEo3rs8iakUQ" pub = "COCOS5X4bfMnAmeWhLoiHKUNrRu7D3LTXKBZQkZvWGj9YCTDBAYaSXU" #创建钱包 if gph.wallet.created() is False: gph.newWallet("123456") #钱包解锁 if gph.wallet.locked() is True: gph.wallet.unlock("123456") #add key if gph.wallet.getAccountFromPublicKey(pub) is None: gph.wallet.addPrivateKey(privateKey) #账号私钥导入钱包 pprint(gph.wallet.getPrivateKeyForPublicKey(pub))