def onSuccess(self, callback = None):
     isMiningSupported = Config.getBoolValue("MINING_SUPPORTED")
     if isMiningSupported:
         account = Accounts.getAccountByAddress(self.address)
         if account != None:
             if not self.chain.exitsMiningWorker(account):
                 self.chain.addMiningWorker(account, self.enabled)
                 callback(
                     JSONRPC.createResultObject('added mining worker', self.id)
                 )
             else:
                 if self.enabled:
                     callback(
                         JSONRPC.createResultObject('worker is mining', self.id)
                     )
                 else:
                     self.chain.stopMiningWorker(account)
                     callback(
                         JSONRPC.createResultObject('worker is stopped mining', self.id)
                     )
         else:
             callback(
                 JSONRPC.createErrorObject(-32005, 'not found', 'account not found', self.id)
             )
     else:
         callback(
             JSONRPC.createErrorObject(-32006, 'not supported', 'node does not support mining', self.id)
         )
 def do_GET(self):
     if self.hasAuthorization():
         response = JSONRPC.createErrorObject(-32601, 'not found',
                                              'method not found', None)
         self.writeResponse(response, doHead=True)
     else:
         response = JSONRPC.createErrorObject(
             -32010, 'unauthorized',
             'you are not authorized to access this resource', None)
         self.writeResponse(response, doHead=False)
Beispiel #3
0
 def add(self, callback=None):
     added = False
     for address in self.contracts:
         added = Contracts.addContract(CoreContract(address))
         if not added:
             break
     if added:
         callback(JSONRPC.createResultObject('contracts added', self.id))
     else:
         callback(
             JSONRPC.createErrorObject(-32003, 'add failed',
                                       'failed to add contracts', self.id))
Beispiel #4
0
 def remove(self, callback=None):
     removed = False
     for address in self.contracts:
         removed = Contracts.removeContract(address)
         if not removed:
             break
     if removed:
         callback(JSONRPC.createResultObject('contracts removed', self.id))
     else:
         callback(
             JSONRPC.createErrorObject(-32003, 'delete failed',
                                       'failed to remove contracts',
                                       self.id))
 def remove(self, callback = None):
     removed = False
     for addr in self.address:
         removed = Accounts.removeAccount(addr)
         if not removed:
             break
     if removed:
         callback(
             JSONRPC.createResultObject('accounts removed', self.id)
         )
     else:
         callback(
             JSONRPC.createErrorObject(-32003, 'delete failed', 'failed to remove accounts', self.id)
         )
 def remove(self, callback = None):
     removed = False
     for address in self.sidechains:
         removed = Sidechains.removeSidechain(address)
         if not removed:
             break
     if removed:
         callback(
             JSONRPC.createResultObject('sidechains removed', self.id)
         )
     else:
         callback(
             JSONRPC.createErrorObject(-32003, 'delete failed', 'failed to remove sidechains', self.id)
         )
 def add(self, callback = None):
     added = False
     for address in self.sidechains:
         added = Sidechains.addSidechain(CoreSidechain(address))
         if not added:
             break
     if added:
         callback(
             JSONRPC.createResultObject('sidechains added', self.id)
         )
     else:
         callback(
             JSONRPC.createErrorObject(-32003, 'add failed', 'failed to add sidechains', self.id)
         )
Beispiel #8
0
 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)
Beispiel #9
0
    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 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 add(self, callback = None):
     account = CoreAccount()
     Accounts.addAccount(account)
     address = Address.to0xAddress(account.address)
     callback(
         JSONRPC.createResultObject(address, self.id)
     )
 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 sendAtomicSwapTx(self, callback):
     transaction = None
     if MemoryPool.addSignedTransaction(transaction):
         callback(
             JSONRPC.createResultObject(result, self.id)
         )
     else:
         self.onFailure(callback)
 def get(self, callback = None):
     sidechains = []
     for sidechain in Sidechains.getSidechains():
         address = Address.to0xAddress(sidechain.address)
         sidechains.append({
             'address': address
         })
     callback(
         JSONRPC.createResultObject(sidechains, self.id)
     )
