This repository has been archived by the owner on Apr 23, 2024. It is now read-only.
/
compat.py
224 lines (189 loc) · 5.79 KB
/
compat.py
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
import rlp
from hashlib import blake2b
from eth_keys import keys
from eth_utils import to_bytes
from rlp.sedes import (
CountableList,
big_endian_int,
binary
)
from .keystore import sha3
from .types import (
bytearray_to_bytestr,
decode_hex,
encode_hex,
encode_number
)
def noop(value):
return value
#
# block
#
ETH_BLOCK_KWARGS_MAP = {
"id": "hash",
"parentID": "parentHash",
"signer": "miner",
"totalScore": "totalDifficulty",
"txsRoot": "transactionsRoot",
}
BLOCK_FORMATTERS = {
"number": encode_number,
"size": encode_number,
"timestamp": encode_number,
"gasLimit": encode_number,
"gasUsed": encode_number,
"totalScore": encode_number,
}
def thor_block_convert_to_eth_block(block):
return {
ETH_BLOCK_KWARGS_MAP.get(k, k): BLOCK_FORMATTERS.get(k, noop)(v)
for k, v in block.items()
}
#
# receipt
#
def thor_receipt_convert_to_eth_receipt(receipt):
return {
"status": encode_number(0 if receipt["reverted"] else 1),
"transactionHash": receipt["meta"]["txID"],
"transactionIndex": encode_number(0),
"blockNumber": encode_number(receipt["meta"]["blockNumber"]),
"blockHash": receipt["meta"]["blockID"],
"cumulativeGasUsed": encode_number(receipt["gasUsed"]),
"gasUsed": encode_number(receipt["gasUsed"]),
"contractAddress": None if receipt["reverted"] else receipt["outputs"][0]["contractAddress"],
"logs": None if receipt["reverted"] else [
thor_receipt_log_convert_to_eth_log(receipt, index, log)
for index, log in enumerate(receipt["outputs"][0]["events"])
],
}
#
# log
#
def thor_receipt_log_convert_to_eth_log(receipt, index, log):
return {
"type": "mined",
"logIndex": encode_number(index),
"transactionIndex": encode_number(0),
"transactionHash": receipt["meta"]["txID"],
"blockHash": receipt["meta"]["blockID"],
"blockNumber": encode_number(receipt["meta"]["blockNumber"]),
"address": log["address"],
"data": log["data"],
"topics": log["topics"],
}
def thor_log_convert_to_eth_log(address, logs):
if logs:
return [
{
"logIndex": encode_number(index),
"blockNumber": encode_number(log["meta"]["blockNumber"]),
"blockHash": log["meta"]["blockID"],
"transactionHash": log["meta"]["txID"],
"transactionIndex": encode_number(0),
"address": address,
"data": log["data"],
"topics": log["topics"],
}
for index, log in enumerate(logs)
]
return []
#
# transaction
#
def thor_tx_convert_to_eth_tx(tx):
return {
"hash": tx["id"],
"nonce": tx["nonce"],
"blockHash": tx["meta"]["blockID"],
"blockNumber": encode_number(tx["meta"]["blockNumber"]),
"transactionIndex": encode_number(0),
"from": tx["origin"],
"to": tx["clauses"][0]["to"],
"value": tx["clauses"][0]["value"],
"gas": encode_number(tx["gas"]),
"gasPrice": encode_number(1),
"input": tx["clauses"][0]["data"]
}
#
# storage
#
def thor_storage_convert_to_eth_storage(storage):
def _convert_hash(key): return "0x{}".format(encode_hex(sha3(to_bytes(hexstr=key))))
return {
_convert_hash(v["key"]): v
for _, v in storage.items()
}
class Clause(rlp.Serializable):
fields = [
("To", binary),
("Value", big_endian_int),
("Data", binary),
]
def __init__(self, To, Value, Data):
super(Clause, self).__init__(To, Value, Data)
class ThorTransaction(rlp.Serializable):
fields = [
("ChainTag", big_endian_int),
("BlockRef", big_endian_int),
("Expiration", big_endian_int),
("Clauses", CountableList(Clause)), # []
("GasPriceCoef", big_endian_int),
("Gas", big_endian_int),
("DependsOn", binary), # b""
("Nonce", big_endian_int),
("Reserved", CountableList(object)), # []
("Signature", binary), # b""
]
def __init__(self, chain_tag, blk_ref, eth_tx):
receiver = b"" if "to" not in eth_tx else decode_hex(eth_tx["to"])
clauses = [
Clause(
receiver,
eth_tx.get("value", 0),
decode_hex(eth_tx.get("data", "")),
)
]
super(ThorTransaction, self).__init__(chain_tag, blk_ref, (2 ** 32) - 1, clauses, 0, eth_tx.get("gas", 3000000), b"", 0, [], b"")
def sign(self, key):
'''Sign this transaction with a private key.
A potentially already existing signature would be overridden.
'''
h = blake2b(digest_size=32)
h.update(rlp.encode(self, ThorTransaction.exclude(["Signature"])))
rawhash = h.digest()
if key in (0, "", b"\x00" * 32, "0" * 64):
raise Exception("Zero privkey cannot sign")
if len(key) == 64:
key = to_bytes(hexstr=key) # we need a binary key
pk = keys.PrivateKey(key)
self.Signature = pk.sign_msg_hash(rawhash).to_bytes()
#
# estimate eth gas
#
TX_GAS = 5000
CLAUSE_GAS = 21000 - TX_GAS
CLAUSE_GAS_CONTRACT_CREATION = 53000 - TX_GAS
TX_DATA_ZERO_GAS = 4
TX_DATA_NON_ZERO_GAS = 68
def data_gas(data):
data = decode_hex(data)
if len(data) == 0:
return 0
z = 0
nz = 0
for byt in data:
if byt == 0:
z += 1
else:
nz += 1
return (TX_DATA_ZERO_GAS * z) + (TX_DATA_NON_ZERO_GAS * nz)
def intrinsic_gas(transaction):
total = TX_GAS
gas = data_gas(transaction["data"])
total += gas
cgas = CLAUSE_GAS
if "to" not in transaction:
cgas = CLAUSE_GAS_CONTRACT_CREATION
total += cgas
return total