_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3 values | text stringlengths 75 19.8k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q32700 | AccountState.Clone | train | def Clone(self):
"""
Clone self.
Returns:
AccountState:
"""
return AccountState(self.ScriptHash, self.IsFrozen, self.Votes, self.Balances) | python | {
"resource": ""
} |
q32701 | AccountState.HasBalance | train | def HasBalance(self, assetId):
"""
Flag indicating if the asset has a balance.
Args:
assetId (UInt256):
Returns:
bool: True if a balance is present. False otherwise.
"""
for key, fixed8 in self.Balances.items():
if key == assetId:
return True
return False | python | {
"resource": ""
} |
q32702 | AccountState.BalanceFor | train | def BalanceFor(self, assetId):
"""
Get the balance for a given asset id.
Args:
assetId (UInt256):
Returns:
Fixed8: balance value.
"""
for key, fixed8 in self.Balances.items():
if key == assetId:
return fixed8
return Fixed8(0) | python | {
"resource": ""
} |
q32703 | AccountState.AddToBalance | train | def AddToBalance(self, assetId, fixed8_val):
"""
Add amount to the specified balance.
Args:
assetId (UInt256):
fixed8_val (Fixed8): amount to add.
"""
found = False
for key, balance in self.Balances.items():
if key == assetId:
self.Balances[assetId] = self.Balances[assetId] + fixed8_val
found = True
if not found:
self.Balances[assetId] = fixed8_val | python | {
"resource": ""
} |
q32704 | AccountState.SubtractFromBalance | train | def SubtractFromBalance(self, assetId, fixed8_val):
"""
Subtract amount to the specified balance.
Args:
assetId (UInt256):
fixed8_val (Fixed8): amount to add.
"""
found = False
for key, balance in self.Balances.items():
if key == assetId:
self.Balances[assetId] = self.Balances[assetId] - fixed8_val
found = True
if not found:
self.Balances[assetId] = fixed8_val * Fixed8(-1) | python | {
"resource": ""
} |
q32705 | AccountState.AllBalancesZeroOrLess | train | def AllBalancesZeroOrLess(self):
"""
Flag indicating if all balances are 0 or less.
Returns:
bool: True if all balances are <= 0. False, otherwise.
"""
for key, fixed8 in self.Balances.items():
if fixed8.value > 0:
return False
return True | python | {
"resource": ""
} |
q32706 | AccountState.ToByteArray | train | def ToByteArray(self):
"""
Serialize self and get the byte stream.
Returns:
bytes: serialized object.
"""
ms = StreamManager.GetStream()
writer = BinaryWriter(ms)
self.Serialize(writer)
retval = ms.ToArray()
StreamManager.ReleaseStream(ms)
return retval | python | {
"resource": ""
} |
q32707 | NotificationDB.start | train | def start(self):
"""
Handle EventHub events for SmartContract decorators
"""
self._events_to_write = []
self._new_contracts_to_write = []
@events.on(SmartContractEvent.CONTRACT_CREATED)
@events.on(SmartContractEvent.CONTRACT_MIGRATED)
def call_on_success_event(sc_event: SmartContractEvent):
self.on_smart_contract_created(sc_event)
@events.on(SmartContractEvent.RUNTIME_NOTIFY)
def call_on_event(sc_event: NotifyEvent):
self.on_smart_contract_event(sc_event)
Blockchain.Default().PersistCompleted.on_change += self.on_persist_completed | python | {
"resource": ""
} |
q32708 | Header.FromTrimmedData | train | def FromTrimmedData(data, index):
"""
Deserialize into a Header object from the provided data.
Args:
data (bytes):
index: UNUSED
Returns:
Header:
"""
header = Header()
ms = StreamManager.GetStream(data)
reader = BinaryReader(ms)
header.DeserializeUnsigned(reader)
reader.ReadByte()
witness = Witness()
witness.Deserialize(reader)
header.Script = witness
StreamManager.ReleaseStream(ms)
return header | python | {
"resource": ""
} |
q32709 | ContractParameterType.FromString | train | def FromString(val):
"""
Create a ContractParameterType object from a str
Args:
val (str): the value to be converted to a ContractParameterType.
val can be hex encoded (b'07'), int (7), string int ("7"), or string literal ("String")
Returns:
ContractParameterType
"""
# first, check if the value supplied is the string literal of the enum (e.g. "String")
if isinstance(val, bytes):
val = val.decode('utf-8')
try:
return ContractParameterType[val]
except Exception as e:
# ignore a KeyError if the val isn't found in the Enum
pass
# second, check if the value supplied is bytes or hex-encoded (e.g. b'07')
try:
if isinstance(val, (bytearray, bytes)):
int_val = int.from_bytes(val, 'little')
else:
int_val = int.from_bytes(binascii.unhexlify(val), 'little')
except (binascii.Error, TypeError) as e:
# if it's not hex-encoded, then convert as int (e.g. "7" or 7)
int_val = int(val)
return ContractParameterType(int_val) | python | {
"resource": ""
} |
q32710 | address_to_scripthash | train | def address_to_scripthash(address: str) -> UInt160:
"""Just a helper method"""
AddressVersion = 23 # fixed at this point
data = b58decode(address)
if len(data) != 25:
raise ValueError('Not correct Address, wrong length.')
if data[0] != AddressVersion:
raise ValueError('Not correct Coin Version')
checksum_data = data[:21]
checksum = hashlib.sha256(hashlib.sha256(checksum_data).digest()).digest()[:4]
if checksum != data[21:]:
raise Exception('Address format error')
return UInt160(data=data[1:21]) | python | {
"resource": ""
} |
q32711 | FunctionCode.HasStorage | train | def HasStorage(self):
"""
Flag indicating if storage is available.
Returns:
bool: True if available. False otherwise.
"""
from neo.Core.State.ContractState import ContractPropertyState
return self.ContractProperties & ContractPropertyState.HasStorage > 0 | python | {
"resource": ""
} |
q32712 | FunctionCode.HasDynamicInvoke | train | def HasDynamicInvoke(self):
"""
Flag indicating if dynamic invocation is supported.
Returns:
bool: True if supported. False otherwise.
"""
from neo.Core.State.ContractState import ContractPropertyState
return self.ContractProperties & ContractPropertyState.HasDynamicInvoke > 0 | python | {
"resource": ""
} |
q32713 | FunctionCode.IsPayable | train | def IsPayable(self):
"""
Flag indicating if the contract accepts payments.
Returns:
bool: True if supported. False otherwise.
"""
from neo.Core.State.ContractState import ContractPropertyState
return self.ContractProperties & ContractPropertyState.Payable > 0 | python | {
"resource": ""
} |
q32714 | FunctionCode.ScriptHash | train | def ScriptHash(self):
"""
Get the script hash.
Returns:
UInt160:
"""
if self._scriptHash is None:
self._scriptHash = Crypto.ToScriptHash(self.Script, unhex=False)
return self._scriptHash | python | {
"resource": ""
} |
q32715 | SettingsHolder.setup | train | def setup(self, config_file):
""" Setup settings from a JSON config file """
def get_config_and_warn(key, default, abort=False):
value = config.get(key, None)
if not value:
print(f"Cannot find {key} in settings, using default value: {default}")
value = default
if abort:
sys.exit(-1)
return value
if not self.DATA_DIR_PATH:
# Setup default data dir
self.set_data_dir(None)
with open(config_file) as data_file:
data = json.load(data_file)
config = data['ProtocolConfiguration']
self.MAGIC = config['Magic']
self.ADDRESS_VERSION = config['AddressVersion']
self.STANDBY_VALIDATORS = config['StandbyValidators']
self.SEED_LIST = config['SeedList']
self.RPC_LIST = config['RPCList']
fees = config['SystemFee']
self.ALL_FEES = fees
self.ENROLLMENT_TX_FEE = fees['EnrollmentTransaction']
self.ISSUE_TX_FEE = fees['IssueTransaction']
self.PUBLISH_TX_FEE = fees['PublishTransaction']
self.REGISTER_TX_FEE = fees['RegisterTransaction']
config = data['ApplicationConfiguration']
self.LEVELDB_PATH = config['DataDirectoryPath']
self.RPC_PORT = int(config['RPCPort'])
self.NODE_PORT = int(config['NodePort'])
self.WS_PORT = config['WsPort']
self.URI_PREFIX = config['UriPrefix']
self.ACCEPT_INCOMING_PEERS = config.get('AcceptIncomingPeers', False)
self.BOOTSTRAP_NAME = get_config_and_warn('BootstrapName', "mainnet")
self.BOOTSTRAP_LOCATIONS = get_config_and_warn('BootstrapFiles', "abort", abort=True)
Helper.ADDRESS_VERSION = self.ADDRESS_VERSION
self.USE_DEBUG_STORAGE = config.get('DebugStorage', False)
self.DEBUG_STORAGE_PATH = config.get('DebugStoragePath', 'Chains/debugstorage')
self.NOTIFICATION_DB_PATH = config.get('NotificationDataPath', 'Chains/notification_data')
self.SERVICE_ENABLED = config.get('ServiceEnabled', self.ACCEPT_INCOMING_PEERS)
self.COMPILER_NEP_8 = config.get('CompilerNep8', False)
self.REST_SERVER = config.get('RestServer', self.DEFAULT_REST_SERVER)
self.RPC_SERVER = config.get('RPCServer', self.DEFAULT_RPC_SERVER) | python | {
"resource": ""
} |
q32716 | SettingsHolder.setup_privnet | train | def setup_privnet(self, host=None):
"""
Load settings from the privnet JSON config file
Args:
host (string, optional): if supplied, uses this IP or domain as neo nodes. The host must
use these standard ports: P2P 20333, RPC 30333.
"""
self.setup(FILENAME_SETTINGS_PRIVNET)
if isinstance(host, str):
if ":" in host:
raise Exception("No protocol prefix or port allowed in host, use just the IP or domain.")
print("Using custom privatenet host:", host)
self.SEED_LIST = ["%s:20333" % host]
self.RPC_LIST = ["http://%s:30333" % host]
print("- P2P:", ", ".join(self.SEED_LIST))
print("- RPC:", ", ".join(self.RPC_LIST))
self.check_privatenet() | python | {
"resource": ""
} |
q32717 | SettingsHolder.set_loglevel | train | def set_loglevel(self, level):
"""
Set the minimum loglevel for all components
Args:
level (int): eg. logging.DEBUG or logging.ERROR. See also https://docs.python.org/2/library/logging.html#logging-levels
"""
self.log_level = level
log_manager.config_stdio(default_level=level) | python | {
"resource": ""
} |
q32718 | SettingsHolder.check_chain_dir_exists | train | def check_chain_dir_exists(self, warn_migration=False):
"""
Checks to make sure there is a directory called ``Chains`` at the root of DATA_DIR_PATH
and creates it if it doesn't exist yet
"""
chain_path = os.path.join(self.DATA_DIR_PATH, 'Chains')
if not os.path.exists(chain_path):
try:
os.makedirs(chain_path)
logger.info("Created 'Chains' directory at %s " % chain_path)
except Exception as e:
logger.error("Could not create 'Chains' directory at %s %s" % (chain_path, e))
warn_migration = False
# Add a warning for migration purposes if we created a chain dir
if warn_migration and ROOT_INSTALL_PATH != self.DATA_DIR_PATH:
if os.path.exists(os.path.join(ROOT_INSTALL_PATH, 'Chains')):
logger.warning("[MIGRATION] You are now using the blockchain data at %s, but it appears you have existing data at %s/Chains" % (
chain_path, ROOT_INSTALL_PATH))
logger.warning(
"[MIGRATION] If you would like to use your existing data, please move any data at %s/Chains to %s " % (ROOT_INSTALL_PATH, chain_path))
logger.warning("[MIGRATION] Or you can continue using your existing data by starting your script with the `--datadir=.` flag") | python | {
"resource": ""
} |
q32719 | SplitUnspentCoin | train | def SplitUnspentCoin(wallet, asset_id, from_addr, index, divisions, fee=Fixed8.Zero(), prompt_passwd=True):
"""
Split unspent asset vins into several vouts
Args:
wallet (neo.Wallet): wallet to show unspent coins from.
asset_id (UInt256): a bytearray (len 32) representing an asset on the blockchain.
from_addr (UInt160): a bytearray (len 20) representing an address.
index (int): index of the unspent vin to split
divisions (int): number of vouts to create
fee (Fixed8): A fee to be attached to the Transaction for network processing purposes.
prompt_passwd (bool): prompt password before processing the transaction
Returns:
neo.Core.TX.Transaction.ContractTransaction: contract transaction created
"""
if wallet is None:
print("Please open a wallet.")
return
unspent_items = wallet.FindUnspentCoinsByAsset(asset_id, from_addr=from_addr)
if not unspent_items:
print(f"No unspent assets matching the arguments.")
return
if index < len(unspent_items):
unspent_item = unspent_items[index]
else:
print(f"unspent-items: {unspent_items}")
print(f"Could not find unspent item for asset {asset_id} with index {index}")
return
outputs = split_to_vouts(asset_id, from_addr, unspent_item.Output.Value, divisions)
# subtract a fee from the first vout
if outputs[0].Value > fee:
outputs[0].Value -= fee
else:
print("Fee could not be subtracted from outputs.")
return
contract_tx = ContractTransaction(outputs=outputs, inputs=[unspent_item.Reference])
ctx = ContractParametersContext(contract_tx)
wallet.Sign(ctx)
print("Splitting: %s " % json.dumps(contract_tx.ToJson(), indent=4))
if prompt_passwd:
passwd = prompt("[Password]> ", is_password=True)
if not wallet.ValidatePassword(passwd):
print("incorrect password")
return
if ctx.Completed:
contract_tx.scripts = ctx.GetScripts()
relayed = NodeLeader.Instance().Relay(contract_tx)
if relayed:
wallet.SaveTransaction(contract_tx)
print("Relayed Tx: %s " % contract_tx.Hash.ToString())
return contract_tx
else:
print("Could not relay tx %s " % contract_tx.Hash.ToString()) | python | {
"resource": ""
} |
q32720 | load_class_from_path | train | def load_class_from_path(path_and_class: str):
"""
Dynamically load a class from a module at the specified path
Args:
path_and_class: relative path where to find the module and its class name
i.e. 'neo.<package>.<package>.<module>.<class name>'
Raises:
ValueError: if the Module or Class is not found.
Returns:
class object
"""
try:
module_path = '.'.join(path_and_class.split('.')[:-1])
module = importlib.import_module(module_path)
except ImportError as err:
raise ValueError(f"Failed to import module {module_path} with error: {err}")
try:
class_name = path_and_class.split('.')[-1]
class_obj = getattr(module, class_name)
return class_obj
except AttributeError as err:
raise ValueError(f"Failed to get class {class_name} with error: {err}") | python | {
"resource": ""
} |
q32721 | ApplicationEngine.Run | train | def Run(script, container=None, exit_on_error=False, gas=Fixed8.Zero(), test_mode=True):
"""
Runs a script in a test invoke environment
Args:
script (bytes): The script to run
container (neo.Core.TX.Transaction): [optional] the transaction to use as the script container
Returns:
ApplicationEngine
"""
from neo.Core.Blockchain import Blockchain
from neo.SmartContract.StateMachine import StateMachine
from neo.EventHub import events
bc = Blockchain.Default()
accounts = DBCollection(bc._db, DBPrefix.ST_Account, AccountState)
assets = DBCollection(bc._db, DBPrefix.ST_Asset, AssetState)
validators = DBCollection(bc._db, DBPrefix.ST_Validator, ValidatorState)
contracts = DBCollection(bc._db, DBPrefix.ST_Contract, ContractState)
storages = DBCollection(bc._db, DBPrefix.ST_Storage, StorageItem)
script_table = CachedScriptTable(contracts)
service = StateMachine(accounts, validators, assets, contracts, storages, None)
engine = ApplicationEngine(
trigger_type=TriggerType.Application,
container=container,
table=script_table,
service=service,
gas=gas,
testMode=test_mode,
exit_on_error=exit_on_error
)
script = binascii.unhexlify(script)
engine.LoadScript(script)
try:
success = engine.Execute()
engine.testMode = True
service.ExecutionCompleted(engine, success)
except Exception as e:
engine.testMode = True
service.ExecutionCompleted(engine, False, e)
for event in service.events_to_dispatch:
events.emit(event.event_type, event)
return engine | python | {
"resource": ""
} |
q32722 | ConcatenatedEnumerator.Next | train | def Next(self):
"""
Advances the iterator forward 1 step.
Returns:
bool: True if another item exists in the iterator, False otherwise.
"""
try:
self.key, self.value = next(self.current)
except StopIteration:
if self.current != self.second:
self.current = self.second
return self.Next()
return False
return True | python | {
"resource": ""
} |
q32723 | AssetType.AllTypes | train | def AllTypes():
"""
Get a list of all available asset types.
Returns:
list: of AssetType items.
"""
return [AssetType.CreditFlag, AssetType.DutyFlag, AssetType.GoverningToken,
AssetType.UtilityToken, AssetType.Currency, AssetType.Share,
AssetType.Invoice, AssetType.Token] | python | {
"resource": ""
} |
q32724 | custom_background_code | train | def custom_background_code():
""" Custom code run in a background thread. Prints the current block height.
This function is run in a daemonized thread, which means it can be instantly killed at any
moment, whenever the main thread quits. If you need more safety, don't use a daemonized
thread and handle exiting this thread in another way (eg. with signals and events).
"""
while True:
logger.info("Block %s / %s", str(Blockchain.Default().Height), str(Blockchain.Default().HeaderHeight))
sleep(15) | python | {
"resource": ""
} |
q32725 | wait_for_tx | train | def wait_for_tx(self, tx, max_seconds=120):
""" Wait for tx to show up on blockchain
Args:
tx (Transaction or UInt256 or str): Transaction or just the hash
max_seconds (float): maximum seconds to wait for tx to show up. default: 120
Returns:
True: if transaction was found
Raises:
AttributeError: if supplied tx is not Transaction or UInt256 or str
TxNotFoundInBlockchainError: if tx is not found in blockchain after max_seconds
"""
tx_hash = None
if isinstance(tx, (str, UInt256)):
tx_hash = str(tx)
elif isinstance(tx, Transaction):
tx_hash = tx.Hash.ToString()
else:
raise AttributeError("Supplied tx is type '%s', but must be Transaction or UInt256 or str" % type(tx))
wait_event = Event()
time_start = time.time()
while True:
# Try to find transaction in blockchain
_tx, height = Blockchain.Default().GetTransaction(tx_hash)
if height > -1:
return True
# Using a wait event for the delay because it is not blocking like time.sleep()
wait_event.wait(3)
seconds_passed = time.time() - time_start
if seconds_passed > max_seconds:
raise TxNotFoundInBlockchainError("Transaction with hash %s not found after %s seconds" % (tx_hash, int(seconds_passed))) | python | {
"resource": ""
} |
q32726 | Wallet.AddContract | train | def AddContract(self, contract):
"""
Add a contract to the wallet.
Args:
contract (Contract): a contract of type neo.SmartContract.Contract.
Raises:
Exception: Invalid operation - public key mismatch.
"""
if not contract.PublicKeyHash.ToBytes() in self._keys.keys():
raise Exception('Invalid operation - public key mismatch')
self._contracts[contract.ScriptHash.ToBytes()] = contract
if contract.ScriptHash in self._watch_only:
self._watch_only.remove(contract.ScriptHash) | python | {
"resource": ""
} |
q32727 | Wallet.AddWatchOnly | train | def AddWatchOnly(self, script_hash):
"""
Add a watch only address to the wallet.
Args:
script_hash (UInt160): a bytearray (len 20) representing the public key.
Note:
Prints a warning to the console if the address already exists in the wallet.
"""
if script_hash in self._contracts:
logger.error("Address already in contracts")
return
self._watch_only.append(script_hash) | python | {
"resource": ""
} |
q32728 | Wallet.AddNEP5Token | train | def AddNEP5Token(self, token):
"""
Add a NEP-5 compliant token to the wallet.
Args:
token (NEP5Token): an instance of type neo.Wallets.NEP5Token.
Note:
Prints a warning to the console if the token already exists in the wallet.
"""
if token.ScriptHash.ToBytes() in self._tokens.keys():
logger.error("Token already in wallet")
return
self._tokens[token.ScriptHash.ToBytes()] = token | python | {
"resource": ""
} |
q32729 | Wallet.ChangePassword | train | def ChangePassword(self, password_old, password_new):
"""
Change the password used to protect the private key.
Args:
password_old (str): the current password used to encrypt the private key.
password_new (str): the new to be used password to encrypt the private key.
Returns:
bool: whether the password has been changed
"""
if not self.ValidatePassword(password_old):
return False
if isinstance(password_new, str):
password_new = password_new.encode('utf-8')
password_key = hashlib.sha256(password_new)
self.SaveStoredData("PasswordHash", password_key)
self.SaveStoredData("MasterKey", AES.new(self._master_key, AES.MODE_CBC, self._iv))
return True | python | {
"resource": ""
} |
q32730 | Wallet.ContainsKey | train | 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. e.g. KeyPair.PublicKey
Returns:
bool: True if exists, False otherwise.
"""
return self.ContainsKeyHash(Crypto.ToScriptHash(public_key.encode_point(True), unhex=True)) | python | {
"resource": ""
} |
q32731 | Wallet.ContainsAddressStr | train | def ContainsAddressStr(self, address):
"""
Determine if the wallet contains the address.
Args:
address (str): a string representing the public key.
Returns:
bool: True, if the address is present in the wallet. False otherwise.
"""
for key, contract in self._contracts.items():
if contract.Address == address:
return True
return False | python | {
"resource": ""
} |
q32732 | Wallet.CreateKey | train | def CreateKey(self, private_key=None):
"""
Create a KeyPair
Args:
private_key (iterable_of_ints): (optional) 32 byte private key
Returns:
KeyPair: a KeyPair instance
"""
if private_key is None:
private_key = bytes(Random.get_random_bytes(32))
key = KeyPair(priv_key=private_key)
self._keys[key.PublicKeyHash.ToBytes()] = key
return key | python | {
"resource": ""
} |
q32733 | Wallet.EncryptPrivateKey | train | def EncryptPrivateKey(self, decrypted):
"""
Encrypt the provided plaintext with the initialized private key.
Args:
decrypted (byte string): the plaintext to be encrypted.
Returns:
bytes: the ciphertext.
"""
aes = AES.new(self._master_key, AES.MODE_CBC, self._iv)
return aes.encrypt(decrypted) | python | {
"resource": ""
} |
q32734 | Wallet.DecryptPrivateKey | train | def DecryptPrivateKey(self, encrypted_private_key):
"""
Decrypt the provided ciphertext with the initialized private key.
Args:
encrypted_private_key (byte string): the ciphertext to be decrypted.
Returns:
bytes: the ciphertext.
"""
aes = AES.new(self._master_key, AES.MODE_CBC, self._iv)
return aes.decrypt(encrypted_private_key) | python | {
"resource": ""
} |
q32735 | Wallet.FindCoinsByVins | train | def FindCoinsByVins(self, vins):
"""
Looks through the current collection of coins in a wallet
and chooses coins that match the specified CoinReference objects.
Args:
vins: A list of ``neo.Core.CoinReference`` objects.
Returns:
list: A list of ``neo.Wallet.Coin`` objects.
"""
ret = []
for coin in self.GetCoins():
coinref = coin.Reference
for vin in vins:
if coinref.PrevIndex == vin.PrevIndex and \
coinref.PrevHash == vin.PrevHash:
ret.append(coin)
return ret | python | {
"resource": ""
} |
q32736 | Wallet.FindUnspentCoins | train | def FindUnspentCoins(self, from_addr=None, use_standard=False, watch_only_val=0):
"""
Finds unspent coin objects in the wallet.
Args:
from_addr (UInt160): a bytearray (len 20) representing an address.
use_standard (bool): whether or not to only include standard contracts ( i.e not a smart contract addr ).
watch_only_val (int): a flag ( 0 or 64 ) indicating whether or not to find coins that are in 'watch only' addresses.
Returns:
list: a list of ``neo.Wallet.Coins`` in the wallet that are not spent.
"""
ret = []
for coin in self.GetCoins():
if coin.State & CoinState.Confirmed > 0 and \
coin.State & CoinState.Spent == 0 and \
coin.State & CoinState.Locked == 0 and \
coin.State & CoinState.Frozen == 0 and \
coin.State & CoinState.WatchOnly == watch_only_val:
do_exclude = False
if self._vin_exclude:
for to_exclude in self._vin_exclude:
if coin.Reference.PrevIndex == to_exclude.PrevIndex and \
coin.Reference.PrevHash == to_exclude.PrevHash:
do_exclude = True
if do_exclude:
continue
if from_addr is not None:
if coin.Output.ScriptHash == from_addr:
ret.append(coin)
elif use_standard:
contract = self._contracts[coin.Output.ScriptHash.ToBytes()]
if contract.IsStandard:
ret.append(coin)
else:
ret.append(coin)
return ret | python | {
"resource": ""
} |
q32737 | Wallet.FindUnspentCoinsByAsset | train | def FindUnspentCoinsByAsset(self, asset_id, from_addr=None, use_standard=False, watch_only_val=0):
"""
Finds unspent coin objects in the wallet limited to those of a certain asset type.
Args:
asset_id (UInt256): a bytearray (len 32) representing an asset on the blockchain.
from_addr (UInt160): a bytearray (len 20) representing an address.
use_standard (bool): whether or not to only include standard contracts ( i.e not a smart contract addr ).
watch_only_val (int): a flag ( 0 or 64 ) indicating whether or not to find coins that are in 'watch only' addresses.
Returns:
list: a list of ``neo.Wallet.Coin`` in the wallet that are not spent
"""
coins = self.FindUnspentCoins(from_addr=from_addr, use_standard=use_standard, watch_only_val=watch_only_val)
return [coin for coin in coins if coin.Output.AssetId == asset_id] | python | {
"resource": ""
} |
q32738 | Wallet.FindUnspentCoinsByAssetAndTotal | train | def FindUnspentCoinsByAssetAndTotal(self, asset_id, amount, from_addr=None, use_standard=False, watch_only_val=0, reverse=False):
"""
Finds unspent coin objects totalling a requested value in the wallet limited to those of a certain asset type.
Args:
asset_id (UInt256): a bytearray (len 32) representing an asset on the blockchain.
amount (int): the amount of unspent coins that are being requested.
from_addr (UInt160): a bytearray (len 20) representing an address.
use_standard (bool): whether or not to only include standard contracts ( i.e not a smart contract addr ).
watch_only_val (int): a flag ( 0 or 64 ) indicating whether or not to find coins that are in 'watch only' addresses.
Returns:
list: a list of ``neo.Wallet.Coin`` in the wallet that are not spent. this list is empty if there are not enough coins to satisfy the request.
"""
coins = self.FindUnspentCoinsByAsset(asset_id, from_addr=from_addr,
use_standard=use_standard, watch_only_val=watch_only_val)
sum = Fixed8(0)
for coin in coins:
sum = sum + coin.Output.Value
if sum < amount:
return None
coins = sorted(coins, key=lambda coin: coin.Output.Value.value)
if reverse:
coins.reverse()
total = Fixed8(0)
# go through all coins, see if one is an exact match. then we'll use that
for coin in coins:
if coin.Output.Value == amount:
return [coin]
to_ret = []
for coin in coins:
total = total + coin.Output.Value
to_ret.append(coin)
if total >= amount:
break
return to_ret | python | {
"resource": ""
} |
q32739 | Wallet.GetUnclaimedCoins | train | def GetUnclaimedCoins(self):
"""
Gets coins in the wallet that have not been 'claimed', or redeemed for their gas value on the blockchain.
Returns:
list: a list of ``neo.Wallet.Coin`` that have 'claimable' value
"""
unclaimed = []
neo = Blockchain.SystemShare().Hash
for coin in self.GetCoins():
if coin.Output.AssetId == neo and \
coin.State & CoinState.Confirmed > 0 and \
coin.State & CoinState.Spent > 0 and \
coin.State & CoinState.Claimed == 0 and \
coin.State & CoinState.Frozen == 0 and \
coin.State & CoinState.WatchOnly == 0:
unclaimed.append(coin)
return unclaimed | python | {
"resource": ""
} |
q32740 | Wallet.GetAvailableClaimTotal | train | def GetAvailableClaimTotal(self):
"""
Gets the total amount of Gas that this wallet is able to claim at a given moment.
Returns:
Fixed8: the amount of Gas available to claim as a Fixed8 number.
"""
coinrefs = [coin.Reference for coin in self.GetUnclaimedCoins()]
bonus = Blockchain.CalculateBonusIgnoreClaimed(coinrefs, True)
return bonus | python | {
"resource": ""
} |
q32741 | Wallet.GetUnavailableBonus | train | def GetUnavailableBonus(self):
"""
Gets the total claimable amount of Gas in the wallet that is not available to claim
because it has not yet been spent.
Returns:
Fixed8: the amount of Gas unavailable to claim.
"""
height = Blockchain.Default().Height + 1
unspents = self.FindUnspentCoinsByAsset(Blockchain.SystemShare().Hash)
refs = [coin.Reference for coin in unspents]
try:
unavailable_bonus = Blockchain.CalculateBonus(refs, height_end=height)
return unavailable_bonus
except Exception as e:
pass
return Fixed8(0) | python | {
"resource": ""
} |
q32742 | Wallet.GetKey | train | def GetKey(self, public_key_hash):
"""
Get the KeyPair belonging to the public key hash.
Args:
public_key_hash (UInt160): a public key hash to get the KeyPair for.
Returns:
KeyPair: If successful, the KeyPair belonging to the public key hash, otherwise None
"""
if public_key_hash.ToBytes() in self._keys.keys():
return self._keys[public_key_hash.ToBytes()]
return None | python | {
"resource": ""
} |
q32743 | Wallet.GetKeyByScriptHash | train | def GetKeyByScriptHash(self, script_hash):
"""
Get the KeyPair belonging to the script hash.
Args:
script_hash (UInt160): a bytearray (len 20) representing the public key.
Returns:
KeyPair: If successful, the KeyPair belonging to the public key hash, otherwise None
"""
contract = self.GetContract(script_hash)
if contract:
return self.GetKey(contract.PublicKeyHash)
return None | python | {
"resource": ""
} |
q32744 | Wallet.GetTokenBalance | train | def GetTokenBalance(self, token, watch_only=0):
"""
Get the balance of the specified token.
Args:
token (NEP5Token): an instance of type neo.Wallets.NEP5Token to get the balance from.
watch_only (bool): True, to limit to watch only wallets.
Returns:
Decimal: total balance for `token`.
"""
total = Decimal(0)
if watch_only > 0:
for addr in self._watch_only:
balance = token.GetBalance(self, addr)
total += balance
else:
for contract in self._contracts.values():
balance = token.GetBalance(self, contract.Address)
total += balance
return total | python | {
"resource": ""
} |
q32745 | Wallet.GetBalance | train | def GetBalance(self, asset_id, watch_only=0):
"""
Get the balance of a specific token by its asset id.
Args:
asset_id (NEP5Token|TransactionOutput): an instance of type neo.Wallets.NEP5Token or neo.Core.TX.Transaction.TransactionOutput to get the balance from.
watch_only (bool): True, to limit to watch only wallets.
Returns:
Fixed8: total balance.
"""
total = Fixed8(0)
if type(asset_id) is NEP5Token.NEP5Token:
return self.GetTokenBalance(asset_id, watch_only)
for coin in self.GetCoins():
if coin.Output.AssetId == asset_id:
if coin.State & CoinState.Confirmed > 0 and \
coin.State & CoinState.Spent == 0 and \
coin.State & CoinState.Locked == 0 and \
coin.State & CoinState.Frozen == 0 and \
coin.State & CoinState.WatchOnly == watch_only:
total = total + coin.Output.Value
return total | python | {
"resource": ""
} |
q32746 | Wallet.ProcessBlocks | train | def ProcessBlocks(self, block_limit=1000):
"""
Method called on a loop to check the current height of the blockchain. If the height of the blockchain
is more than the current stored height in the wallet, we get the next block in line and
processes it.
In the case that the wallet height is far behind the height of the blockchain, we do this 1000
blocks at a time.
Args:
block_limit (int): the number of blocks to process synchronously. defaults to 1000. set to 0 to block until the wallet is fully rebuilt.
"""
self._lock.acquire()
try:
blockcount = 0
while self._current_height <= Blockchain.Default().Height and (block_limit == 0 or blockcount < block_limit):
block = Blockchain.Default().GetBlockByHeight(self._current_height)
if block is not None:
self.ProcessNewBlock(block)
else:
self._current_height += 1
blockcount += 1
self.SaveStoredData("Height", self._current_height)
except Exception as e:
logger.warn("Could not process ::: %s " % e)
finally:
self._lock.release() | python | {
"resource": ""
} |
q32747 | Wallet.ProcessNewBlock | train | def ProcessNewBlock(self, block):
"""
Processes a block on the blockchain. This should be done in a sequential order, ie block 4 should be
only processed after block 3.
Args:
block: (neo.Core.Block) a block on the blockchain.
"""
added = set()
changed = set()
deleted = set()
try:
# go through the list of transactions in the block and enumerate
# over their outputs
for tx in block.FullTransactions:
for index, output in enumerate(tx.outputs):
# check to see if the outputs in the tx are in this wallet
state = self.CheckAddressState(output.ScriptHash)
if state & AddressState.InWallet > 0:
# if it's in the wallet, check to see if the coin exists yet
key = CoinReference(tx.Hash, index)
# if it exists, update it, otherwise create a new one
if key in self._coins.keys():
coin = self._coins[key]
coin.State |= CoinState.Confirmed
changed.add(coin)
else:
newcoin = Coin.CoinFromRef(coin_ref=key, tx_output=output, state=CoinState.Confirmed, transaction=tx)
self._coins[key] = newcoin
added.add(newcoin)
if state & AddressState.WatchOnly > 0:
self._coins[key].State |= CoinState.WatchOnly
changed.add(self._coins[key])
# now iterate over the inputs of the tx and do the same
for tx in block.FullTransactions:
for input in tx.inputs:
if input in self._coins.keys():
if self._coins[input].Output.AssetId == Blockchain.SystemShare().Hash:
coin = self._coins[input]
coin.State |= CoinState.Spent | CoinState.Confirmed
changed.add(coin)
else:
deleted.add(self._coins[input])
del self._coins[input]
for claimTx in [tx for tx in block.Transactions if tx.Type == TransactionType.ClaimTransaction]:
for ref in claimTx.Claims:
if ref in self._coins.keys():
deleted.add(self._coins[ref])
del self._coins[ref]
# update the current height of the wallet
self._current_height += 1
# in the case that another wallet implementation needs to do something
# with the coins that have been changed ( ie persist to db ) this
# method is called
self.OnProcessNewBlock(block, added, changed, deleted)
# this is not necessary at the moment, but any outside process
# that wants to subscribe to the balance changed event could do
# so from the BalanceChanged method
if len(added) + len(deleted) + len(changed) > 0:
self.BalanceChanged()
except Exception as e:
traceback.print_stack()
traceback.print_exc()
logger.error("could not process %s " % e) | python | {
"resource": ""
} |
q32748 | Wallet.IsWalletTransaction | train | def IsWalletTransaction(self, tx):
"""
Verifies if a transaction belongs to the wallet.
Args:
tx (TransactionOutput):an instance of type neo.Core.TX.Transaction.TransactionOutput to verify.
Returns:
bool: True, if transaction belongs to wallet. False, if not.
"""
for key, contract in self._contracts.items():
for output in tx.outputs:
if output.ScriptHash.ToBytes() == contract.ScriptHash.ToBytes():
return True
for script in tx.scripts:
if script.VerificationScript:
if bytes(contract.Script) == script.VerificationScript:
return True
for watch_script_hash in self._watch_only:
for output in tx.outputs:
if output.ScriptHash == watch_script_hash:
return True
for script in tx.scripts:
if Crypto.ToScriptHash(script.VerificationScript, unhex=False) == watch_script_hash:
return True
return False | python | {
"resource": ""
} |
q32749 | Wallet.CheckAddressState | train | def CheckAddressState(self, script_hash):
"""
Determine the address state of the provided script hash.
Args:
script_hash (UInt160): a script hash to determine the address state of.
Returns:
AddressState: the address state.
"""
for key, contract in self._contracts.items():
if contract.ScriptHash.ToBytes() == script_hash.ToBytes():
return AddressState.InWallet
for watch in self._watch_only:
if watch == script_hash:
return AddressState.InWallet | AddressState.WatchOnly
return AddressState.NoState | python | {
"resource": ""
} |
q32750 | Wallet.ToScriptHash | train | def ToScriptHash(self, address):
"""
Retrieve the script_hash based from an address.
Args:
address (str): a base58 encoded address.
Raises:
ValuesError: if an invalid address is supplied or the coin version is incorrect
Exception: if the address string does not start with 'A' or the checksum fails
Returns:
UInt160: script hash.
"""
if len(address) == 34:
if address[0] == 'A':
data = b58decode(address)
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])
else:
raise Exception('Address format error')
else:
raise ValueError('Not correct Address, wrong length.') | python | {
"resource": ""
} |
q32751 | Wallet.ValidatePassword | train | def ValidatePassword(self, password):
"""
Validates if the provided password matches with the stored password.
Args:
password (string): a password.
Returns:
bool: the provided password matches with the stored password.
"""
password = to_aes_key(password)
return hashlib.sha256(password).digest() == self.LoadStoredData('PasswordHash') | python | {
"resource": ""
} |
q32752 | Wallet.GetStandardAddress | train | def GetStandardAddress(self):
"""
Get the Wallet's default address.
Raises:
Exception: if no default contract address is set.
Returns:
UInt160: script hash.
"""
for contract in self._contracts.values():
if contract.IsStandard:
return contract.ScriptHash
raise Exception("Could not find a standard contract address") | python | {
"resource": ""
} |
q32753 | Wallet.GetChangeAddress | train | def GetChangeAddress(self, from_addr=None):
"""
Get the address where change is send to.
Args:
from_address (UInt160): (optional) from address script hash.
Raises:
Exception: if change address could not be found.
Returns:
UInt160: script hash.
"""
if from_addr is not None:
for contract in self._contracts.values():
if contract.ScriptHash == from_addr:
return contract.ScriptHash
for contract in self._contracts.values():
if contract.IsStandard:
return contract.ScriptHash
if len(self._contracts.values()):
for k, v in self._contracts.items():
return v
raise Exception("Could not find change address") | python | {
"resource": ""
} |
q32754 | Wallet.GetDefaultContract | train | def GetDefaultContract(self):
"""
Get the default contract.
Returns:
contract (Contract): if Successful, a contract of type neo.SmartContract.Contract, otherwise an Exception.
Raises:
Exception: if no default contract is found.
Note:
Prints a warning to the console if the default contract could not be found.
"""
try:
return self.GetContracts()[0]
except Exception as e:
logger.error("Could not find default contract: %s" % str(e))
raise | python | {
"resource": ""
} |
q32755 | Wallet.GetCoinAssets | train | def GetCoinAssets(self):
"""
Get asset ids of all coins present in the wallet.
Returns:
list: of UInt256 asset id's.
"""
assets = set()
for coin in self.GetCoins():
assets.add(coin.Output.AssetId)
return list(assets) | python | {
"resource": ""
} |
q32756 | Wallet.GetContract | train | def GetContract(self, script_hash):
"""
Get contract for specified script_hash.
Args:
script_hash (UInt160): a bytearray (len 20).
Returns:
Contract: if a contract was found matching the provided script hash, otherwise None
"""
if script_hash.ToBytes() in self._contracts.keys():
return self._contracts[script_hash.ToBytes()]
return None | python | {
"resource": ""
} |
q32757 | Wallet.SaveTransaction | train | def SaveTransaction(self, tx):
"""
This method is used to after a transaction has been made by this wallet. It updates the states of the coins
In the wallet to reflect the new balance, but the coins remain in a ``CoinState.UNCONFIRMED`` state until
The transaction has been processed by the network.
The results of these updates can be used by overriding the ``OnSaveTransaction`` method, and, for example
persisting the results to a database.
Args:
tx (Transaction): The transaction that has been made by this wallet.
Returns:
bool: True is successfully processes, otherwise False if input is not in the coin list, already spent or not confirmed.
"""
coins = self.GetCoins()
changed = []
added = []
deleted = []
found_coin = False
for input in tx.inputs:
coin = None
for coinref in coins:
test_coin = coinref.Reference
if test_coin == input:
coin = coinref
if coin is None:
return False
if coin.State & CoinState.Spent > 0:
return False
elif coin.State & CoinState.Confirmed == 0:
return False
coin.State |= CoinState.Spent
coin.State &= ~CoinState.Confirmed
changed.append(coin)
for index, output in enumerate(tx.outputs):
state = self.CheckAddressState(output.ScriptHash)
key = CoinReference(tx.Hash, index)
if state & AddressState.InWallet > 0:
newcoin = Coin.CoinFromRef(coin_ref=key, tx_output=output, state=CoinState.Unconfirmed)
self._coins[key] = newcoin
if state & AddressState.WatchOnly > 0:
newcoin.State |= CoinState.WatchOnly
added.append(newcoin)
if isinstance(tx, ClaimTransaction):
# do claim stuff
for claim in tx.Claims:
claim_coin = self._coins[claim]
claim_coin.State |= CoinState.Claimed
claim_coin.State &= ~CoinState.Confirmed
changed.append(claim_coin)
self.OnSaveTransaction(tx, added, changed, deleted)
return True | python | {
"resource": ""
} |
q32758 | Wallet.SignMessage | train | def SignMessage(self, message, script_hash):
"""
Sign a message with a specified script_hash.
Args:
message (str): a hex encoded message to sign
script_hash (UInt160): a bytearray (len 20).
Returns:
str: the signed message
"""
keypair = self.GetKeyByScriptHash(script_hash)
prikey = bytes(keypair.PrivateKey)
res = Crypto.Default().Sign(message, prikey)
return res, keypair.PublicKey | python | {
"resource": ""
} |
q32759 | Wallet.IsSynced | train | def IsSynced(self):
"""
Check if wallet is synced.
Returns:
bool: True if wallet is synced.
"""
if Blockchain.Default().Height == 0:
return False
if (int(100 * self._current_height / Blockchain.Default().Height)) < 100:
return False
else:
return True | python | {
"resource": ""
} |
q32760 | UserWallet.Create | train | def Create(path, password, generate_default_key=True):
"""
Create a new user wallet.
Args:
path (str): A path indicating where to create or open the wallet e.g. "/Wallets/mywallet".
password (str): a 10 characters minimum password to secure the wallet with.
Returns:
UserWallet: a UserWallet instance.
"""
wallet = UserWallet(path=path, passwordKey=password, create=True)
if generate_default_key:
wallet.CreateKey()
return wallet | python | {
"resource": ""
} |
q32761 | UserWallet.CreateKey | train | def CreateKey(self, prikey=None):
"""
Create a KeyPair and store it encrypted in the database.
Args:
private_key (iterable_of_ints): (optional) 32 byte private key.
Returns:
KeyPair: a KeyPair instance.
"""
account = super(UserWallet, self).CreateKey(private_key=prikey)
self.OnCreateAccount(account)
contract = WalletContract.CreateSignatureContract(account.PublicKey)
self.AddContract(contract)
return account | python | {
"resource": ""
} |
q32762 | UserWallet.OnCreateAccount | train | def OnCreateAccount(self, account):
"""
Save a KeyPair in encrypted form into the database.
Args:
account (KeyPair):
"""
pubkey = account.PublicKey.encode_point(False)
pubkeyunhex = binascii.unhexlify(pubkey)
pub = pubkeyunhex[1:65]
priv = bytearray(account.PrivateKey)
decrypted = pub + priv
encrypted_pk = self.EncryptPrivateKey(bytes(decrypted))
db_account, created = Account.get_or_create(
PrivateKeyEncrypted=encrypted_pk, PublicKeyHash=account.PublicKeyHash.ToBytes())
db_account.save()
self.__dbaccount = db_account | python | {
"resource": ""
} |
q32763 | UserWallet.AddContract | train | def AddContract(self, contract):
"""
Add a contract to the database.
Args:
contract(neo.SmartContract.Contract): a Contract instance.
"""
super(UserWallet, self).AddContract(contract)
try:
db_contract = Contract.get(ScriptHash=contract.ScriptHash.ToBytes())
db_contract.delete_instance()
except Exception as e:
logger.debug("contract does not exist yet")
sh = bytes(contract.ScriptHash.ToArray())
address, created = Address.get_or_create(ScriptHash=sh)
address.IsWatchOnly = False
address.save()
db_contract = Contract.create(RawData=contract.ToArray(),
ScriptHash=contract.ScriptHash.ToBytes(),
PublicKeyHash=contract.PublicKeyHash.ToBytes(),
Address=address,
Account=self.__dbaccount)
logger.debug("Creating db contract %s " % db_contract)
db_contract.save() | python | {
"resource": ""
} |
q32764 | NeoNode.Disconnect | train | def Disconnect(self, reason=None, isDead=True):
"""Close the connection with the remote node client."""
self.disconnecting = True
self.expect_verack_next = False
if reason:
logger.debug(f"Disconnecting with reason: {reason}")
self.stop_block_loop()
self.stop_header_loop()
self.stop_peerinfo_loop()
if isDead:
self.leader.AddDeadAddress(self.address, reason=f"{self.prefix} Forced disconnect by us")
self.leader.forced_disconnect_by_us += 1
self.disconnect_deferred = defer.Deferred()
self.disconnect_deferred.debug = True
# force disconnection without waiting on the other side
# calling later to give func caller time to add callbacks to the deferred
reactor.callLater(1, self.transport.abortConnection)
return self.disconnect_deferred | python | {
"resource": ""
} |
q32765 | NeoNode.Name | train | def Name(self):
"""
Get the peer name.
Returns:
str:
"""
name = ""
if self.Version:
name = self.Version.UserAgent
return name | python | {
"resource": ""
} |
q32766 | NeoNode.GetNetworkAddressWithTime | train | def GetNetworkAddressWithTime(self):
"""
Get a network address object.
Returns:
NetworkAddressWithTime: if we have a connection to a node.
None: otherwise.
"""
if self.port is not None and self.host is not None and self.Version is not None:
return NetworkAddressWithTime(self.host, self.port, self.Version.Services)
return None | python | {
"resource": ""
} |
q32767 | NeoNode.connectionMade | train | def connectionMade(self):
"""Callback handler from twisted when establishing a new connection."""
self.endpoint = self.transport.getPeer()
# get the reference to the Address object in NodeLeader so we can manipulate it properly.
tmp_addr = Address(f"{self.endpoint.host}:{self.endpoint.port}")
try:
known_idx = self.leader.KNOWN_ADDRS.index(tmp_addr)
self.address = self.leader.KNOWN_ADDRS[known_idx]
except ValueError:
# Not found.
self.leader.AddKnownAddress(tmp_addr)
self.address = tmp_addr
self.address.address = "%s:%s" % (self.endpoint.host, self.endpoint.port)
self.host = self.endpoint.host
self.port = int(self.endpoint.port)
self.leader.AddConnectedPeer(self)
self.leader.RemoveFromQueue(self.address)
self.leader.peers_connecting -= 1
logger.debug(f"{self.address} connection established")
if self.incoming_client:
# start protocol
self.SendVersion() | python | {
"resource": ""
} |
q32768 | NeoNode.connectionLost | train | def connectionLost(self, reason=None):
"""Callback handler from twisted when a connection was lost."""
try:
self.connected = False
self.stop_block_loop()
self.stop_peerinfo_loop()
self.stop_header_loop()
self.ReleaseBlockRequests()
self.leader.RemoveConnectedPeer(self)
time_expired = self.time_expired(HEARTBEAT_BLOCKS)
# some NEO-cli versions have a 30s timeout to receive block/consensus or tx messages. By default neo-python doesn't respond to these requests
if time_expired > 20:
self.address.last_connection = Address.Now()
self.leader.AddDeadAddress(self.address, reason=f"{self.prefix} Premature disconnect")
if reason and reason.check(twisted_error.ConnectionDone):
# this might happen if they close our connection because they've reached max peers or something similar
logger.debug(f"{self.prefix} disconnected normally with reason:{reason.value}")
self._check_for_consecutive_disconnects("connection done")
elif reason and reason.check(twisted_error.ConnectionLost):
# Can be due to a timeout. Only if this happened again within 5 minutes do we label the node as bad
# because then it clearly doesn't want to talk to us or we have a bad connection to them.
# Otherwise allow for the node to be queued again by NodeLeader.
logger.debug(f"{self.prefix} disconnected with connectionlost reason: {reason.value}")
self._check_for_consecutive_disconnects("connection lost")
else:
logger.debug(f"{self.prefix} disconnected with reason: {reason.value}")
except Exception as e:
logger.error("Error with connection lost: %s " % e)
def try_me(err):
err.check(error.ConnectionAborted)
if self.disconnect_deferred:
d, self.disconnect_deferred = self.disconnect_deferred, None # type: defer.Deferred
d.addErrback(try_me)
if len(d.callbacks) > 0:
d.callback(reason)
else:
print("connLost, disconnect_deferred cancelling!")
d.cancel() | python | {
"resource": ""
} |
q32769 | NeoNode.dataReceived | train | def dataReceived(self, data):
""" Called from Twisted whenever data is received. """
self.bytes_in += (len(data))
self.buffer_in = self.buffer_in + data
while self.CheckDataReceived():
pass | python | {
"resource": ""
} |
q32770 | NeoNode.CheckDataReceived | train | def CheckDataReceived(self):
"""Tries to extract a Message from the data buffer and process it."""
currentLength = len(self.buffer_in)
if currentLength < 24:
return False
# Extract the message header from the buffer, and return if not enough
# buffer to fully deserialize the message object.
try:
# Construct message
mstart = self.buffer_in[:24]
ms = StreamManager.GetStream(mstart)
reader = BinaryReader(ms)
m = Message()
# Extract message metadata
m.Magic = reader.ReadUInt32()
m.Command = reader.ReadFixedString(12).decode('utf-8')
m.Length = reader.ReadUInt32()
m.Checksum = reader.ReadUInt32()
# Return if not enough buffer to fully deserialize object.
messageExpectedLength = 24 + m.Length
if currentLength < messageExpectedLength:
return False
except Exception as e:
logger.debug(f"{self.prefix} Error: could not read message header from stream {e}")
# self.Log('Error: Could not read initial bytes %s ' % e)
return False
finally:
StreamManager.ReleaseStream(ms)
del reader
# The message header was successfully extracted, and we have enough enough buffer
# to extract the full payload
try:
# Extract message bytes from buffer and truncate buffer
mdata = self.buffer_in[:messageExpectedLength]
self.buffer_in = self.buffer_in[messageExpectedLength:]
# Deserialize message with payload
stream = StreamManager.GetStream(mdata)
reader = BinaryReader(stream)
message = Message()
message.Deserialize(reader)
if self.incoming_client and self.expect_verack_next:
if message.Command != 'verack':
self.Disconnect("Expected 'verack' got {}".format(message.Command))
# Propagate new message
self.MessageReceived(message)
except Exception as e:
logger.debug(f"{self.prefix} Could not extract message {e}")
# self.Log('Error: Could not extract message: %s ' % e)
return False
finally:
StreamManager.ReleaseStream(stream)
return True | python | {
"resource": ""
} |
q32771 | NeoNode.HandlePeerInfoReceived | train | def HandlePeerInfoReceived(self, payload):
"""Process response of `self.RequestPeerInfo`."""
addrs = IOHelper.AsSerializableWithType(payload, 'neo.Network.Payloads.AddrPayload.AddrPayload')
if not addrs:
return
for nawt in addrs.NetworkAddressesWithTime:
self.leader.RemoteNodePeerReceived(nawt.Address, nawt.Port, self.prefix) | python | {
"resource": ""
} |
q32772 | NeoNode.SendVersion | train | def SendVersion(self):
"""Send our client version."""
m = Message("version", VersionPayload(settings.NODE_PORT, self.remote_nodeid, settings.VERSION_NAME))
self.SendSerializedMessage(m) | python | {
"resource": ""
} |
q32773 | NeoNode.SendVerack | train | def SendVerack(self):
"""Send version acknowledge"""
m = Message('verack')
self.SendSerializedMessage(m)
self.expect_verack_next = True | python | {
"resource": ""
} |
q32774 | NeoNode.HandleVersion | train | def HandleVersion(self, payload):
"""Process the response of `self.RequestVersion`."""
self.Version = IOHelper.AsSerializableWithType(payload, "neo.Network.Payloads.VersionPayload.VersionPayload")
if not self.Version:
return
if self.incoming_client:
if self.Version.Nonce == self.nodeid:
self.Disconnect()
self.SendVerack()
else:
self.nodeid = self.Version.Nonce
self.SendVersion() | python | {
"resource": ""
} |
q32775 | NeoNode.HandleVerack | train | def HandleVerack(self):
"""Handle the `verack` response."""
m = Message('verack')
self.SendSerializedMessage(m)
self.leader.NodeCount += 1
self.identifier = self.leader.NodeCount
logger.debug(f"{self.prefix} Handshake complete!")
self.handshake_complete = True
self.ProtocolReady() | python | {
"resource": ""
} |
q32776 | NeoNode.SendSerializedMessage | train | def SendSerializedMessage(self, message):
"""
Send the `message` to the remote client.
Args:
message (neo.Network.Message):
"""
try:
ba = Helper.ToArray(message)
ba2 = binascii.unhexlify(ba)
self.bytes_out += len(ba2)
self.transport.write(ba2)
except Exception as e:
logger.debug(f"Could not send serialized message {e}") | python | {
"resource": ""
} |
q32777 | NeoNode.HandleBlockReceived | train | def HandleBlockReceived(self, inventory):
"""
Process a Block inventory payload.
Args:
inventory (neo.Network.Inventory):
"""
block = IOHelper.AsSerializableWithType(inventory, 'neo.Core.Block.Block')
if not block:
return
blockhash = block.Hash.ToBytes()
try:
if blockhash in BC.Default().BlockRequests:
BC.Default().BlockRequests.remove(blockhash)
except KeyError:
pass
try:
if blockhash in self.myblockrequests:
# logger.debug(f"{self.prefix} received block: {block.Index}")
self.heart_beat(HEARTBEAT_BLOCKS)
self.myblockrequests.remove(blockhash)
except KeyError:
pass
self.leader.InventoryReceived(block) | python | {
"resource": ""
} |
q32778 | NeoNode.HandleGetDataMessageReceived | train | def HandleGetDataMessageReceived(self, payload):
"""
Process a InvPayload payload.
Args:
payload (neo.Network.Inventory):
"""
inventory = IOHelper.AsSerializableWithType(payload, 'neo.Network.Payloads.InvPayload.InvPayload')
if not inventory:
return
for hash in inventory.Hashes:
hash = hash.encode('utf-8')
item = None
# try to get the inventory to send from relay cache
if hash in self.leader.RelayCache.keys():
item = self.leader.RelayCache[hash]
if inventory.Type == InventoryType.TXInt:
if not item:
item, index = BC.Default().GetTransaction(hash)
if not item:
item = self.leader.GetTransaction(hash)
if item:
message = Message(command='tx', payload=item, print_payload=False)
self.SendSerializedMessage(message)
elif inventory.Type == InventoryType.BlockInt:
if not item:
item = BC.Default().GetBlock(hash)
if item:
message = Message(command='block', payload=item, print_payload=False)
self.SendSerializedMessage(message)
elif inventory.Type == InventoryType.ConsensusInt:
if item:
self.SendSerializedMessage(Message(command='consensus', payload=item, print_payload=False)) | python | {
"resource": ""
} |
q32779 | NeoNode.HandleGetBlocksMessageReceived | train | def HandleGetBlocksMessageReceived(self, payload):
"""
Process a GetBlocksPayload payload.
Args:
payload (neo.Network.Payloads.GetBlocksPayload):
"""
if not self.leader.ServiceEnabled:
return
inventory = IOHelper.AsSerializableWithType(payload, 'neo.Network.Payloads.GetBlocksPayload.GetBlocksPayload')
if not inventory:
return
blockchain = BC.Default()
hash = inventory.HashStart[0]
if not blockchain.GetHeader(hash):
return
hashes = []
hcount = 0
while hash != inventory.HashStop and hcount < 500:
hash = blockchain.GetNextBlockHash(hash)
if hash is None:
break
hashes.append(hash)
hcount += 1
if hcount > 0:
self.SendSerializedMessage(Message('inv', InvPayload(type=InventoryType.Block, hashes=hashes))) | python | {
"resource": ""
} |
q32780 | NeoNode.Relay | train | def Relay(self, inventory):
"""
Wrap the inventory in a InvPayload object and send it over the write to the remote node.
Args:
inventory:
Returns:
bool: True (fixed)
"""
inventory = InvPayload(type=inventory.InventoryType, hashes=[inventory.Hash.ToBytes()])
m = Message("inv", inventory)
self.SendSerializedMessage(m)
return True | python | {
"resource": ""
} |
q32781 | Helper.DeserializeTX | train | def DeserializeTX(buffer):
"""
Deserialize the stream into a Transaction object.
Args:
buffer (BytesIO): stream to deserialize the Transaction from.
Returns:
neo.Core.TX.Transaction:
"""
mstream = MemoryStream(buffer)
reader = BinaryReader(mstream)
tx = Transaction.DeserializeFrom(reader)
return tx | python | {
"resource": ""
} |
q32782 | UnspentCoinState.FromTXOutputsConfirmed | train | def FromTXOutputsConfirmed(outputs):
"""
Get unspent outputs from a list of transaction outputs.
Args:
outputs (list): of neo.Core.TX.Transaction.TransactionOutput items.
Returns:
UnspentCoinState:
"""
uns = UnspentCoinState()
uns.Items = [0] * len(outputs)
for i in range(0, len(outputs)):
uns.Items[i] = int(CoinState.Confirmed)
return uns | python | {
"resource": ""
} |
q32783 | UnspentCoinState.IsAllSpent | train | def IsAllSpent(self):
"""
Flag indicating if all balance is spend.
Returns:
bool:
"""
for item in self.Items:
if item == CoinState.Confirmed:
return False
return True | python | {
"resource": ""
} |
q32784 | Transaction.Hash | train | def Hash(self):
"""
Get the hash of the transaction.
Returns:
UInt256:
"""
if not self.__hash:
ba = bytearray(binascii.unhexlify(self.GetHashData()))
hash = Crypto.Hash256(ba)
self.__hash = UInt256(data=hash)
return self.__hash | python | {
"resource": ""
} |
q32785 | Transaction.References | train | def References(self):
"""
Get all references.
Returns:
dict:
Key (UInt256): input PrevHash
Value (TransactionOutput): object.
"""
if self.__references is None:
refs = {}
# group by the input prevhash
for hash, group in groupby(self.inputs, lambda x: x.PrevHash):
tx, height = GetBlockchain().GetTransaction(hash.ToBytes())
if tx is not None:
for input in group:
refs[input] = tx.outputs[input.PrevIndex]
self.__references = refs
return self.__references | python | {
"resource": ""
} |
q32786 | Transaction.NetworkFee | train | def NetworkFee(self):
"""
Get the network fee.
Returns:
Fixed8:
"""
if self._network_fee is None:
input = Fixed8(0)
for coin_ref in self.References.values():
if coin_ref.AssetId == GetBlockchain().SystemCoin().Hash:
input = input + coin_ref.Value
output = Fixed8(0)
for tx_output in self.outputs:
if tx_output.AssetId == GetBlockchain().SystemCoin().Hash:
output = output + tx_output.Value
self._network_fee = input - output - self.SystemFee()
# logger.info("Determined network fee to be %s " % (self.__network_fee.value))
return self._network_fee | python | {
"resource": ""
} |
q32787 | Transaction.DeserializeFromBufer | train | def DeserializeFromBufer(buffer, offset=0):
"""
Deserialize object instance from the specified buffer.
Args:
buffer (bytes, bytearray, BytesIO): (Optional) data to create the stream from.
offset: UNUSED
Returns:
Transaction:
"""
mstream = StreamManager.GetStream(buffer)
reader = BinaryReader(mstream)
tx = Transaction.DeserializeFrom(reader)
StreamManager.ReleaseStream(mstream)
return tx | python | {
"resource": ""
} |
q32788 | Transaction.DeserializeUnsigned | train | def DeserializeUnsigned(self, reader):
"""
Deserialize object.
Args:
reader (neo.IO.BinaryReader):
Raises:
Exception: if transaction type is incorrect.
"""
txtype = reader.ReadByte()
if txtype != int.from_bytes(self.Type, 'little'):
raise Exception('incorrect type {}, wanted {}'.format(txtype, int.from_bytes(self.Type, 'little')))
self.DeserializeUnsignedWithoutType(reader) | python | {
"resource": ""
} |
q32789 | Transaction.DeserializeUnsignedWithoutType | train | def DeserializeUnsignedWithoutType(self, reader):
"""
Deserialize object without reading transaction type data.
Args:
reader (neo.IO.BinaryReader):
"""
self.Version = reader.ReadByte()
self.DeserializeExclusiveData(reader)
self.Attributes = reader.ReadSerializableArray('neo.Core.TX.TransactionAttribute.TransactionAttribute',
max=self.MAX_TX_ATTRIBUTES)
self.inputs = reader.ReadSerializableArray('neo.Core.CoinReference.CoinReference')
self.outputs = reader.ReadSerializableArray('neo.Core.TX.Transaction.TransactionOutput') | python | {
"resource": ""
} |
q32790 | Transaction.GetTransactionResults | train | def GetTransactionResults(self):
"""
Get the execution results of the transaction.
Returns:
None: if the transaction has no references.
list: of TransactionResult objects.
"""
if self.References is None:
return None
results = []
realresults = []
for ref_output in self.References.values():
results.append(TransactionResult(ref_output.AssetId, ref_output.Value))
for output in self.outputs:
results.append(TransactionResult(output.AssetId, output.Value * Fixed8(-1)))
for key, group in groupby(results, lambda x: x.AssetId):
sum = Fixed8(0)
for item in group:
sum = sum + item.Amount
if sum != Fixed8.Zero():
realresults.append(TransactionResult(key, sum))
return realresults | python | {
"resource": ""
} |
q32791 | ContractParameter.ToParameter | train | def ToParameter(item: StackItem):
"""
Convert a StackItem to a ContractParameter object
Args:
item (neo.VM.InteropService.StackItem) The item to convert to a ContractParameter object
Returns:
ContractParameter
"""
if isinstance(item, Array) or isinstance(item, Struct):
items = item.GetArray()
output = [ContractParameter.ToParameter(subitem) for subitem in items]
return ContractParameter(type=ContractParameterType.Array, value=output)
elif isinstance(item, Boolean):
return ContractParameter(type=ContractParameterType.Boolean, value=item.GetBoolean())
elif isinstance(item, ByteArray):
return ContractParameter(type=ContractParameterType.ByteArray, value=item.GetByteArray())
elif isinstance(item, Integer):
return ContractParameter(type=ContractParameterType.Integer, value=str(item.GetBigInteger()))
elif isinstance(item, InteropInterface):
return ContractParameter(type=ContractParameterType.InteropInterface, value=item.GetInterface()) | python | {
"resource": ""
} |
q32792 | ContractParameter.ToJson | train | def ToJson(self, auto_hex=True):
"""
Converts a ContractParameter instance to a json representation
Returns:
dict: a dictionary representation of the contract parameter
"""
jsn = {}
jsn['type'] = str(ContractParameterType(self.Type))
if self.Type == ContractParameterType.Signature:
jsn['value'] = self.Value.hex()
elif self.Type == ContractParameterType.ByteArray:
if auto_hex:
jsn['value'] = self.Value.hex()
else:
jsn['value'] = self.Value
elif self.Type == ContractParameterType.Boolean:
jsn['value'] = self.Value
elif self.Type == ContractParameterType.String:
jsn['value'] = str(self.Value)
elif self.Type == ContractParameterType.Integer:
jsn['value'] = self.Value
# @TODO, see ``FromJson``, not sure if this is working properly
elif self.Type == ContractParameterType.PublicKey:
jsn['value'] = self.Value.ToString()
elif self.Type in [ContractParameterType.Hash160,
ContractParameterType.Hash256]:
jsn['value'] = self.Value.ToString()
elif self.Type == ContractParameterType.Array:
res = []
for item in self.Value:
if item:
res.append(item.ToJson(auto_hex=auto_hex))
jsn['value'] = res
elif self.Type == ContractParameterType.InteropInterface:
try:
jsn['value'] = self.Value.ToJson()
except Exception as e:
pass
return jsn | python | {
"resource": ""
} |
q32793 | ContractParameter.ToVM | train | def ToVM(self):
"""
Used for turning a ContractParameter item into somethnig consumable by the VM
Returns:
"""
if self.Type == ContractParameterType.String:
return str(self.Value).encode('utf-8').hex()
elif self.Type == ContractParameterType.Integer and isinstance(self.Value, int):
return BigInteger(self.Value)
return self.Value | python | {
"resource": ""
} |
q32794 | ContractParameter.FromJson | train | def FromJson(json):
"""
Convert a json object to a ContractParameter object
Args:
item (dict): The item to convert to a ContractParameter object
Returns:
ContractParameter
"""
type = ContractParameterType.FromString(json['type'])
value = json['value']
param = ContractParameter(type=type, value=None)
if type == ContractParameterType.Signature or type == ContractParameterType.ByteArray:
param.Value = bytearray.fromhex(value)
elif type == ContractParameterType.Boolean:
param.Value = bool(value)
elif type == ContractParameterType.Integer:
param.Value = int(value)
elif type == ContractParameterType.Hash160:
param.Value = UInt160.ParseString(value)
elif type == ContractParameterType.Hash256:
param.Value = UInt256.ParseString(value)
# @TODO Not sure if this is working...
elif type == ContractParameterType.PublicKey:
param.Value = ECDSA.decode_secp256r1(value).G
elif type == ContractParameterType.String:
param.Value = str(value)
elif type == ContractParameterType.Array:
val = [ContractParameter.FromJson(item) for item in value]
param.Value = val
return param | python | {
"resource": ""
} |
q32795 | Coin.CoinFromRef | train | def CoinFromRef(coin_ref, tx_output, state=CoinState.Unconfirmed, transaction=None):
"""
Get a Coin object using a CoinReference.
Args:
coin_ref (neo.Core.CoinReference): an object representing a single UTXO / transaction input.
tx_output (neo.Core.Transaction.TransactionOutput): an object representing a transaction output.
state (neo.Core.State.CoinState):
Returns:
Coin: self.
"""
coin = Coin(coin_reference=coin_ref, tx_output=tx_output, state=state)
coin._transaction = transaction
return coin | python | {
"resource": ""
} |
q32796 | CoinReference.Equals | train | def Equals(self, other):
"""
Test for equality.
Args:
other (obj):
Returns:
bool: True `other` equals self.
"""
if other is None:
return False
if other.PrevHash.ToBytes() == self.PrevHash.ToBytes() and other.PrevIndex == self.PrevIndex:
return True
return False | python | {
"resource": ""
} |
q32797 | Helper.GetHashData | train | 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 | python | {
"resource": ""
} |
q32798 | Helper.Sign | train | 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 | python | {
"resource": ""
} |
q32799 | Helper.AddrStrToScriptHash | train | 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]) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.