def test_invocation_assetcreate_block(self): hexdata = binascii.unhexlify(self.asset_create_block) block = Helper.AsSerializableWithType(hexdata, 'neo.Core.Block.Block') self.assertEqual(block.Index, self.asset_create_index) result = Blockchain.Default().Persist(block) self.assertTrue(result) # now the asset that was created should be there sn = Blockchain.Default()._db.snapshot() assets = DBCollection(Blockchain.Default()._db, sn, DBPrefix.ST_Asset, AssetState) newasset = assets.TryGet(self.asset_create_id) self.assertIsNotNone(newasset) self.assertEqual(newasset.AssetType, 96) self.assertEqual(newasset.Precision, 2) self.assertEqual(Crypto.ToAddress(newasset.Admin), self.asset_admin) self.assertEqual(Crypto.ToAddress(newasset.Issuer), self.asset_admin) self.assertIsInstance(newasset.AssetId, UInt256) self.assertEqual(newasset.AssetId.ToBytes(), self.asset_create_id)
def ToJson(self): return { 'assetId': self.AssetId.ToString(), 'assetType': self.AssetType, 'name': self.GetName(), 'amount': self.Amount.value, 'available': self.Available.value, 'precision': self.Precision, 'fee': self.Fee.value, 'address': self.FeeAddress.ToString(), 'owner': self.Owner.ToString(), 'admin': Crypto.ToAddress(self.Admin), 'issuer': Crypto.ToAddress(self.Issuer), 'expiration': self.Expiration, 'is_frozen': self.IsFrozen }
def Addresses(self): result = [] for addr in Address.select(): addr_str = Crypto.ToAddress(UInt160(data=addr.ScriptHash)) result.append(addr_str) return result
def ImportMultiSigContractAddr(wallet, args): if len(args) < 4: print( "please specify multisig contract like such: 'import multisig {pubkey in wallet} {minimum # of signatures required} {signing pubkey 1} {signing pubkey 2}...'" ) return if wallet is None: print("please open a wallet") return pubkey = get_arg(args, 0) m = get_arg(args, 1) publicKeys = args[2:] if publicKeys[1]: pubkey_script_hash = Crypto.ToScriptHash(pubkey, unhex=True) verification_contract = Contract.CreateMultiSigContract( pubkey_script_hash, int(m), publicKeys) address = verification_contract.Address wallet.AddContract(verification_contract) print("Added multi-sig contract address %s to wallet" % address) return 'Hello'
def __init__(self, trigger_type, container, table, service, gas, testMode=False): super(ApplicationEngine, self).__init__(container=container,crypto=Crypto.Default(), table=table, service=service) self.Trigger = trigger_type self.gas_amount = self.gas_free + gas.value self.testMode = testMode
def GetBalance(self, wallet, address, as_string=False): if type(address) is UInt160: address = Crypto.ToAddress(address) invoke_args = [ self.ScriptHash.ToString(), parse_param('balanceOf'), [parse_param(address)] ] tx, fee, balanceResults, num_ops = TestInvokeContract( wallet, invoke_args, None, False) try: val = balanceResults[0].GetBigInteger() precision_divisor = pow(10, self.decimals) balance = Decimal(val) / Decimal(precision_divisor) if as_string: formatter_str = '.%sf' % self.decimals balance_str = format(balance, formatter_str) return balance_str return balance except Exception as e: logger.error("could not get balance: %s " % e) traceback.print_stack() return 0
def ToJson(self, verbose=False): assets = self.GetCoinAssets() if Blockchain.Default().Height == 0: percent_synced = 0 else: percent_synced = int(100 * self._current_height / Blockchain.Default().Height) jsn = {} jsn['path'] = self._path addresses = [ Crypto.ToAddress(UInt160(data=addr.ScriptHash)) for addr in Address.select() ] jsn['addresses'] = addresses jsn['height'] = self._current_height jsn['percent_synced'] = percent_synced jsn['balances'] = [ "%s : %s " % (asset.ToString(), self.GetBalance(asset).value / Fixed8.D) for asset in assets ] jsn['public_keys'] = self.PubKeys() if verbose: jsn['coins'] = [coin.ToJson() for coin in self.FindUnspentCoins()] jsn['transactions'] = [ tx.ToJson() for tx in self.GetTransactions() ] return jsn
def ScriptHash(self): if self._scriptHash is None: self._scriptHash = Crypto.ToScriptHash(self.Script) return self._scriptHash
def test_issue_tx(self): miner_tx = MinerTransaction() miner_tx.Nonce = 2083236893 share_tx = GetSystemShare() coin_tx = GetSystemCoin() script = Contract.CreateMultiSigRedeemScript(int(len(Blockchain.StandbyValidators()) / 2) + 1, Blockchain.StandbyValidators()) if Settings.MAGIC == 1953787457: self.assertEqual(script, self.contractraw) out = Crypto.ToScriptHash(script) output = TransactionOutput( share_tx.Hash, Blockchain.SystemShare().Amount, out ) script = Witness( bytearray(0), bytearray(PUSHT)) issue_tx = IssueTransaction([],[output],[], [script]) self.assertEqual(issue_tx.GetHashData(), self.issuetx_rraw) self.assertEqual(issue_tx.Hash.ToBytes(), self.gen_issue_tx_id)
def Contract_Create(self, engine): script = engine.EvaluationStack.Pop().GetByteArray() if len(script) > 1024 * 1024: return False param_list = engine.EvaluationStack.Pop().GetByteArray() if len(param_list) > 252: return False return_type = int(engine.EvaluationStack.Pop().GetBigInteger()) needs_storage = engine.EvaluationStack.Pop().GetBoolean() if len(engine.EvaluationStack.Peek().GetByteArray()) > 252: return False name = engine.EvaluationStack.Pop().GetByteArray() if len(engine.EvaluationStack.Peek().GetByteArray()) > 252: return False code_version = engine.EvaluationStack.Pop().GetByteArray() if len(engine.EvaluationStack.Peek().GetByteArray()) > 252: return False author = engine.EvaluationStack.Pop().GetByteArray() if len(engine.EvaluationStack.Peek().GetByteArray()) > 252: return False email = engine.EvaluationStack.Pop().GetByteArray() if len(engine.EvaluationStack.Peek().GetByteArray()) > 65536: return False description = engine.EvaluationStack.Pop().GetByteArray() hash = Crypto.ToScriptHash(script, unhex=False) contract = self._contracts.TryGet(hash.ToBytes()) if contract is None: code = FunctionCode(script=script, param_list=param_list, return_type=return_type) contract = ContractState(code, needs_storage, name, code_version, author, email, description) self._contracts.GetAndChange(code.ScriptHash().ToBytes(), contract) self._contracts_created[hash.ToBytes()] = UInt160( data=engine.CurrentContext.ScriptHash()) engine.EvaluationStack.PushT(StackItem.FromInterface(contract)) # print("*****************************************************") # print("CREATED CONTRACT %s " % hash.ToBytes()) # print("*****************************************************") return True
def PrivateKeyFromWIF(wif): """ Get the private key from a WIF key Args: wif (str): The wif key Returns: bytes: The private key """ if wif is None or len(wif) is not 52: raise ValueError('Please provide a wif with a length of 52 bytes (LEN: {0:d})'.format(len(wif))) data = base58.b58decode(wif) length = len(data) if length is not 38 or data[0] is not 0x80 or data[33] is not 0x01: raise ValueError("Invalid format!") checksum = Crypto.Hash256(data[0:34])[0:4] if checksum != data[34:]: raise ValueError("Invalid WIF Checksum!") return data[1:33]
def Storage_Delete(self, engine): context = engine.EvaluationStack.Pop().GetInterface() if not self.CheckStorageContext(context): return False key = engine.EvaluationStack.Pop().GetByteArray() storage_key = StorageKey(script_hash=context.ScriptHash, key=key) keystr = key if len(key) == 20: keystr = Crypto.ToAddress(UInt160(data=key)) dispatch_smart_contract_event(SmartContractEvent.STORAGE_DELETE, keystr, context.ScriptHash, Blockchain.Default().Height, engine.ScriptContainer.Hash, test_mode=engine.testMode) self._storages.Remove(storage_key.GetHashCodeBytes()) return True
def InvokeWithdrawTx(wallet, tx, contract_hash): # print("withdraw tx 1 %s " % json.dumps(tx.ToJson(), indent=4)) requestor_contract = wallet.GetDefaultContract() tx.Attributes = [ TransactionAttribute(usage=TransactionAttributeUsage.Script, data=Crypto.ToScriptHash( requestor_contract.Script).Data) ] withdraw_contract_state = Blockchain.Default().GetContract( contract_hash.encode('utf-8')) withdraw_verification = None if withdraw_contract_state is not None: reedeem_script = withdraw_contract_state.Code.Script.hex() # there has to be at least 1 param, and the first # one needs to be a signature param param_list = bytearray(b'\x00') # if there's more than one param # we set the first parameter to be the signature param if len(withdraw_contract_state.Code.ParameterList) > 1: param_list = bytearray(withdraw_contract_state.Code.ParameterList) param_list[0] = 0 verification_contract = Contract.Create( reedeem_script, param_list, requestor_contract.PublicKeyHash) address = verification_contract.Address withdraw_verification = verification_contract context = ContractParametersContext(tx) wallet.Sign(context) context.Add(withdraw_verification, 0, 0) if context.Completed: tx.scripts = context.GetScripts() print("withdraw tx %s " % json.dumps(tx.ToJson(), indent=4)) wallet.SaveTransaction(tx) relayed = NodeLeader.Instance().Relay(tx) if relayed: print("Relayed Withdrawal Tx: %s " % tx.Hash.ToString()) return True else: print("Could not relay witdrawal tx %s " % tx.Hash.ToString()) else: print("Incomplete signature")
def SearchAssetState(self, query): res = [] sn = self._db.snapshot() assets = DBCollection(self._db, sn, DBPrefix.ST_Asset, AssetState) keys = assets.Keys for item in keys: asset = assets.TryGet(keyval=item) if query in asset.Name.decode('utf-8'): res.append(asset) elif query in Crypto.ToAddress(asset.Issuer): res.append(asset) elif query in Crypto.ToAddress(asset.Admin): res.append(asset) sn.close() return res
def notify_transfer(event_args): tfrom = event_args[0].GetByteArray() tto = event_args[1].GetByteArray() tamount = event_args[2].GetBigInteger() fromaddr = tfrom toaddr = tto try: if len(fromaddr) == 20: fromaddr = Crypto.ToAddress(UInt160(data=tfrom)) if len(toaddr) == 20: toaddr = Crypto.ToAddress(UInt160(data=tto)) except Exception as e: print("Couldnt convert from/to to address %s " % e) print("[Neo.Runtime.Notify :: Transfer] %s from %s to %s " % (tamount, fromaddr, toaddr))
def notify_refund(event_args): to = event_args[0].GetByteArray() if len(to) == 20: to = Crypto.ToAddress(UInt160(data=to)) print("[Neo.Runtime.Notify :: REFUND] TO %s " % to) amount = event_args[1].GetBigInteger() print("[Neo.Runtime.Notify :: REFUND] amount %s " % amount)
def Blockchain_GetAccount(self, engine): hash = UInt160(data=engine.EvaluationStack.Pop().GetByteArray()) address = Crypto.ToAddress(hash).encode('utf-8') account = self._accounts.TryGet(address) if account: engine.EvaluationStack.PushT(StackItem.FromInterface(account)) return True return False
def test_to_address_alt_version(self): original_version = settings.ADDRESS_VERSION settings.ADDRESS_VERSION = 42 script_hash = UInt160( data=b'B\x11#x\xff\xa3,Le\xd5\x13\xaa5\x06\x89\xdf\xf68\x11T') self.assertEqual(Crypto.ToAddress(script_hash), 'J1DfV2jS511SMtP6dH5ckr3Nwf26kbFx7s') settings.ADDRESS_VERSION = original_version
def notify_other(event_name, event_args): to = event_args[0].GetByteArray() if len(to) == 20: to = Crypto.ToAddress(UInt160(data=to)) ename = event_name.upper() print("[Neo.Runtime.Notify :: %s] TO %s " % (ename, to)) amount = event_args[1].GetBigInteger() print("[Neo.Runtime.Notify :: %s] amount %s " % (ename, amount))
def ToScriptHash(self, address): data = b58decode(address) if len(data) != 25: raise ValueError('Not correct Address, wrong length.') if data[0] != self.AddressVersion: 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])
def test_neon_sig(self): key = KeyPair(priv_key=self.nmpk) hhex = hashlib.sha256(binascii.unhexlify(self.nmsg)).hexdigest() self.assertEqual(hhex, self.hashhex) sig = Crypto.Sign(self.nmsg, key.PrivateKey, key.PublicKey) self.assertEqual(sig.hex(), self.neon_sig)
def Export(self): data = bytearray(38) data[0] = 0x80 data[1:33] = self.PrivateKey[0:32] data[33] = 0x01 checksum = Crypto.Default().Hash256(data[0:34]) data[34:38] = checksum[0:4] b58 = base58.b58encode(bytes(data)) return b58
def ContainsKey(self, public_key): """ Test if the wallet contains the supplied public key. Args: public_key (edcsa.Curve.point): a public key to test for its existance. i.e. KeyPair.PublicKey Returns: bool: True if exists, False otherwise. """ return self.ContainsKeyHash( Crypto.ToScriptHash(public_key.encode_point(True), unhex=False))
def ToJson(self): jsn = super(RegisterTransaction, self).ToJson() asset = { 'type': self.AssetType, 'name': self.Name.decode('utf-8'), 'amount': self.Amount.value, 'precision': self.Precision if type(self.Precision) is int else self.Precision.decode('utf-8'), 'owner': self.Owner.ToString(), 'admin': Crypto.ToAddress(self.Admin) } jsn['asset'] = asset return jsn
def ToJson(self): json = super(AccountState, self).ToJson() addr = Crypto.ToAddress(self.ScriptHash) json['script_hash'] = addr json['frozen'] = self.IsFrozen json['votes'] = [v.hex() for v in self.Votes] balances = {} for key, value in self.Balances.items(): balances[key.ToString()] = str(value.value / Fixed8.D) json['balances'] = balances return json
def Storage_Get(self, engine): context = None try: item = engine.EvaluationStack.Pop() context = item.GetInterface('neo.SmartContract.StorageContext.StorageContext') shash = context.ScriptHash except Exception as e: print("could not get storage context %s " % e) return False contract = Blockchain.Default().GetContract(context.ScriptHash.ToBytes()) if contract is not None: if not contract.HasStorage: return False else: return False key = engine.EvaluationStack.Pop().GetByteArray() storage_key = StorageKey(script_hash=context.ScriptHash, key=key) item = Blockchain.Default().GetStorageItem(storage_key) keystr = key valStr = bytearray(0) if item is not None: valStr = bytearray(item.Value) if len(key) == 20: keystr = Crypto.ToAddress(UInt160(data=key)) try: valStr = int.from_bytes(valStr, 'little') except Exception as e: print("couldnt convert %s to number: %s " % (valStr, e)) if item is not None: print("[Neo.Storage.Get] [Script:%s] [%s] -> %s " % (context.ScriptHash, keystr, valStr)) engine.EvaluationStack.PushT(bytearray(item.Value)) else: print("[Neo.Storage.Get] [Script:%s] [%s] -> 0 " % (context.ScriptHash, keystr)) engine.EvaluationStack.PushT(bytearray(0)) return True
def Storage_Get(self, engine): context = None try: item = engine.EvaluationStack.Pop() context = item.GetInterface() shash = context.ScriptHash except Exception as e: logger.error("could not get storage context %s " % e) return False if not self.CheckStorageContext(context): return False key = engine.EvaluationStack.Pop().GetByteArray() storage_key = StorageKey(script_hash=context.ScriptHash, key=key) item = self._storages.TryGet(storage_key.GetHashCodeBytes()) keystr = key valStr = bytearray(0) if item is not None: valStr = bytearray(item.Value) if len(key) == 20: keystr = Crypto.ToAddress(UInt160(data=key)) try: valStr = int.from_bytes(valStr, 'little') except Exception as e: pass if item is not None: engine.EvaluationStack.PushT(bytearray(item.Value)) else: engine.EvaluationStack.PushT(bytearray([0])) dispatch_smart_contract_event(SmartContractEvent.STORAGE_GET, '%s -> %s' % (keystr, valStr), context.ScriptHash, Blockchain.Default().Height, engine.ScriptContainer.Hash, test_mode=engine.testMode) return True
def PubKeys(self): keys = self.LoadKeyPairs() jsn = [] for k in keys.values(): addr = Crypto.ToAddress(k.PublicKeyHash) pub = k.PublicKey.encode_point(True) signature_contract = None for ct in self._contracts.values(): if ct.PublicKeyHash == k.PublicKeyHash: signature_contract = ct addr = signature_contract.Address jsn.append({'Address': addr, 'Public Key': pub.decode('utf-8')}) return jsn
def PrivateKeyFromWIF(wif): if wif is None: raise Exception('Please provide wif') data = base58.b58decode(wif) length = len(data) if length is not 38 and data[0] is not 0x80 and data[33] is not 0x01: raise Exception("Invalid format!") checksum = Crypto.Hash256(data[0:34])[0:4] if checksum != data[34:]: raise Exception("Invalid WIF Checksum") return data[1:33]
def createWallet(self): # Creating wallet instance self.Wallet = UserWallet.Open(path=self.walletpath, password=self.walletpass) print("AddressVersion: ", self.Wallet.AddressVersion) self._walletdb_loop = task.LoopingCall(self.Wallet.ProcessBlocks) self._walletdb_loop.start(1) self.wallet_sh = self.Wallet.GetStandardAddress() self.wallet_addr = Crypto.ToAddress(self.wallet_sh) for addr in self.Wallet.ToJson()['public_keys']: if addr['Address'] == self.wallet_addr: self.wallet_pub = addr['Public Key'] print('Wallet SH', self.wallet_sh) print('Wallet Addr', self.wallet_addr) print('Wallet Pub', self.wallet_pub)