def GetKey(key): msg = concat("Get key: ", key) Log(msg) #get key context = GetContext() data = Get(context, key) msg = concat("Data found: ", data) Log(msg) return data
def Main(initialString, args): result = initialString for word in args: if result == None: result = word else: result = concat(result, " ") result = concat(result, word) print(result)
def SignOnly(address, document, metadata): idConcat = concat(address, document) docKey = sha1(idConcat) data = concat(docKey, metadata) # tx = GetTransactionHash() # data = concat(data, tx) hash = sha256(data) return hash
def isGameInstanceJudged(game_type, instance_ts): k1 = concat(key_prefix_game_type, game_type) k2 = concat(key_prefix_game_instance, instance_ts) k12 = concat(k1, k2) key = concat(k12, key_prefix_game_instance_judged) context = GetContext() v = Get(context, key) if v == 0: return False else: return True
def put_cert(domain, cert): curr_domains = Get(GetContext, "all_domains") if curr_domains: Delete(GetContext, "all_domains") curr_domains = concat(curr_domains, ",") new_curr_domains = concat(curr_domains, domain) Put(GetContext, "all_domains", new_curr_domains) else: Put(GetContext, "all_domains", domain) Put(GetContext, domain, cert) return "ok"
def IncrementCount(prediction_name, normalised_timestamp, price, context): k0 = concat("prediction_count", prediction_name) k1 = concat(k0, normalised_timestamp) k2 = concat(k1, price) count = Get(context, k2) if count == 0: Put(context, k2, 1) return 1 else: count = count + 1 Put(context, k2, count) return count
def isOracleRegisteredForInstance(game_type, instance_ts, oracle): k1 = concat(key_prefix_game_type, game_type) k2 = concat(key_prefix_game_instance, instance_ts) k12 = concat(k1, k2) k4 = concat(key_prefix_game_instance_oracle, oracle) key = concat(k12, k4) context = GetContext() v = Get(context, key) if v == 0: return False else: return True
def CreateNewPredictionGame(prediction_name, context): # Check if Prediction Live if CheckPredictionGameLive(prediction_name, context): Log("Prediction Game is live") else: key = concat("prediction_live", prediction_name) Put(context, key, 1) normalised_timestamp = GetNormalisedTimestamp() key = concat("timestamp", prediction_name) Put(context, key, normalised_timestamp) return True return False
def CreateNewGameInstance(client_hash, game_type, instance_ts): if isGameInstanceLive(game_type, instance_ts): return "Game Instance is Already Live" else: k1 = concat(key_prefix_game_type, game_type) k2 = concat(key_prefix_game_instance, instance_ts) key = concat(k1, k2) context = GetContext() Put(context, key, client_hash) key_hash = concat(key, client_hash) Notify(key_hash) return "Success"
def ValidateArgsLength(args, length_required): length = len(args) if length != length_required: msg_a = concat("Expected length: ", length_required) msg_b = concat(", Received length: ", length) msg = concat(msg_a, msg_b) Log(msg) return False return True
def IncrementCountForPrediction(game_type, instance_ts, prediction): # Get current count k1 = concat(key_prefix_game_type, game_type) k2 = concat(key_prefix_game_instance, instance_ts) k12 = concat(k1, k2) k3 = concat(key_prefix_game_instance_prediction, prediction) key = concat(k12, k3) p_count = Get(GetContext(), key) if p_count == 0: p_count = 1 else: p_count = p_count + 1 Put(GetContext(), key, p_count) return p_count
def generate_uid(ref=''): height = GetHeight() # header = GetHeader(height) # header.Timestamp block = GetBlock(height) timestamp = block.Timestamp tx = block.Transactions[0] tx_hash = tx.Hash time_hash = concat(timestamp, tx_hash) return concat(time_hash, ref)
def Sign(address, document, metadata): idConcat = concat(address, document) docKey = sha1(idConcat) data = concat(docKey, metadata) # tx = GetTransactionHash() # data = concat(data, tx) hash = sha256(data) if not checkIfKeyExists(docKey): StoreKey(docKey, hash) StoreTimestamp(hash) return hash return False
def Stage(operation, dest, tag, amount): context = GetContext() src = getSource() dest_tag = concat(dest, tag) dest_tag_users = concat(dest_tag, "-users") dest_tag_src = concat(dest_tag, src) if operation == 'donate': donation = getValue() donate(context, dest_tag, dest_tag_users, dest_tag_src, src, donation) return "WOW I LOVE TO HACK THIS IS SO THRILLING" if operation == 'spend': spend(context, amount, src, dest, tag) return "Not yet functional" return "Invalid operation"
def submitPost(args): # Default args user = args[0] postHash = args[1] # Creating domains postDomain = "post." userDomain = concat("user.", user) postLatestDomain = concat(postDomain, "latest") userLatestDomain = concat(userDomain, ".latest") """ Adding to post domain post.latest Latest index of a post in common post.{postIndex} Getting a post by index post.data.{IPFS_PostHash} Getting a post by Hash From IPFS post.{IPFS_PostHash} Getting post by Hash from IPFS (Optional) """ # Setting post.latest = {postIndex} - increase afterwards latestPostIndex = Get(GetContext, postLatestDomain) newLatestPostIndex = -1 if latestPostIndex == '': newLatestPostIndex = 0 Put(GetContext, postLatestDomain, newLatestPostIndex) else: newLatestPostIndex = latestPostIndex + 1 Put(GetContext, postLatestDomain, newLatestPostIndex) # Setting post.{postIndex} = {postHash} postIndexDomain = concat(postDomain, newLatestPostIndex) Put(GetContext, postIndexDomain, postHash) # Setting post.data.{postHash} = {postIndex} postDataDomainTemp = concat(postDomain, 'data.') postDataDomain = concat(postDataDomainTemp, postHash) Put(GetContext, postDataDomain, newLatestPostIndex) # Insert the post on domain "post.{index}" postKeyDomain = concat(postDomain, newLatestPostIndex) Put(GetContext, postKeyDomain, postHash) """ Adding to user domain user.{userAddress} User address of a user (Public key/hash) user.{userAddress}.latest Getting the latest post index of a certain user user.{userAddress}.{postIndex} Getting a post from a certain user by index """ # Setting user.{userAddress}.latest = {postIndex} latestUserPostIndex = Get(GetContext, userLatestDomain) newLatestUserPostIndex = -1 if latestUserPostIndex == '': newLatestUserPostIndex = 0 Put(GetContext, userLatestDomain, newLatestUserPostIndex) else: newLatestUserPostIndex = latestUserPostIndex + 1 Put(GetContext, userLatestDomain, newLatestUserPostIndex) # Setting user.{userAddress}.{postIndex} = {postHash} userIndexDomain = concat(userDomain, newLatestUserPostIndex) Put(GetContext, userIndexDomain, postHash) return True
def GenerateStorageKey(s1, s2: str) -> str: """Concatenate arguments for use as storage key. Args: s1 (str): first string to be used in concatenation. s2 (str): second string to be used in concatenation. Return: (str): args concatenated together with a '.' between each value. """ withPeriod = concat(s1, '.') return concat(withPeriod, s2)
def kyc_deregister(self, args, token: Token): """ :param args:list a list of addresses to deregister :param token: Token A token object with your ICO settings :return: int: The number of addresses deregistered from KYC """ ok_count = 0 storage = StorageAPI() owner = storage.get(token.owner_key) if CheckWitness(owner): for address in args: if len(address) == 20: kyc_storage_key = concat(self.kyc_key, address) storage.delete(kyc_storage_key) OnKYCDeregister(address) ok_count += 1 return ok_count
def kyc_register(self, args, token:Token): """ :param args:List Eine Liste der Adressen die zu registrieren sind :param token:Token Ein Token Objekt mit Ihren ICO Einstellungen :return: int: Die Nummer der Adressen die mit KYC registriert werden """ ok_count = 0 if CheckWitness(token.owner): for address in args: if len(address) == 20: storage = StorageAPI() kyc_storage_key = concat(self.kyc_key, address) storage.put(kyc_storage_key, True) OnKYCRegister(address) ok_count += 1 return ok_count
def do_approve(self, storage: StorageAPI, t_owner, t_spender, amount): if not CheckWitness(t_owner): print("Incorrect permission") return False from_balance = storage.get(t_owner) # Kann keinen Betrag bestätigen der momentan # größer ist als der von "from balance" if from_balance >= amount: approval_key = concat(t_owner, t_spender) current_approved_balance = storage.get(approval_key) new_approved_balance = current_approved_balance + amount storage.put(approval_key, new_approved_balance) OnApprove(t_owner, t_spender, amount) return True return False
def do_approve(self, storage: StorageAPI, t_owner, t_spender, amount): if not CheckWitness(t_owner): print("Incorrect permission") return False if amount < 0: print("Negative amount") return False from_balance = storage.get(t_owner) # cannot approve an amount that is # currently greater than the from balance if from_balance >= amount: approval_key = concat(t_owner, t_spender) if amount == 0: storage.delete(approval_key) else: storage.put(approval_key, amount) OnApprove(t_owner, t_spender, amount) return True return False
def SubmitPrediction(oracle, game_type, instance_ts, prediction): if not isGameInstanceLive(game_type, instance_ts): return "Game Instance not yet commissioned" if isGameInstanceJudged(game_type, instance_ts): return "Game Instance already judged" if CheckTimestamp(instance_ts): return JudgeInstance(game_type, instance_ts) # Too late to submit, but can judge else: # Check if Oracle already registered if isOracleRegisteredForInstance(oracle, game_type, instance_ts): return "Already registered" current_oracle_balance = GetOracleBalance(oracle) n_oracles_for_instance = GetOracleCountForInstance(game_type, instance_ts) # See if the agent has sent any NEO-GAS assets tx = GetScriptContainer() refs = tx.References if len(refs) < 1: if current_oracle_balance >= collateral_requirement: new_count = n_oracles_for_instance + 1 RegisterOracle(game_type, instance_ts, oracle, new_count) else: # No assets sent and existing balance too low return "Not enough balance to register" else: ref = refs[0] sentAsset = GetAssetId(ref) #sender_hash = GetScriptHash(ref) if sentAsset == GAS_ASSET_ID: receiver = GetExecutingScriptHash() totalGasSent = 0 cOutputs = len(tx.Outputs) for output in tx.Outputs: Log(output.Value) shash = GetScriptHash(output) if shash == receiver: totalGasSent = totalGasSent + output.Value if totalGasSent == b'\x00e\xcd\x1d': current_oracle_balance = current_oracle_balance + totalGasSent key = concat(key_prefix_agent_available_balance, oracle) # Updates Balance of Oracle context = GetContext() Put(context, key, current_oracle_balance) new_count = n_oracles_for_instance + 1 RegisterOracle(game_type, instance_ts, oracle, new_count) else: return "Wrong amount of NEO GAS Sent" # Now to submit prediction if no errors RegisterPrediction(game_type, instance_ts, oracle, prediction) p_count = IncrementCountForPrediction(game_type, instance_ts, prediction) max_so_far = GetCurrentMax(game_type, instance_ts) if p_count > max_so_far: # New Current Winner UpdateMaxVotes(game_type, instance_ts, p_count) UpdatePrediction(game_type, instance_ts, prediction) if CheckTimestamp(instance_ts): return JudgeInstance(game_type, instance_ts) return True
def AddOracle(self, args): storage = StorageAPI() isValidOwner = self.ValidateOwner() if isValidOwner == False: return False isValidLength = ValidateArgsLength(args, 1) if isValidLength == False: return False oracleID = args[0] oracleKey = concat(self.oracle_prefix, oracleID) isOracle = storage.get(oracleKey) if isOracle == True: Log("Address is already an oracle") return False oracleCount = storage.get(self.oracle_count_key) newCount = oracleCount + 1 storage.put(oracleKey, True) storage.put(self.oracle_count_key, newCount) OnOracleAdded(oracleID, newCount) return True
def check_winners(self, storage: StorageAPI, address): if address == self.owner: return 10000 place_key = concat('place', address) current_place = storage.getitem(place_key) # if they aleady won, we don't want to let them do it again if current_place > 0: return 0 total_winners = storage.getitem('total_winners') place = total_winners + 1 storage.putitem('total_winners', place) storage.putitem(place_key, place) # persist winners if place == 1: storage.putitem('first_place', address) elif place == 2: storage.putitem('second_place', address) elif place == 3: storage.putitem('third_place', address) return place
def do_allowance(self, storage: StorageAPI, t_owner, t_spender): allowance_key = concat(t_owner, t_spender) amount = storage.get(allowance_key) return amount
def remove_offer(marketplace, offer_id): """ Helper method to remove an offer that exists on a marketplace. :param marketplace:str The name of the marketplace to access. :param offer_id:int The id of the offer to remove. :return: bool: Whether the offer was removed. """ context = GetContext() # Concatenate an offer key for the specified marketplace. marketplace_offers_key = concat(offers_key, marketplace) # Get all the available offers of a marketplace. offers_s = get_all_offers(marketplace) offers = deserialize_bytearray(offers_s) # Iterate through the offers, we must currently remove by index. # TODO: Remove manually searching for the index once list method "indexOf" is added. current_index = 0 for offer in offers: # If the offer equals the offer_id remove at current_index. if offer == offer_id: offers.remove(current_index) # Replace the list of offers currently in storage with the modified list. offers_s = serialize_array(offers) Delete(context, marketplace_offers_key) Put(context, marketplace_offers_key, offers_s) # Delete the offer from the storage. Delete(context, offer_id) return True current_index += 1 return False
def do_approve(self, storage: StorageAPI, t_owner, t_spender, amount): if not CheckWitness(t_owner): print("Incorrect permission") return False from_balance = storage.get(t_owner) # cannot approve an amount that is # currently greater than the from balance if from_balance >= amount: approval_key = concat(t_owner, t_spender) current_approved_balance = storage.get(approval_key) new_approved_balance = current_approved_balance + amount storage.put(approval_key, new_approved_balance) OnApprove(t_owner, t_spender, amount) return True return False
def kyc_register(self, args, token:Token): """ :param args:list a list of addresses to register :param token:Token A token object with your ICO settings :return: int: The number of addresses to register for KYC """ ok_count = 0 if CheckWitness(token.owner): for address in args: if len(address) == 20: storage = StorageAPI() kyc_storage_key = concat(self.kyc_key, address) storage.put(kyc_storage_key, True) OnKYCRegister(address) ok_count += 1 return ok_count
def get_kyc_status(self, address, storage:StorageAPI): """ Looks up the KYC status of an address :param address:bytearray The address to lookup :param storage:StorageAPI A StorageAPI object for storage interaction :return: bool: KYC Status of address """ kyc_storage_key = concat(self.kyc_key, address) return storage.get(kyc_storage_key)
def calculate_can_exchange(self, token: Token, amount: int, address): """ Perform custom token exchange calculations here. :param token:Token The token settings for the sale :param amount:int Number of tokens to convert from asset to tokens :param address:bytearray The address to mint the tokens to :return: bool: Whether or not an address can exchange a specified amount """ height = GetHeight() storage = StorageAPI() current_in_circulation = storage.get(token.in_circulation_key) new_amount = current_in_circulation + amount if new_amount > token.total_supply: print("amount greater than total supply") return False print("trying to calculate height????") if height < token.block_sale_start: print("sale not begun yet") return False # if we are in free round, any amount if height > token.limited_round_end: print("Free for all, accept as much as possible") return True # check amount in limited round if amount <= token.max_exchange_limited_round: # check if they have already exchanged in the limited round r1key = concat(address, self.limited_round_key) has_exchanged = storage.get(r1key) # if not, then save the exchange for limited round if not has_exchanged: storage.put(r1key, True) return True print("already exchanged in limited round") return False print("too much for limited round") return False
def serialize_array(items): # serialize the length of the list itemlength = serialize_var_length_item(items) output = itemlength # now go through and append all your stuff for item in items: # get the variable length of the item # to be serialized itemlen = serialize_var_length_item(item) # add that indicator output = concat(output, itemlen) # now add the item output = concat(output, item) # return the stuff return output
def kyc_status(self, args): """ Gets the KYC Status of an address :param args:list a list of arguments :return: bool: Returns the kyc status of an address """ storage = StorageAPI() if len(args) > 0: addr = args[0] kyc_storage_key = concat(self.kyc_key, addr) return storage.get(kyc_storage_key) return False
def serialize_var_length_item(item): # get the length of your stuff stuff_len = len(item) # now we need to know how many bytes the length of the array # will take to store # this is one byte if stuff_len <= 255: byte_len = b'\x01' # two byte elif stuff_len <= 65535: byte_len = b'\x02' # hopefully 4 byte else: byte_len = b'\x04' out = concat(byte_len, stuff_len) return out