一、获取ontology

  1、从release获取

  (1)通过命令获取最新的ontology版本

    curl https://dev.ont.io/ontology_install | sh

  (2)可以下载地址下载

  2、从源码获取

  (1)克隆ontology仓库到 $GOPATH/src/github.com/ontio 目录

    git clone https://github.com/ontio/ontology.git

    或者

    go get github.com/ontio/ontology

  (2)用第三方包管理工具glide拉取依赖库

     cd $GOPATH/src/github.com/ontio/ontology

     glide install

  (3)如果项目有新的第三方依赖包,使用glide更新依赖库

    cd $GOPATH/src/github.com/ontio/ontology

    glide update

  (4)用make编译源码

    make all

  成功编译后会生成两个可以执行程序:

    ontology: 节点程序/以命令行方式提供的节点控制程序

    tools/sigsvr: (可选)签名服务 - sigsvr是一个签名服务的server以满足一些特殊的需求。

二、运行ontology

  1、主网同步节点

    ./ontology

  2、本地访问测试节点信息

    (1)Ubuntu 18.04开放指定端口

      添加开放端口,ontology默认rpc端口是20336

      # sudo iptables -I INPUT -p tcp --dport [端口号] -j ACCEPT

      sudo iptables -I INPUT -p tcp --dport 20336 -j ACCEPT

      # 临时保存配置,重启后失效

      sudo iptables-save

      安装 iptables-persistent工具,持久化开放端口配置:sudo apt-get install iptables-persistent

      sudo netfilter-persistent save

      sudo netfilter-persistent reload

    (2)post访问示例

      利用postman工具的post请求 

      获取当前节点最高区块的哈希值:

      headers:写了常规请求时的内容(头为空也不影响接口请求)
      body选择raw

      参数含义:

      id字段用来标识消息,修改内容也不影响接口请求,
      jsonrpc字段表示JSON-RPC版本号,
      method字段表示需要调用的API方法名字,

      params字段表示要传送的参数
      

      返回值:

      

 

      更多json-rpc命令,请参考官方文档:https://dev-docs.ont.io/#/docs-cn/ontology-cli/05-rpc-specification?id=_1-getbestblockhash

三、解析transaction信息到数据库

   1、时间格式处理代码,ontology_time.py

import time
def time_transformation(time__):
    time_ = time.localtime(time__)
    time_ = time.strftime('%Y-%m-%d %H:%M:%S', time_)
    return time_

  2、连接数据库代码,ontology_connect_mysql.py

import pymysql
import time
# 连接数据库
def connet_mysql():
    while True:
        try:
            db = pymysql.connect('localhost','root','123456','pcany_onto')
            cursor = db.cursor()
            if db:
                return db,cursor
        except Exception as e:
            time.sleep(5)

  3、调用rpc接口的代码,ontology_json_rpc.py

import time
import requests
import json

url = 'http://192.168.3.28:20336'
chain_name = 'onto'
def get_block_by_request(height):
    data = {
        "jsonrpc": "2.0",
        "method": "getblock",
        "params": [int(height), 1],
        "id": 1
    }
    while True:
        try:
            r = requests.post(url,json=data)
            response = json.loads(r.text)
            result = response['result']
            if result:
                break
        except:

            time.sleep(5)
    return result
# 通过区块高度获取所有交易地址
def get_transaction_address(height):
    data = {
        "jsonrpc": "2.0",
        "method": "getsmartcodeevent",
        "params": [int(height)],
        "id": 3
    }
    while True:
        try:
            r = requests.post(url,json=data)
            response = json.loads(r.text)
            result = response['result']
            break
        except:
            time.sleep(0.1)
    return result
# 通过交易hash获取交易时间、交易类型
def get_transaction_time(TxHash):
    data = {
        "jsonrpc": "2.0",
        "method": "getrawtransaction",
        "params": [TxHash,1],
        "id": 1
    }
    while True:
        try:
            r = requests.post(url,json=data)
            response = json.loads(r.text)
            result = response['result']
            break
        except:
            time.sleep(0.1)
    return result

  4、针对通过rpc接口获取数据格式不对问题写的爬虫,ontology_riptile.py

import requests
import json
import time
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
}
# 返回数据
def get_ontology_Transactions_info(tx_hash):
    # https://explorer.ont.io/v2/transactions/
    response = while_get(url=f"https://explorer.ont.io/v2/transactions/{tx_hash}",
                         headers=headers, timeout=15)

    block_data = json.loads(response.text)['result']['detail']['transfers']
    if block_data == None:
        return 
    return block_data
