def deploy(self, isLocal, callback): result = None fromAccount = Accounts.getAccountByAddress(self.fromAddress) if fromAccount != None: if isLocal: toAddress = Crypto.generateAddress(fromAccount.address) _script = bytearray() _script.append(Config.getIntValue("EXTENSION_SCRIPT_VERSION")) _script.extend(self.script) _script = DataType.serialize(_script) extraData = None if len(self.parameters) > 0: extraData = self.parameters extraData.append(fromAccount.address) output = Output(toAddress, _script, self.value, extraData) result = self.handleLocalScript(fromAccount, output, True) if result != None: Contracts.addContract(Contract(toAddress), False) else: result = MemoryPool.addUnconfirmedTransaction( fromAccount, None, self.value, self.gasLimit, self.gasPrice, self.script, self.parameters) try: result = DataType.toHex(result) except: pass if result != None: callback(JSONRPC.createResultObject(result, self.id)) else: self.onFailure(callback)
def deserialize(self, buffer): decodedBuffer = RLP.decode(buffer) self.chainWork = DataType.deserialize(decodedBuffer[0], DataType.INT, 0) self.previousHash = decodedBuffer[1] self.gasLimit = DataType.deserialize(decodedBuffer[2], DataType.INT, 0) self.height = DataType.deserialize(decodedBuffer[3], DataType.INT, 0)
def deserialize(self, payload): if self.validatePayload(payload, 2): self.type = DataType.deserialize(payload[0]) self.nonce = DataType.deserialize(payload[1], DataType.INT, 0) if self.validate(): return True return False
def deserialize(self, payload): if self.validatePayload(payload, 2): self.type = DataType.deserialize(payload[0]) self.addrList = DataType.deserialize(payload[1], DataType.LIST, []) if self.validate(): return True return False
def serialize(self): return { 'address': Address.toAddressStr(self.address), 'public': DataType.toHex(self.public), 'private': DataType.toHex(self.private), 'type': self.type }
def encodeItem(item, itemLen, prefix): if itemLen <= SHORT_PAYLOAD: return DataType.intToBytes(prefix + itemLen) + item else: itemLen = DataType.intToBytes(itemLen) return DataType.intToBytes(prefix + len(itemLen) + SHORT_PAYLOAD) + itemLen + item
def deserialize(self, buffer): decodedBuffer = RLP.decode(buffer) self.host = DataType.deserialize(decodedBuffer[0]) self.version = DataType.deserialize(decodedBuffer[1]) self.lastVersionNonce = DataType.deserialize(decodedBuffer[2], DataType.INT, None) self.chainHeadBlockHash = decodedBuffer[3] self.lastUpdate = DataType.deserialize(decodedBuffer[4], DataType.INT, 0)
def writeResponse(self, response): response = DataType.serialize(response) responseLen = len(response) responseLen = DataType.intToBytes( responseLen, Config.getIntValue("SOCKET_HEADER_BUFFER_SIZE")) self.request.sendall(responseLen) self.request.sendall(response)
def createAtomicSwapTx(self, callback): fromAccount = Accounts.getAccountByAddress(self.fromAddress) toMultiSigAccount = Accounts.getAccountByAddress(self.toAddress) ''' A picks a random number x ''' hashPrivKey = Crypto.generateHash(toMultiSigAccount.private) ''' A creates TX1: "Pay w BTC to <B's public key> if (x for H(x) known and signed by B) or (signed by A & B)" ''' transactionA1 = MemoryPool.createUnconfirmedAtomicSwapTransaction(fromAccount, toMultiSigAccount.address, self.value, self.gasLimit, self.gasPrice, Script.verifyAtomicSwapSignature(), self.threshold) if transactionA1 != None: ''' A creates TX2: "Pay w BTC from TX1 to <A's public key>, locked 48 hours in the future, signed by A" ''' transactionA2 = MemoryPool.createUnconfirmedAtomicSwapTransaction(fromAccount, toMultiSigAccount.address, self.value, self.gasLimit, self.gasPrice, Script.verifyAtomicSwapLock()) if transactionA2 != None: tx = transactionA1.serialize() unsignedTx = transactionA2.serialize() result = { 'tx': DataType.toHex(tx), 'unsignedTx': DataType.toHex(unsignedTx) } callback( JSONRPC.createResultObject(result, self.id) ) else: self.onFailure(callback) else: self.onFailure(callback)
def handleLocalScript(self, fromAccount, output, deploy): gasLimit = Config.getIntValue('TRANSACTION_LOCAL_GAS_LIMIT') gasPrice = Config.getIntValue('TRANSACTION_LOCAL_GAS_PRICE') localTx = Transaction(gasLimit, gasPrice) localTx.gasRemaining = Config.getIntValue( 'TRANSACTION_LOCAL_GAS_REMAINING') _input = None if deploy: pass else: scriptData = [] scriptData.append(DataType.zeroFillArray(0, 32)) scriptData.append(DataType.zeroFillArray(0, 32)) scriptData.append(fromAccount.address) scriptData.extend(self.parameters) _input = Input(Config.getValue('SCRIPT_TRANSACTION_ID'), Config.getIntValue('SCRIPT_OUTPUT_INDEX')) _input.witness = scriptData if RVM.run(localTx, _input, output, True, deploy, True): if len(localTx.internalOutputs) > 0: internalOutput = localTx.internalOutputs[-1] if deploy: PersistentStorage.add(internalOutput.address, internalOutput, True) result = 'Script Deployed Locally' else: result = internalOutput.script try: result = DataType.toHex(result) result = DataType.asInt(result, 16) except ValueError: pass return result return None
def deserialize(self, payload): if self.validatePayload(payload, 3): self.type = DataType.deserialize(payload[0]) self.version = DataType.deserialize(payload[1], DataType.INT, 0) self.blockHashes = payload[2] if self.validate(): return True return False
def deserialize(self, buffer): decodedBuffer = RLP.decode(buffer) self.output = Output() self.output.deserialize(decodedBuffer[0]) self.txOutputSize = DataType.deserialize(decodedBuffer[1], DataType.INT, 0) self.height = DataType.deserialize(decodedBuffer[2], DataType.INT, 0) self.coinbase = DataType.deserialize(decodedBuffer[3], DataType.BOOL, False)
def deserialize(self, payload): if self.validatePayload(payload, 5): self.type = DataType.deserialize(payload[0]) self.version = DataType.deserialize(payload[1]) self.timestamp = DataType.deserialize(payload[2], DataType.INT, 0) self.nonce = DataType.deserialize(payload[3], DataType.INT, 0) self.chainHeadBlockHash = payload[4] if self.validate(): return True return False
def decode(buffer): decodedBuffer = b'' if len(buffer) > 0: prefix = buffer[0] if prefix >= BYTE_PREFIX_START and prefix <= BYTE_PREFIX_END: decodedBuffer += DataType.intToBytes(prefix) elif prefix >= STRING_PREFIX_START and prefix <= STRING_PREFIX_END: offset = 1 decodedBufferLen = None if prefix > STRING_55_LEN_MAX_RANGE: prefixLen = prefix - STRING_55_LEN_MAX_RANGE bufferLen = buffer[offset:offset + prefixLen] decodedBufferLen = DataType.bytesToInt(bufferLen) offset += prefixLen else: decodedBufferLen = prefix - STRING_PREFIX_START decodedBuffer += buffer[offset:offset + decodedBufferLen] elif prefix >= LIST_PREFIX_START and prefix <= LIST_PREFIX_END: decodedBuffer = [] offset = 1 decodedBufferLen = None if prefix > LIST_55_LEN_MAX_RANGE: prefixLen = prefix - LIST_55_LEN_MAX_RANGE bufferLen = buffer[offset:offset + prefixLen] decodedBufferLen = DataType.bytesToInt(bufferLen) offset += prefixLen else: decodedBufferLen = prefix - LIST_PREFIX_START buffer = buffer[offset:offset + decodedBufferLen] while len(buffer) > 0: tempBufferDecoded = decode(buffer) decodedBuffer.append(tempBufferDecoded) offset = 1 prefix = buffer[0] if prefix >= BYTE_PREFIX_START and prefix <= BYTE_PREFIX_END: decodedBufferLen = 0 elif prefix >= STRING_PREFIX_START and prefix <= STRING_PREFIX_END: if prefix > STRING_55_LEN_MAX_RANGE: prefixLen = prefix - STRING_55_LEN_MAX_RANGE bufferLen = buffer[offset:offset + prefixLen] decodedBufferLen = DataType.bytesToInt(bufferLen) offset += prefixLen else: decodedBufferLen = prefix - STRING_PREFIX_START elif prefix >= LIST_PREFIX_START and prefix <= LIST_PREFIX_END: if prefix > LIST_55_LEN_MAX_RANGE: prefixLen = prefix - LIST_55_LEN_MAX_RANGE bufferLen = buffer[offset:offset + prefixLen] decodedBufferLen = DataType.bytesToInt(bufferLen) offset += prefixLen else: decodedBufferLen = prefix - LIST_PREFIX_START buffer = buffer[offset + decodedBufferLen:] return decodedBuffer
def do_POST(self): if self.hasAuthorization(): length = DataType.asInt(self.headers['Content-Length']) payload = self.rfile.read(length) payload = DataType.deserialize(payload) payload = json.loads(payload) self.handlePayload(payload) else: response = JSONRPC.createErrorObject( -32010, 'unauthorized', 'you are not authorized to access this resource', None) self.writeResponse(response, doHead=False)
def merge(): script = bytearray() script.append(Config.getIntValue("SCRIPT_VERSION")) script.append(Opcodes.alias('MERGE', True)) return DataType.serialize(script)
def addPeers(peers): for peer in peers: if peer.host != Peers.hostname and peer.host != Peers.ipAddress: currPeer = getPeerByHost(peer.host) synchronized = False if currPeer == None: currPeer = peer else: currPeer.merge(peer) synchronized = True currPeer.lastUpdate = DataType.asTime() hostBytes = DataType.serialize(currPeer.host) Peers.peers.set(hostBytes, currPeer.serialize()) if not synchronized: Sync.synchronize(currPeer.host) Sync.addr(currPeer.host)
def call(self, isLocal, callback): result = None fromAccount = Accounts.getAccountByAddress(self.fromAddress) if fromAccount != None: if isLocal: _output = PersistentStorage.get(self.script, True) if _output == None: unspentTransactionScript = UXTO.getUnspentTransactionScript( self.script) if unspentTransactionScript != None: _output = unspentTransactionScript.output if _output != None: result = self.handleLocalScript(fromAccount, _output, False) else: result = MemoryPool.addUnconfirmedTransaction( fromAccount, self.script, self.value, self.gasLimit, self.gasPrice, None, self.parameters) try: result = DataType.toHex(result) except: pass if result != None: callback(JSONRPC.createResultObject(result, self.id)) else: self.onFailure(callback)
def verifyMultiSignature(): script = bytearray() script.append(Config.getIntValue("SCRIPT_VERSION")) script.append(Opcodes.alias('CHECKMULTISIGVERIFY', True)) return DataType.serialize(script)
def deserialize(self, payload): if self.validatePayload(payload, 2): self.type = DataType.deserialize(payload[0]) self.transaction = payload[1] if self.validate(): return True return False
def verifyAtomicSwapLock(): script = bytearray() script.append(Config.getIntValue("SCRIPT_VERSION")) script.append(Opcodes.alias('CHECKATOMICSWAPLOCKVERIFY', True)) return DataType.serialize(script)
def open(self, subDatabase=None): self.lock.acquire() self.db = lmdb.open(self.database, max_dbs=Config.getIntValue('MAX_DATABASES')) subDatabaseBytes = DataType.serialize( self.subDatabase if subDatabase == None else subDatabase) self.subDb = self.db.open_db(subDatabaseBytes)
def deserialize(self, payload): if payload != None and len(payload) == 2: self.invType = DataType.deserialize(payload[0]) self.invHash = payload[1] if self.validate(): return True return False
def getInstance(msg): msgType = msg if isinstance(msg, list): msgType = DataType.deserialize(msg[0]) '''Socket Messages Types''' if MessageType.ADDR == msgType: return Addr() elif MessageType.BLOCK == msgType: return Block() elif MessageType.GETADDR == msgType: return GetAddr() elif MessageType.GETBLOCKS == msgType: return GetBlocks() elif MessageType.GETDATA == msgType: return GetData() elif MessageType.INV == msgType: return Inv() elif MessageType.MEMPOOL == msgType: return MemPool() elif MessageType.PING == msgType: return Ping() elif MessageType.PONG == msgType: return Pong() elif MessageType.TX == msgType: return Tx() elif MessageType.VERACK == msgType: return VerAck() elif MessageType.VERSION == msgType: return Version()
def __init__(self): super().__init__() self.type = MessageType.VERSION self.version = Config.getValue("NODE_VERSION") self.timestamp = DataType.asTime() self.nonce = randint(0, sys.maxsize) self.chainHeadBlockHash = None
def getBasicAuth(): username = Config.getValue("HTTP_RPC_USERNAME") password = Config.getValue("HTTP_RPC_PASSWORD") userpass = "******" % (username, password) userpassBytes = DataType.serialize(userpass) userpassB64 = b64encode(userpassBytes) return 'Basic %s' % userpassB64.decode("ascii")
def get(self, callback = None): accounts = [] # Account Types standard = [] multisig = [] atomicswap = [] for account in Accounts.getAccounts(): confirmedBalance = Accounts.getConfirmedBalanceByAddress(account.address) confirmedBalance = Units.toValue(confirmedBalance) confirmedBalance = DataType.asFloat(confirmedBalance) address = Address.to0xAddress(account.address) accountInfo = { 'address': address, 'type': account.type, 'balance': confirmedBalance } if account.type == AccountType.STANDARD: standard.append(accountInfo) elif account.type == AccountType.MULTISIGNATURE: multisig.append(accountInfo) elif account.type == AccountType.ATOMIC_SWAP: atomicswap.append(accountInfo) accounts.extend(standard) accounts.extend(multisig) accounts.extend(atomicswap) callback( JSONRPC.createResultObject(accounts, self.id) )
def getNewBlock(self, address, previousHash, bits, extraNonce): previousIndexBlock = self.getIndexBlockByHash(previousHash) block = Block() gasLimit = Config.getIntValue("BLOCK_REWARDS_GAS_LIMIT") gasPrice = Config.getIntValue("BLOCK_REWARDS_GAS_PRICE") transaction = Transaction(gasLimit, gasPrice) height = previousIndexBlock.height + 1 coinbaseData = [ DataType.asString(height), DataType.asString(bits), DataType.asString(extraNonce) ] transaction.addCoinbaseInput(coinbaseData) block.transactions.append(transaction) txFees = 0 totalTxGasUsed = 0 unconfirmedTransactions = MemoryPool.getMemoryPool() for txId in unconfirmedTransactions: unconfirmedTransaction = unconfirmedTransactions[txId] block.transactions.append(unconfirmedTransaction) txFees += unconfirmedTransaction.calculateTxFee() totalTxGasUsed += unconfirmedTransaction.calculateTxGasUsed() blockRewards = Config.getDecimalValue("BLOCK_REWARDS") blockRewards = Units.toUnits(blockRewards) coinbaseValue = blockRewards + txFees script = Script.verifySignature() transaction.addOutput(address, script, coinbaseValue) transaction.hash() #Include coinbase tx gas used totalTxGasUsed += transaction.calculateTxGasUsed() block.merkleRoot = MerkleTree.getMerkleRoot(block.transactions, False) block.witnessRoot = MerkleTree.getMerkleRoot(block.transactions, True) blockGasLimit = previousIndexBlock.gasLimit + (previousIndexBlock.gasLimit * (1 / 1024)) blockGasLimit = math.ceil(blockGasLimit) block.gasLimit = blockGasLimit block.gasUsed = totalTxGasUsed block.nonce = 0 block.bits = bits block.previousHash = previousHash return block
def jumpi(self): destination = self.popAsInt() cond = self.pop() if cond != 0: self.pc = DataType.asInt(destination, 16) if self.JUMPDEST != self.code[self.pc]: self.pc = len(self.code) self.invalid = True
def sload(self): PersistentStorage.dump() key = self.pop() key = self.persistentStorageKey + key value = PersistentStorage.get(key, True) if value == None: value = DataType.zeroFillArray(0, 32) self.stack.append(value)