Beispiel #15
0
 def logs(self, callback=None):
     logs = PersistentStorage.get(self.script, True)
     _logs = []
     for log in logs:
         _logs.append({
             'address': log.address,
             'data': log.data,
             'topics': log.topics
         })
     callback(JSONRPC.createResultObject(_logs, self.id))
 def createNewMultiSigAccountType(self, accountType, privateKey, callback = None):
     multiSigAddressBytes = bytearray()
     for publicKey in self.publicKeys:
         multiSigAddressBytes.extend(publicKey)
     multiSigAddress = Crypto.generateAddress(multiSigAddressBytes)
     account = CoreAccount(multiSigAddress, self.publicKeys, privateKey, accountType)
     Accounts.addAccount(account)
     multiSigAddress = Address.to0xAddress(multiSigAddress)
     callback(
         JSONRPC.createResultObject(multiSigAddress, self.id)
     )
 def signAtomicSwapTx(self, callback):
     transaction = Transaction()
     transaction.deserialize(self.unsignedTx)
     transaction.sign()
     if MemoryPool.addSignedTransaction(transaction):
         txId = transaction.hash()
         callback(
             JSONRPC.createResultObject(DataType.toHex(txId), self.id)
         )
     else:
         self.onFailure(callback)
Beispiel #18
0
 def addUnconfirmedMultiSigTransaction(self, callback=None):
     fromAccount = Accounts.getAccountByAddress(self.fromAddress)
     txId = None
     if fromAccount != None:
         txId = MemoryPool.addUnconfirmedMultiSigTransaction(
             fromAccount, self.publicKeys, self.signatures, self.toAddress,
             self.value, self.gasLimit, self.gasPrice, self.threshold)
     if txId != None:
         callback(JSONRPC.createResultObject(DataType.toHex(txId), self.id))
     else:
         self.onFailure(callback)
 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)
Beispiel #20
0
 def get(self, callback=None):
     contracts = []
     for contract in Contracts.getContracts():
         confirmedBalance = 0
         unspentTransactionScript = UXTO.getUnspentTransactionScript(
             contract.address)
         if unspentTransactionScript != None:
             txOut = unspentTransactionScript.output
             confirmedBalance = txOut.value
         confirmedBalance = Units.toValue(confirmedBalance)
         confirmedBalance = DataType.asFloat(confirmedBalance)
         address = Address.to0xAddress(contract.address)
         contracts.append({'address': address, 'balance': confirmedBalance})
     callback(JSONRPC.createResultObject(contracts, self.id))
Beispiel #21
0
 def signMultiSigOutput(self, callback=None):
     signatures = []
     multiSigAccount = Accounts.getAccountByAddress(self.fromAddress)
     if multiSigAccount != None:
         transaction = MemoryPool.createUnconfirmedMultiSigTransaction(
             multiSigAccount, self.toAddress, self.value, self.gasLimit,
             self.gasPrice, self.threshold)
         if transaction != None:
             for txIn in transaction.inputs:
                 multiSigAddress = DataType.toHex(multiSigAccount.address)
                 _publicKeys = txIn.witness[::2]
                 _signatures = txIn.witness[1::2]
                 for publicKey, signature in zip(_publicKeys, _signatures):
                     publicKey = DataType.toHex(publicKey)
                     signature = DataType.toHex(signature)
                     signatures.append({
                         'address': multiSigAddress,
                         'public': publicKey,
                         'signature': signature
                     })
     callback(JSONRPC.createResultObject(signatures, self.id))
Beispiel #22
0
 def onFailure(self, callback=None):
     callback(
         JSONRPC.createErrorObject(-32004, 'invalid message',
                                   'rejected transaction', self.id))
 def onFailure(self, callback = None):
     callback(
         JSONRPC.createErrorObject(-32000, 'invalid message', 'invalid account request', self.id)
     )