# 发起请求
def while_get(url,**kwargs):
    while True:
        try:
            response = requests.get(url,
                                    **kwargs)
            if response.status_code == 200:
                return response
        except Exception as e:
            print(e)
            time.sleep(5)
#解析数据
def analysis_info(tx_hash):
    info = get_ontology_Transactions_info(tx_hash)
    # 交易地址、交易金额
    account_1, account_2 = [],[]
    price = 0
    for lis in info:
        if lis['description'] == 'gasconsume':
            continue
        account_1.append([lis['from_address'], lis['amount']+lis['asset_name']])
        account_2.append([lis['to_address'], lis['amount']+lis['asset_name']])
        price += float(lis['amount'])
    return  account_1,account_2,price
if __name__ == '__main__':
    analysis_info("d7a81db41b2608f2c5da4a4d84b266a8e8f86c244781287c183ee1129e37a9cd")

  5、解析代码,ontology_analysis.py

import json
import logging
from ontology_connect_mysql import connet_mysql
from ontology_json_rpc import get_block_by_request,get_transaction_address,get_transaction_time
from ontology_riptile import analysis_info
from ontology_time import time_transformation
logging.basicConfig(
    filename='log.txt',
    filemode='a',
    format='%(asctime)s %(name)s %(levelname)s %(message)s',
    datefmt='%d-%M-%Y %H:%M:%S',
    level = logging.INFO
)
# 调用连接数据库的方法
db,cursor=connet_mysql()
# 解析数据
def Analysis_transactions_onto(height):
    json_obj = get_block_by_request(height)
    transactions = json_obj['Transactions']
    # transactions不为【】执行解析
    if transactions:
        json_adds_list = get_transaction_address(height)
        try:
            logging.info('区块高度:{}--success'.format(height))
            print(f'当前执行区块高度{height}')
            for adds in json_adds_list:
                # 交易hash
                TxHash = adds['TxHash']
                json_info = get_transaction_time(TxHash)
                # 交易类型
                if int(json_info['TxType']) == 208:
                    TxType = 'Deploy Smart Contract'
                elif int(json_info['TxType']) == 209:
                    TxType = 'Invoke NeoVM Contract'
                elif int(json_info['TxType']) == 210:
                    TxType = 'Invoke WasmVM Contract'
                else:
                    TxType='11111111111111111111111111111111111111111111111111'

                # 交易时间  格式化
                time_ = time_transformation(json_info['Nonce'])
                # 时间戳
                timestamp = json_info['Nonce']
                #交易地址、交易金额
                account_1,account_2=[],[]
                price = 0
                for ac in adds['Notify']:
                    if ac['States'][0] == 'transfer' and len(ac['States'])==4:
                        if ac['States'][3] == 10000000 or ac['States'][3] == 20000:
                                continue
                        else:
                            account_1.append([ac['States'][1],ac['States'][3]])
                            account_2.append([ac['States'][2],ac['States'][3]])
                            price+=ac['States'][3]
                    if ac['States'][0] != 'transfer' and len(ac['States'])==4:
                        account_1, account_2 = [], []
                #         爬虫获取交易信息
                #         account_1, account_2,price = analysis_info("3386e1a0ef49659e3c141c94672adec8549e8d0261617ac03983c97a66604832")
                        account_1, account_2, price = analysis_info(TxHash)
                        # print(account_1, account_2,price)9
                if not (account_1 and account_2):
                    break
                account_1=json.dumps(account_1)
                account_2=json.dumps(account_2)
                sql_transactions = 'insert into transaction(hash,account_1,account_2,type,price,time,timestamp) values (%s,%s,%s,%s,%s,%s,%s)'
                try:
                    cursor.execute(sql_transactions, (TxHash,account_1,account_2,TxType,price,time_,timestamp))
                    db.commit()
                    print(TxHash, ';', TxType, ';', time_, ';', account_1, ';', account_2, ';', price)
                    print("success")
                except Exception as e:
                    print(e)
                    logging.info('error:{}--fail'.format(e))
                    continue
        except Exception as e:
            logging.info('error:{}--fail'.format(e))


if __name__ == '__main__':
    # Analysis_transactions_onto(20000)
    # get_block_by_request(1)
    height = 0
    while True:
        Analysis_transactions_onto(13471)
        height += 1
    db.close()

这几个文件放到一个文件夹下,如果使用pycharm执行的话,存放文件的文件夹要变成根目录,执行以下操作:右击该文件夹,

 

 

  

posted on 2020-05-15 20:01  痴人谈情  阅读(222)  评论(0编辑  收藏  举报