一、代码:
import base64
import json
import grpc
from google.protobuf.json_format import MessageToDict
from google.protobuf.any_pb2 import Any
from turbo_config_file import common_pb2, chain_admin_pb2, chain_admin_pb2_grpc
from common.layer2_sig import get_sig_value
class ChainAdminGrpc:
def __init__(self, host):
self.any_msg = Any()
self.host = host
def register_chain_req(self, **presc_par):
regulatory_analysis = {
"chain_symbol": presc_par['chain_id'],
"chain_name": presc_par['chain_name'],
"chain_intro": presc_par['chain_intro'],
"space_id": presc_par['space_id'],
}
child_msg = chain_admin_pb2.Body(**regulatory_analysis)
self.any_msg.Pack(child_msg)
# 构造签名所需的参数
signature_reference = {
"body": {
"type_url": self.any_msg.type_url,
"value": base64.b64encode(self.any_msg.value).decode('utf-8')
},
"nonce": presc_par['nonce'],
"chain_symbol": presc_par['chain_symbol'],
"pubkey": presc_par['pub_k'],
"privkey": presc_par['pri_k'],
"sign-type": presc_par['sign_type'],
"memo": presc_par['memo']
}
# 获得签名值
sig = get_sig_value(**signature_reference)
try:
request_body = {
"body": {
"type_url": self.any_msg.type_url,
"value": self.any_msg.value
},
"auth_info": {
"nonce": presc_par['nonce'],
"chain_symbol": presc_par['chain_symbol'],
"public_keys": [{
"type": presc_par['sign_type'],
"key": presc_par['pub_k']
}]
},
"signatures": [sig],
"memo": presc_par['memo']
}
with grpc.insecure_channel(self.host) as channel:
stub = chain_admin_pb2_grpc.ServiceChainStub(channel)
response = stub.RegisterChain(common_pb2.Request(**request_body))
resp_data = MessageToDict(response)
json_string = json.dumps(resp_data)
return json_string
except TypeError as e:
return {"code": "002001", "msg": "param invalid", "error": str(e)}
except ValueError as e:
return {"code": "002001", "msg": "param invalid", "error": str(e)}
except Exception as e:
return {"code": "002001", "msg": "unknown error", "error": str(e)}
二、代码解释:
import base64
import json
import gr