Beispiel #24
0
def handleCommand(command, parameters):
    id = 1
    commands = []
    if command == 'CreateAtomicSwapAccount':
        commands.append(JSONRPC.createMethodObject(command, parameters, id))
    elif command == 'CreateMultiSigAccount':
        commands.append(JSONRPC.createMethodObject(command, parameters, id))
    elif command == 'GetAccounts':
        commands.append(JSONRPC.createMethodObject(command, [], id))
    elif command == 'GetNewAccount':
        commands.append(JSONRPC.createMethodObject(command, [], id))
    elif command == 'DeleteAccounts':
        commands.append(JSONRPC.createMethodObject(command, parameters, id))
    elif command == 'SendTransaction':
        fromAddress = parameters[0]
        toAddress = parameters[1]
        value = DataType.asFloat(parameters[2])
        gasLimit = DataType.asInt(parameters[3])
        gasPrice = DataType.asFloat(parameters[4])
        params = {
            'fromAddress': fromAddress,
            'toAddress': toAddress,
            'value': value,
            'gasLimit': gasLimit,
            'gasPrice': gasPrice
        }
        commands.append(JSONRPC.createMethodObject(command, params, id))
    elif command == 'SendTransactionToMultiSig':
        fromAddress = parameters[0]
        threshold = DataType.asInt(parameters[1])
        toMultiSigAddress = parameters[2]
        value = DataType.asFloat(parameters[3])
        gasLimit = DataType.asInt(parameters[4])
        gasPrice = DataType.asFloat(parameters[5])
        params = {
            'fromAddress': fromAddress,
            'threshold': threshold,
            'toAddress': toMultiSigAddress,
            'value': value,
            'gasLimit': gasLimit,
            'gasPrice': gasPrice
        }
        commands.append(JSONRPC.createMethodObject(command, params, id))
    elif command == 'SendTransactionFromMultiSig':
        fromAddress = parameters[0]
        publicKeys = []
        signatures = []
        idx = 0
        for parameter in parameters[1:-5]:
            if idx % 2 == 0:
                publicKeys.append(parameter)
            else:
                signatures.append(parameter)
            idx += 1
        threshold = DataType.asInt(parameters[-5])
        toAddress = parameters[-4]
        value = DataType.asFloat(parameters[-3])
        gasLimit = DataType.asInt(parameters[-2])
        gasPrice = DataType.asFloat(parameters[-1])
        params = {
            'fromAddress': fromAddress,
            'publicKeys': publicKeys,
            'signatures': signatures,
            'threshold': threshold,
            'toAddress': toAddress,
            'value': value,
            'gasLimit': gasLimit,
            'gasPrice': gasPrice
        }
        commands.append(JSONRPC.createMethodObject(command, params, id))
    elif command == 'SignMultiSigOutput':
        multiSigAddress = parameters[0]
        threshold = DataType.asInt(parameters[1])
        toAddress = parameters[2]
        value = DataType.asFloat(parameters[3])
        gasLimit = DataType.asInt(parameters[4])
        gasPrice = DataType.asFloat(parameters[5])
        params = {
            'fromAddress': multiSigAddress,
            'threshold': threshold,
            'toAddress': toAddress,
            'value': value,
            'gasLimit': gasLimit,
            'gasPrice': gasPrice
        }
        commands.append(JSONRPC.createMethodObject(command, params, id))
    elif command == 'GetMiningWorker':
        address = parameters[0]
        enabled = DataType.asBool(parameters[1])
        params = {'address': address, 'enabled': enabled}
        commands.append(JSONRPC.createMethodObject(command, params, id))
    elif command == 'CreateAtomicSwapTx':
        fromAddress = parameters[0]
        threshold = DataType.asInt(parameters[1])
        toAddress = parameters[2]
        value = DataType.asFloat(parameters[3])
        gasLimit = DataType.asInt(parameters[4])
        gasPrice = DataType.asFloat(parameters[5])
        params = {
            'fromAddress': fromAddress,
            'threshold': threshold,
            'toAddress': toAddress,
            'value': value,
            'gasLimit': gasLimit,
            'gasPrice': gasPrice
        }
        commands.append(JSONRPC.createMethodObject(command, params, id))
    elif command == 'SendAtomicSwapTx':
        fromAddress = parameters[0]
        toAddress = parameters[1]
        value = DataType.asFloat(parameters[2])
        gasLimit = DataType.asInt(parameters[3])
        gasPrice = DataType.asFloat(parameters[4])
        params = {
            'fromAddress': fromAddress,
            'toAddress': toAddress,
            'value': value,
            'gasLimit': gasLimit,
            'gasPrice': gasPrice
        }
        commands.append(JSONRPC.createMethodObject(command, params, id))
    elif command == 'SignAtomicSwapTx':
        commands.append(JSONRPC.createMethodObject(command, parameters, id))
    elif command == 'WatchContracts':
        commands.append(JSONRPC.createMethodObject(command, parameters, id))
    elif command == 'DeleteContracts':
        commands.append(JSONRPC.createMethodObject(command, parameters, id))
    elif command == 'GetContracts':
        commands.append(JSONRPC.createMethodObject(command, [], id))
    elif command == 'GetScriptLogs':
        fromAddress = parameters[0]
        scriptAddress = parameters[1]
        value = DataType.asFloat(parameters[2])
        gasLimit = DataType.asInt(parameters[3])
        gasPrice = DataType.asFloat(parameters[4])
        params = {
            'fromAddress': fromAddress,
            'script': scriptAddress,
            'value': value,
            'gasLimit': gasLimit,
            'gasPrice': gasPrice
        }
        commands.append(JSONRPC.createMethodObject(command, params, id))
    elif command == 'DeployScript' or command == 'DeployLocalScript':
        fromAddress = parameters[0]
        with open(parameters[1], 'r') as scriptFile:
            script = scriptFile.read()
        _parameters = parameters[2:-3]
        value = DataType.asFloat(parameters[-3])
        gasLimit = DataType.asInt(parameters[-2])
        gasPrice = DataType.asFloat(parameters[-1])
        params = {
            'fromAddress': fromAddress,
            'script': script,
            'parameters': _parameters,
            'value': value,
            'gasLimit': gasLimit,
            'gasPrice': gasPrice
        }
        commands.append(JSONRPC.createMethodObject(command, params, id))
    elif command == 'CallTxScript' or command == 'CallLocalScript':
        fromAddress = parameters[0]
        scriptAddress = parameters[1]
        _parameters = parameters[2:-3]
        if _parameters and len(_parameters) > 0:
            _parameters[0] = DataType.serialize(_parameters[0])
            hashFunction = keccak.new(data=_parameters[0], digest_bits=256)
            methodHash = hashFunction.hexdigest()
            _parameters[0] = methodHash[0:8]
        value = DataType.asFloat(parameters[-3])
        gasLimit = DataType.asInt(parameters[-2])
        gasPrice = DataType.asFloat(parameters[-1])
        params = {
            'fromAddress': fromAddress,
            'script': scriptAddress,
            'parameters': _parameters,
            'value': value,
            'gasLimit': gasLimit,
            'gasPrice': gasPrice
        }
        commands.append(JSONRPC.createMethodObject(command, params, id))
    elif command == 'WatchSideChain':
        commands.append(JSONRPC.createMethodObject(command, parameters, id))
    elif command == 'DeleteSideChains':
        commands.append(JSONRPC.createMethodObject(command, parameters, id))
    elif command == 'GetSideChains':
        commands.append(JSONRPC.createMethodObject(command, [], id))
    elif command == 'DeploySideChain':
        fromAddress = parameters[0]
        parameters = parameters[1]
        value = DataType.asFloat(parameters[2])
        gasLimit = DataType.asInt(parameters[3])
        gasPrice = DataType.asFloat(parameters[4])
        params = {
            'fromAddress': fromAddress,
            'parameters': parameters,
            'value': value,
            'gasLimit': gasLimit,
            'gasPrice': gasPrice
        }
        commands.append(JSONRPC.createMethodObject(command, params, id))
    elif command == 'GetPeers':
        commands.append(JSONRPC.createMethodObject(command, [], id))
    elif command == 'AddPeers':
        commands.append(JSONRPC.createMethodObject(command, parameters, id))
    elif command == 'DeletePeers':
        commands.append(JSONRPC.createMethodObject(command, parameters, id))
    else:
        raise ValueError('Unsupported command: ' + command)

    url = '%s:%s' % (Http.getNodeHostname(), Http.getHttpPort())
    for cmd in commands:
        cmd = json.dumps(cmd)
        response = Http.send(url, cmd, doBasicAuth=True)
        if response == None or len(response) == 0:
            print('Empty response from ', url, 'request', cmd)
            continue
        response = json.loads(response)
        value = '\n'
        if 'result' in response:
            result = response['result']
            if isinstance(result, list):
                for item in result:
                    if isinstance(item, dict):
                        for v in item.values():
                            value += ('%s\t' % v)
                        value += '\n'
                    else:
                        value += item
                        value += '\n'
            else:
                value += DataType.asString(result)
                value += '\n'
        elif 'error' in response:
            error = response['error']

            code = error['code']
            message = error['message']
            data = error['data']

            value += '%s %s %s' % (code, message, data)
            value += '\n'
        print(value)
 def onFailure(self, callback = None):
     callback(
         JSONRPC.createErrorObject(-32004, 'invalid message', 'rejected atomic swap', self.id)
     )
Beispiel #26
0
 def onFailure(self, callback=None):
     callback(
         JSONRPC.createErrorObject(-32011, 'invalid message',
                                   'rejected script', self.id))