开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
捐赠
捐赠前请先登录
扫描微信二维码支付
取消
支付完成
支付提示
将跳转至支付宝完成支付
确定
取消
1 Star 0 Fork 3

kentzhang/python-agent

forked from kentzhang/python-sdk
加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
master
分支 (10)
master
gm2026
crypto
refactor202604
dev310
liquid
tassl
dev
dev2020
gm
master
分支 (10)
master
gm2026
crypto
refactor202604
dev310
liquid
tassl
dev
dev2020
gm
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
master
分支 (10)
master
gm2026
crypto
refactor202604
dev310
liquid
tassl
dev
dev2020
gm
python-agent
/
utils
/
encoding.py
python-agent
/
utils
/
encoding.py
encoding.py 9.88 KB
一键复制 编辑 原始数据 按行查看 历史
kentzhang 提交于 2020年03月05日 01:55 +08:00 . autopep8 format & make signtx together (ecdsa/gm)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
# String encodings and numeric representations
import json
import re
from eth_abi.encoding import (
BaseArrayEncoder,
)
from eth_utils import (
add_0x_prefix,
big_endian_to_int,
decode_hex,
encode_hex,
int_to_big_endian,
is_boolean,
is_bytes,
is_hex,
is_integer,
is_list_like,
remove_0x_prefix,
to_hex,
)
from eth_utils.toolz import (
curry,
)
from hexbytes import (
HexBytes,
)
from utils.abi import (
is_address_type,
is_array_type,
is_bool_type,
is_bytes_type,
is_int_type,
is_string_type,
is_uint_type,
size_of_type,
sub_type_of_array_type,
)
from utils.validation import (
assert_one_val,
validate_abi_type,
validate_abi_value,
)
from utils.datastructures import (
AttributeDict,
)
def hex_encode_abi_type(abi_type, value, force_size=None):
"""
Encodes value into a hex string in format of abi_type
"""
validate_abi_type(abi_type)
validate_abi_value(abi_type, value)
data_size = force_size or size_of_type(abi_type)
if is_array_type(abi_type):
sub_type = sub_type_of_array_type(abi_type)
return "".join([remove_0x_prefix(hex_encode_abi_type(sub_type, v, 256)) for v in value])
elif is_bool_type(abi_type):
return to_hex_with_size(value, data_size)
elif is_uint_type(abi_type):
return to_hex_with_size(value, data_size)
elif is_int_type(abi_type):
return to_hex_twos_compliment(value, data_size)
elif is_address_type(abi_type):
return pad_hex(value, data_size)
elif is_bytes_type(abi_type):
if is_bytes(value):
return encode_hex(value)
else:
return value
elif is_string_type(abi_type):
return to_hex(text=value)
else:
raise ValueError(
"Unsupported ABI type: {0}".format(abi_type)
)
def to_hex_twos_compliment(value, bit_size):
"""
Converts integer value to twos compliment hex representation with given bit_size
"""
if value >= 0:
return to_hex_with_size(value, bit_size)
value = (1 << bit_size) + value
hex_value = hex(value)
hex_value = hex_value.rstrip("L")
return hex_value
def to_hex_with_size(value, bit_size):
"""
Converts a value to hex with given bit_size:
"""
return pad_hex(to_hex(value), bit_size)
def pad_hex(value, bit_size):
"""
Pads a hex string up to the given bit_size
"""
value = remove_0x_prefix(value)
return add_0x_prefix(value.zfill(int(bit_size / 4)))
def trim_hex(hexstr):
if hexstr.startswith('0x0'):
hexstr = re.sub('^0x0+', '0x', hexstr)
if hexstr == '0x':
hexstr = '0x0'
return hexstr
def to_int(value=None, hexstr=None, text=None):
"""
Converts value to it's integer representation.
Values are converted this way:
* value:
* bytes: big-endian integer
* bool: True => 1, False => 0
* hexstr: interpret hex as integer
* text: interpret as string of digits, like '12' => 12
"""
assert_one_val(value, hexstr=hexstr, text=text)
if hexstr is not None:
return int(hexstr, 16)
elif text is not None:
return int(text)
elif isinstance(value, bytes):
return big_endian_to_int(value)
elif isinstance(value, str):
raise TypeError("Pass in strings with keyword hexstr or text")
else:
return int(value)
@curry
def pad_bytes(fill_with, num_bytes, unpadded):
return unpadded.rjust(num_bytes, fill_with)
zpad_bytes = pad_bytes(b'0円')
def to_bytes(primitive=None, hexstr=None, text=None):
assert_one_val(primitive, hexstr=hexstr, text=text)
if is_boolean(primitive):
return b'\x01' if primitive else b'\x00'
elif isinstance(primitive, bytes):
return primitive
elif is_integer(primitive):
return to_bytes(hexstr=to_hex(primitive))
elif hexstr is not None:
if len(hexstr) % 2:
hexstr = '0x0' + remove_0x_prefix(hexstr)
return decode_hex(hexstr)
elif text is not None:
return text.encode('utf-8')
raise TypeError("expected an int in first arg, or keyword of hexstr or text")
def to_text(primitive=None, hexstr=None, text=None):
assert_one_val(primitive, hexstr=hexstr, text=text)
if hexstr is not None:
return to_bytes(hexstr=hexstr).decode('utf-8')
elif text is not None:
return text
elif isinstance(primitive, str):
return to_text(hexstr=primitive)
elif isinstance(primitive, bytes):
return primitive.decode('utf-8')
elif is_integer(primitive):
byte_encoding = int_to_big_endian(primitive)
return to_text(byte_encoding)
raise TypeError("Expected an int, bytes or hexstr.")
@curry
def text_if_str(to_type, text_or_primitive):
"""
Convert to a type, assuming that strings can be only unicode text (not a hexstr)
@param to_type is a function that takes the arguments (primitive, hexstr=hexstr, text=text),
eg~ to_bytes, to_text, to_hex, to_int, etc
@param hexstr_or_primitive in bytes, str, or int.
"""
if isinstance(text_or_primitive, str):
(primitive, text) = (None, text_or_primitive)
else:
(primitive, text) = (text_or_primitive, None)
return to_type(primitive, text=text)
@curry
def hexstr_if_str(to_type, hexstr_or_primitive):
"""
Convert to a type, assuming that strings can be only hexstr (not unicode text)
@param to_type is a function that takes the arguments (primitive, hexstr=hexstr, text=text),
eg~ to_bytes, to_text, to_hex, to_int, etc
@param text_or_primitive in bytes, str, or int.
"""
if isinstance(hexstr_or_primitive, str):
(primitive, hexstr) = (None, hexstr_or_primitive)
if remove_0x_prefix(hexstr) and not is_hex(hexstr):
raise ValueError(
"when sending a str, it must be a hex string. Got: {0!r}".format(
hexstr_or_primitive,
)
)
else:
(primitive, hexstr) = (hexstr_or_primitive, None)
return to_type(primitive, hexstr=hexstr)
class FriendlyJsonSerde:
"""
Friendly JSON serializer & deserializer
When encoding or decoding fails, this class collects
information on which fields failed, to show more
helpful information in the raised error messages.
"""
def _json_mapping_errors(self, mapping):
for key, val in mapping.items():
try:
self._friendly_json_encode(val)
except TypeError as exc:
yield "%r: because (%s)" % (key, exc)
def _json_list_errors(self, iterable):
for index, element in enumerate(iterable):
try:
self._friendly_json_encode(element)
except TypeError as exc:
yield "%d: because (%s)" % (index, exc)
def _friendly_json_encode(self, obj, cls=None):
try:
encoded = json.dumps(obj, cls=cls)
return encoded
except TypeError as full_exception:
if hasattr(obj, 'items'):
item_errors = '; '.join(self._json_mapping_errors(obj))
raise TypeError("dict had unencodable value at keys: {{{}}}".format(item_errors))
elif is_list_like(obj):
element_errors = '; '.join(self._json_list_errors(obj))
raise TypeError("list had unencodable value at index: [{}]".format(element_errors))
else:
raise full_exception
def json_decode(self, json_str):
try:
decoded = json.loads(json_str)
return decoded
except json.decoder.JSONDecodeError as exc:
err_msg = 'Could not decode {} because of {}.'.format(repr(json_str), exc)
# Calling code may rely on catching JSONDecodeError to recognize bad json
# so we have to re-raise the same type.
raise json.decoder.JSONDecodeError(err_msg, exc.doc, exc.pos)
def json_encode(self, obj, cls=None):
try:
return self._friendly_json_encode(obj, cls=cls)
except TypeError as exc:
raise TypeError("Could not encode to JSON: {}".format(exc))
def to_4byte_hex(hex_or_str_or_bytes):
size_of_4bytes = 4 * 8
byte_str = hexstr_if_str(to_bytes, hex_or_str_or_bytes)
if len(byte_str) > 4:
raise ValueError(
'expected value of size 4 bytes. Got: %d bytes' % len(byte_str)
)
hex_str = encode_hex(byte_str)
return pad_hex(hex_str, size_of_4bytes)
class DynamicArrayPackedEncoder(BaseArrayEncoder):
is_dynamic = True
def encode(self, value):
encoded_elements = self.encode_elements(value)
encoded_value = encoded_elements
return encoded_value
# TODO: Replace with eth-abi packed encoder once web3 requires eth-abi>=2
def encode_single_packed(_type, value):
import codecs
from eth_abi import (
grammar as abi_type_parser,
)
from eth_abi.registry import has_arrlist, registry
abi_type = abi_type_parser.parse(_type)
if has_arrlist(_type):
item_encoder = registry.get_encoder(abi_type.item_type.to_type_str())
if abi_type.arrlist[-1] != 1:
return DynamicArrayPackedEncoder(item_encoder=item_encoder).encode(value)
else:
raise NotImplementedError(
"Fixed arrays are not implemented in this packed encoder prototype")
elif abi_type.base == "string":
return codecs.encode(value, 'utf8')
elif abi_type.base == "bytes":
return value
class Web3JsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, AttributeDict):
return {k: v for k, v in obj.items()}
if isinstance(obj, HexBytes):
return obj.hex()
return json.JSONEncoder.default(self, obj)
def to_json(obj):
'''
Convert a complex object (like a transaction object) to a JSON string
'''
return FriendlyJsonSerde().json_encode(obj, cls=Web3JsonEncoder)
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

fisco bcos python sdk
暂无标签
MIT
使用 MIT 开源许可协议
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/coderkent/python-agent.git
git@gitee.com:coderkent/python-agent.git
coderkent
python-agent
python-agent
master
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /