This repository has been archived by the owner on Nov 15, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 192
/
Helper.py
221 lines (173 loc) · 6.25 KB
/
Helper.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
from base58 import b58decode
from logzero import logger
import binascii
from neo.Blockchain import GetBlockchain, GetStateReader
from neocore.Cryptography.Crypto import Crypto
from neocore.IO.BinaryWriter import BinaryWriter
from neocore.UInt160 import UInt160
from neo.IO.MemoryStream import StreamManager
from neo.VM.ScriptBuilder import ScriptBuilder
from neo.SmartContract.ApplicationEngine import ApplicationEngine
from neocore.Fixed8 import Fixed8
from neo.SmartContract import TriggerType
from neo.Settings import settings
from neo.EventHub import events
class Helper:
@staticmethod
def WeightedFilter(list):
raise NotImplementedError()
@staticmethod
def WeightedAverage(list):
raise NotImplementedError()
@staticmethod
def GetHashData(hashable):
"""
Get the data used for hashing.
Args:
hashable (neo.IO.Mixins.SerializableMixin): object extending SerializableMixin
Returns:
bytes:
"""
ms = StreamManager.GetStream()
writer = BinaryWriter(ms)
hashable.SerializeUnsigned(writer)
ms.flush()
retVal = ms.ToArray()
StreamManager.ReleaseStream(ms)
return retVal
@staticmethod
def Sign(verifiable, keypair):
"""
Sign the `verifiable` object with the private key from `keypair`.
Args:
verifiable:
keypair (neocore.KeyPair):
Returns:
bool: True if successfully signed. False otherwise.
"""
prikey = bytes(keypair.PrivateKey)
hashdata = verifiable.GetHashData()
res = Crypto.Default().Sign(hashdata, prikey)
return res
@staticmethod
def ToArray(value):
"""
Serialize the given `value` to a an array of bytes.
Args:
value (neo.IO.Mixins.SerializableMixin): object extending SerializableMixin.
Returns:
bytes: hex formatted bytes
"""
ms = StreamManager.GetStream()
writer = BinaryWriter(ms)
value.Serialize(writer)
retVal = ms.ToArray()
StreamManager.ReleaseStream(ms)
return retVal
@staticmethod
def ToStream(value):
"""
Serialize the given `value` to a an array of bytes.
Args:
value (neo.IO.Mixins.SerializableMixin): object extending SerializableMixin.
Returns:
bytes: not hexlified
"""
ms = StreamManager.GetStream()
writer = BinaryWriter(ms)
value.Serialize(writer)
retVal = ms.getvalue()
StreamManager.ReleaseStream(ms)
return retVal
@staticmethod
def AddrStrToScriptHash(address):
"""
Convert a public address to a script hash.
Args:
address (str): base 58 check encoded public address.
Raises:
ValueError: if the address length of address version is incorrect.
Exception: if the address checksum fails.
Returns:
UInt160:
"""
data = b58decode(address)
if len(data) != 25:
raise ValueError('Not correct Address, wrong length.')
if data[0] != settings.ADDRESS_VERSION:
raise ValueError('Not correct Coin Version')
checksum = Crypto.Default().Hash256(data[:21])[:4]
if checksum != data[21:]:
raise Exception('Address format error')
return UInt160(data=data[1:21])
@staticmethod
def ToScriptHash(scripts):
"""
Get a hash of the provided message using the ripemd160 algorithm.
Args:
scripts (str): message to hash.
Returns:
str: hash as a double digit hex string.
"""
return Crypto.Hash160(scripts)
@staticmethod
def RawBytesToScriptHash(raw):
"""
Get a hash of the provided raw bytes using the ripemd160 algorithm.
Args:
raw (bytes): byte array of raw bytes. i.e. b'\xAA\xBB\xCC'
Returns:
UInt160:
"""
rawh = binascii.unhexlify(raw)
rawhashstr = binascii.unhexlify(bytes(Crypto.Hash160(rawh), encoding='utf-8'))
return UInt160(data=rawhashstr)
@staticmethod
def VerifyScripts(verifiable):
"""
Verify the scripts of the provided `verifiable` object.
Args:
verifiable (neo.IO.Mixins.VerifiableMixin):
Returns:
bool: True if verification is successful. False otherwise.
"""
try:
hashes = verifiable.GetScriptHashesForVerifying()
except Exception as e:
logger.error("couldn't get script hashes %s " % e)
return False
if len(hashes) != len(verifiable.Scripts):
return False
blockchain = GetBlockchain()
for i in range(0, len(hashes)):
verification = verifiable.Scripts[i].VerificationScript
if len(verification) == 0:
sb = ScriptBuilder()
sb.EmitAppCall(hashes[i].Data)
verification = sb.ToArray()
else:
verification_hash = Crypto.ToScriptHash(verification, unhex=False)
if hashes[i] != verification_hash:
return False
state_reader = GetStateReader()
engine = ApplicationEngine(TriggerType.Verification, verifiable, blockchain, state_reader, Fixed8.Zero())
engine.LoadScript(verification)
invocation = verifiable.Scripts[i].InvocationScript
engine.LoadScript(invocation)
try:
success = engine.Execute()
state_reader.ExecutionCompleted(engine, success)
except Exception as e:
state_reader.ExecutionCompleted(engine, False, e)
if engine.ResultStack.Count != 1 or not engine.ResultStack.Pop().GetBoolean():
Helper.EmitServiceEvents(state_reader)
return False
Helper.EmitServiceEvents(state_reader)
return True
@staticmethod
def IToBA(value):
return [1 if digit == '1' else 0 for digit in bin(value)[2:]]
@staticmethod
def EmitServiceEvents(state_reader):
for event in state_reader.events_to_dispatch:
events.emit(event.event_type, event)