コード例 #1
0
    def setUp(self):
        self.fileA = os.path.join(ARMORY_HOME_DIR,
                                  'armory_%s_.wallet' % TEST_WALLET_ID)
        self.fileB = os.path.join(ARMORY_HOME_DIR,
                                  'armory_%s_backup.wallet' % TEST_WALLET_ID)
        self.fileAupd = os.path.join(
            ARMORY_HOME_DIR,
            'armory_%s_backup_unsuccessful.wallet' % TEST_WALLET_ID)
        self.fileBupd = os.path.join(
            ARMORY_HOME_DIR,
            'armory_%s_update_unsuccessful.wallet' % TEST_WALLET_ID)

        self.removeFileList(
            [self.fileA, self.fileB, self.fileAupd, self.fileBupd])

        # We need a controlled test, so we script the all the normally-random stuff
        self.privKey = SecureBinaryData('\xaa' * 32)
        self.privKey2 = SecureBinaryData('\x33' * 32)
        self.chainstr = SecureBinaryData('\xee' * 32)
        theIV = SecureBinaryData(hex_to_binary('77' * 16))
        self.passphrase = SecureBinaryData('A self.passphrase')
        self.passphrase2 = SecureBinaryData('A new self.passphrase')

        self.wallet = PyBtcWallet().createNewWallet(withEncrypt=False, \
                                            plainRootKey=self.privKey, \
                                            chaincode=self.chainstr,   \
                                            IV=theIV, \
                                            shortLabel=TEST_WALLET_NAME, \
                                            longLabel=TEST_WALLET_DESCRIPTION)
        self.jsonServer = Armory_Json_Rpc_Server(self.wallet)
        TheBDM.registerWallet(self.wallet)
コード例 #2
0
    def setUp(self):

        self.verifyBlockHeight()
        self.fileA = os.path.join(self.armoryHomeDir,
                                  'armory_%s_.wallet' % TEST_WALLET_ID)
        self.fileB = os.path.join(self.armoryHomeDir,
                                  'armory_%s_backup.wallet' % TEST_WALLET_ID)
        self.fileAupd = os.path.join(
            self.armoryHomeDir,
            'armory_%s_backup_unsuccessful.wallet' % TEST_WALLET_ID)
        self.fileBupd = os.path.join(
            self.armoryHomeDir,
            'armory_%s_update_unsuccessful.wallet' % TEST_WALLET_ID)

        self.removeFileList(
            [self.fileA, self.fileB, self.fileAupd, self.fileBupd])

        # We need a controlled test, so we script the all the normally-random stuff
        self.privKey = SecureBinaryData('\xaa' * 32)
        self.privKey2 = SecureBinaryData('\x33' * 32)
        self.chainstr = SecureBinaryData('\xee' * 32)
        theIV = SecureBinaryData(hex_to_binary('77' * 16))
        self.passphrase = SecureBinaryData('A self.passphrase')
        self.passphrase2 = SecureBinaryData('A new self.passphrase')

        #register a callback
        TheBDM.registerCppNotification(self.armoryDTestCallback)

        #flag to check on wallet scan status
        self.walletIsScanned = False

        #create the wallet
        self.wallet = PyBtcWallet().createNewWallet(withEncrypt=False, \
                                            plainRootKey=self.privKey, \
                                            chaincode=self.chainstr,   \
                                            IV=theIV, \
                                            shortLabel=TEST_WALLET_NAME, \
                                            longLabel=TEST_WALLET_DESCRIPTION,
                                            armoryHomeDir = self.armoryHomeDir)
        self.jsonServer = Armory_Json_Rpc_Server(self.wallet)

        #register it
        self.wallet.registerWallet()

        #wait on scan for 2 min then raise if the scan hasn't finished yet
        i = 0
        while not self.walletIsScanned:
            time.sleep(0.5)
            i += 1
            if i >= 60 * 4:
                raise RuntimeError(
                    "Timeout waiting for TheBDM to register the wallet.")
コード例 #3
0
 def setUp(self):
    self.verifyBlockHeight()
    # Load the primary file from the test net in a box
    self.fileA    = os.path.join(self.tiab.tiabDirectory, 'tiab\\armory\\armory_%s_.wallet' % TEST_WALLET_ID)
    self.wlt = PyBtcWallet().readWalletFile(self.fileA, doScanNow=True)
    self.jsonServer = Armory_Json_Rpc_Server(self.wlt)
    TheBDM.registerWallet(self.wlt)
コード例 #4
0
   def setUp(self):
      self.verifyBlockHeight()
      self.fileA    = os.path.join(self.armoryHomeDir, 'armory_%s_.wallet' % TEST_WALLET_ID)
      self.fileB    = os.path.join(self.armoryHomeDir, 'armory_%s_backup.wallet' % TEST_WALLET_ID)
      self.fileAupd = os.path.join(self.armoryHomeDir, 'armory_%s_backup_unsuccessful.wallet' % TEST_WALLET_ID)
      self.fileBupd = os.path.join(self.armoryHomeDir, 'armory_%s_update_unsuccessful.wallet' % TEST_WALLET_ID)

      self.removeFileList([self.fileA, self.fileB, self.fileAupd, self.fileBupd])
   
      # We need a controlled test, so we script the all the normally-random stuff
      self.privKey   = SecureBinaryData('\xaa'*32)
      self.privKey2  = SecureBinaryData('\x33'*32)
      self.chainstr  = SecureBinaryData('\xee'*32)
      theIV     = SecureBinaryData(hex_to_binary('77'*16))
      self.passphrase  = SecureBinaryData('A self.passphrase')
      self.passphrase2 = SecureBinaryData('A new self.passphrase')

      self.wallet = PyBtcWallet().createNewWallet(withEncrypt=False, \
                                          plainRootKey=self.privKey, \
                                          chaincode=self.chainstr,   \
                                          IV=theIV, \
                                          shortLabel=TEST_WALLET_NAME, \
                                          longLabel=TEST_WALLET_DESCRIPTION,
                                          armoryHomeDir = self.armoryHomeDir)
      self.jsonServer = Armory_Json_Rpc_Server(self.wallet)
      TheBDM.registerWallet(self.wallet)
コード例 #5
0
 def setUp(self):
     self.verifyBlockHeight()
     # Load the primary file from the test net in a box
     self.fileA = os.path.join(self.tiab.tiabDirectory, 'tiab', 'armory', \
                               'armory_%s_.wallet' % FIRST_WLT_NAME)
     self.wltA = PyBtcWallet().readWalletFile(self.fileA, doScanNow=True)
     self.fileB = os.path.join(self.tiab.tiabDirectory, 'tiab', 'armory', \
                               'armory_%s_.wallet' % SECOND_WLT_NAME)
     self.wltB = PyBtcWallet().readWalletFile(self.fileB, doScanNow=True)
     self.fileC = os.path.join(self.tiab.tiabDirectory, 'tiab', 'armory', \
                               'armory_%s_.wallet' % THIRD_WLT_NAME)
     self.wltC = PyBtcWallet().readWalletFile(self.fileC, doScanNow=True)
     self.jsonServer = Armory_Json_Rpc_Server(self.wltA, \
                                   inWltMap={SECOND_WLT_NAME : self.wltB, \
                                             THIRD_WLT_NAME : self.wltC}, \
                      armoryHomeDir=os.path.join(self.tiab.tiabDirectory, \
                                                 'tiab','armory'))
     TheBDM.registerWallet(self.wltA)
コード例 #6
0
    def setUp(self):
        self.verifyBlockHeight()
        # Load the primary file from the test net in a box
        self.fileA = os.path.join(self.tiab.tiabDirectory, 'tiab', 'armory', \
                                  'armory_%s_.wallet' % FIRST_WLT_NAME)
        self.wltA = PyBtcWallet().readWalletFile(self.fileA)
        self.fileB = os.path.join(self.tiab.tiabDirectory, 'tiab', 'armory', \
                                  'armory_%s_.wallet' % SECOND_WLT_NAME)
        self.wltB = PyBtcWallet().readWalletFile(self.fileB)
        self.fileC = os.path.join(self.tiab.tiabDirectory, 'tiab', 'armory', \
                                  'armory_%s_.wallet' % THIRD_WLT_NAME)
        self.wltC = PyBtcWallet().readWalletFile(self.fileC)
        self.jsonServer = Armory_Json_Rpc_Server(self.wltA, \
                                      inWltMap={SECOND_WLT_NAME : self.wltB, \
                                                THIRD_WLT_NAME : self.wltC}, \
                         armoryHomeDir=os.path.join(self.tiab.tiabDirectory, \
                                                    'tiab','armory'))

        self.wltIDs = [
            self.wltA.uniqueIDB58, self.wltB.uniqueIDB58, self.wltC.uniqueIDB58
        ]
        #register a callback
        TheBDM.registerCppNotification(self.armoryDTiabTestCallback)

        #flag to check on wallet scan status
        self.numberOfWalletsScanned = 0

        self.wltA.registerWallet()
        time.sleep(0.5)
        self.wltB.registerWallet()
        time.sleep(0.5)
        self.wltC.registerWallet()
        time.sleep(0.5)
        #wait on scan for 20sec then raise if the scan hasn't finished yet
        i = 0
        while self.numberOfWalletsScanned < 3:
            time.sleep(0.5)
            i += 1
            if i >= 40:
                raise RuntimeError("self.numberOfWalletsScanned = %d" %
                                   self.numberOfWalletsScanned)
コード例 #7
0
 def setUp(self):
    self.verifyBlockHeight()
    # Load the primary file from the test net in a box
    self.fileA = os.path.join(self.tiab.tiabDirectory, 'tiab', 'armory', \
                              'armory_%s_.wallet' % FIRST_WLT_NAME)
    self.wltA  = PyBtcWallet().readWalletFile(self.fileA, doScanNow=True)
    self.fileB = os.path.join(self.tiab.tiabDirectory, 'tiab', 'armory', \
                              'armory_%s_.wallet' % SECOND_WLT_NAME)
    self.wltB  = PyBtcWallet().readWalletFile(self.fileB, doScanNow=True)
    self.fileC = os.path.join(self.tiab.tiabDirectory, 'tiab', 'armory', \
                              'armory_%s_.wallet' % THIRD_WLT_NAME)
    self.wltC  = PyBtcWallet().readWalletFile(self.fileC, doScanNow=True)
    self.jsonServer = Armory_Json_Rpc_Server(self.wltA, \
                                  inWltMap={SECOND_WLT_NAME : self.wltB, \
                                            THIRD_WLT_NAME : self.wltC}, \
                     armoryHomeDir=os.path.join(self.tiab.tiabDirectory, \
                                                'tiab','armory'))
    TheBDM.registerWallet(self.wltA)
コード例 #8
0
   def setUp(self):
      
      self.verifyBlockHeight()
      self.fileA    = os.path.join(self.armoryHomeDir, 'armory_%s_.wallet' % TEST_WALLET_ID)
      self.fileB    = os.path.join(self.armoryHomeDir, 'armory_%s_backup.wallet' % TEST_WALLET_ID)
      self.fileAupd = os.path.join(self.armoryHomeDir, 'armory_%s_backup_unsuccessful.wallet' % TEST_WALLET_ID)
      self.fileBupd = os.path.join(self.armoryHomeDir, 'armory_%s_update_unsuccessful.wallet' % TEST_WALLET_ID)

      self.removeFileList([self.fileA, self.fileB, self.fileAupd, self.fileBupd])
   
      # We need a controlled test, so we script the all the normally-random stuff
      self.privKey   = SecureBinaryData('\xaa'*32)
      self.privKey2  = SecureBinaryData('\x33'*32)
      self.chainstr  = SecureBinaryData('\xee'*32)
      theIV     = SecureBinaryData(hex_to_binary('77'*16))
      self.passphrase  = SecureBinaryData('A self.passphrase')
      self.passphrase2 = SecureBinaryData('A new self.passphrase')
      
      #register a callback
      TheBDM.registerCppNotification(self.armoryDTestCallback)

      #flag to check on wallet scan status
      self.walletIsScanned = False
      
      #create the wallet
      self.wallet = PyBtcWallet().createNewWallet(withEncrypt=False, \
                                          plainRootKey=self.privKey, \
                                          chaincode=self.chainstr,   \
                                          IV=theIV, \
                                          shortLabel=TEST_WALLET_NAME, \
                                          longLabel=TEST_WALLET_DESCRIPTION,
                                          armoryHomeDir = self.armoryHomeDir)
      self.jsonServer = Armory_Json_Rpc_Server(self.wallet)
      
      #register it
      self.wallet.registerWallet()
      
      #wait on scan for 2 min then raise if the scan hasn't finished yet
      i = 0
      while not self.walletIsScanned:
         time.sleep(0.5)
         i += 1
         if i >= 60*4:
            raise RuntimeError("Timeout waiting for TheBDM to register the wallet.")
コード例 #9
0
   def setUp(self):
      self.verifyBlockHeight()
      # Load the primary file from the test net in a box
      self.fileA = os.path.join(self.tiab.tiabDirectory, 'tiab', 'armory', \
                                'armory_%s_.wallet' % FIRST_WLT_NAME)
      self.wltA  = PyBtcWallet().readWalletFile(self.fileA)
      self.fileB = os.path.join(self.tiab.tiabDirectory, 'tiab', 'armory', \
                                'armory_%s_.wallet' % SECOND_WLT_NAME)
      self.wltB  = PyBtcWallet().readWalletFile(self.fileB)
      self.fileC = os.path.join(self.tiab.tiabDirectory, 'tiab', 'armory', \
                                'armory_%s_.wallet' % THIRD_WLT_NAME)
      self.wltC  = PyBtcWallet().readWalletFile(self.fileC)
      self.jsonServer = Armory_Json_Rpc_Server(self.wltA, \
                                    inWltMap={SECOND_WLT_NAME : self.wltB, \
                                              THIRD_WLT_NAME : self.wltC}, \
                       armoryHomeDir=os.path.join(self.tiab.tiabDirectory, \
                                                  'tiab','armory'))
      
      self.wltIDs = [self.wltA.uniqueIDB58, self.wltB.uniqueIDB58, self.wltC.uniqueIDB58]
      #register a callback
      TheBDM.registerCppNotification(self.armoryDTiabTestCallback)

      #flag to check on wallet scan status
      self.numberOfWalletsScanned = 0
      
      self.wltA.registerWallet()
      time.sleep(0.5)
      self.wltB.registerWallet()
      time.sleep(0.5)
      self.wltC.registerWallet()
      time.sleep(0.5)
      #wait on scan for 20sec then raise if the scan hasn't finished yet
      i = 0
      while self.numberOfWalletsScanned < 3:
         time.sleep(0.5)
         i += 1
         if i >= 40:
            raise RuntimeError("self.numberOfWalletsScanned = %d" % self.numberOfWalletsScanned)
コード例 #10
0
class ArmoryDTest(TiabTest):      
   def removeFileList(self, fileList):
      for f in fileList:
         if os.path.exists(f):
            os.remove(f)
      
   def armoryDTestCallback(self, action, args):
      if action == REFRESH_ACTION:
         self.walletIsScanned = True
         
   def setUp(self):
      
      self.verifyBlockHeight()
      self.fileA    = os.path.join(self.armoryHomeDir, 'armory_%s_.wallet' % TEST_WALLET_ID)
      self.fileB    = os.path.join(self.armoryHomeDir, 'armory_%s_backup.wallet' % TEST_WALLET_ID)
      self.fileAupd = os.path.join(self.armoryHomeDir, 'armory_%s_backup_unsuccessful.wallet' % TEST_WALLET_ID)
      self.fileBupd = os.path.join(self.armoryHomeDir, 'armory_%s_update_unsuccessful.wallet' % TEST_WALLET_ID)

      self.removeFileList([self.fileA, self.fileB, self.fileAupd, self.fileBupd])
   
      # We need a controlled test, so we script the all the normally-random stuff
      self.privKey   = SecureBinaryData('\xaa'*32)
      self.privKey2  = SecureBinaryData('\x33'*32)
      self.chainstr  = SecureBinaryData('\xee'*32)
      theIV     = SecureBinaryData(hex_to_binary('77'*16))
      self.passphrase  = SecureBinaryData('A self.passphrase')
      self.passphrase2 = SecureBinaryData('A new self.passphrase')
      
      #register a callback
      TheBDM.registerCppNotification(self.armoryDTestCallback)

      #flag to check on wallet scan status
      self.walletIsScanned = False
      
      #create the wallet
      self.wallet = PyBtcWallet().createNewWallet(withEncrypt=False, \
                                          plainRootKey=self.privKey, \
                                          chaincode=self.chainstr,   \
                                          IV=theIV, \
                                          shortLabel=TEST_WALLET_NAME, \
                                          longLabel=TEST_WALLET_DESCRIPTION,
                                          armoryHomeDir = self.armoryHomeDir)
      self.jsonServer = Armory_Json_Rpc_Server(self.wallet)
      
      #register it
      self.wallet.registerWallet()
      
      #wait on scan for 2 min then raise if the scan hasn't finished yet
      i = 0
      while not self.walletIsScanned:
         time.sleep(0.5)
         i += 1
         if i >= 60*4:
            raise RuntimeError("Timeout waiting for TheBDM to register the wallet.")
      
   def tearDown(self):
      TheBDM.unregisterCppNotification(self.armoryDTestCallback)
      self.wallet.unregisterWallet()
      self.removeFileList([self.fileA, self.fileB, self.fileAupd, self.fileBupd])
   

   # Can't test with actual transactions in this environment. See ARMORY-34.
   # This wallet has no txs
   # def testListunspent(self):
   #    actualResult = self.jsonServer.jsonrpc_listunspent()
   #    self.assertEqual(actualResult, [])
   def testImportprivkey(self):
      originalLength = len(self.wallet.linearAddr160List)
      self.jsonServer.jsonrpc_importprivkey(binary_to_hex(self.privKey2.toBinStr()))
      self.assertEqual(len(self.wallet.linearAddr160List), originalLength+1)

   def testGettxout(self):
      txOut = self.jsonServer.jsonrpc_gettxout(TX_ID1, 0)
      self.assertEquals(txOut['value'],TX_ID1_OUTPUT0_VALUE)
      txOut = self.jsonServer.jsonrpc_gettxout(TX_ID1, 1)
      self.assertEquals(txOut['value'],TX_ID1_OUTPUT1_VALUE)
         
   def testGetreceivedbyaddress(self):
      a160 = hash160(self.wallet.getNextUnusedAddress().binPublicKey65.toBinStr())
      testAddr = hash160_to_addrStr(a160)
      result = self.jsonServer.jsonrpc_getreceivedbyaddress(testAddr)
      self.assertEqual(result, 0)
      
   def testGetrawtransaction(self):
      actualRawTx = self.jsonServer.jsonrpc_getrawtransaction(TX_ID1)
      pyTx = PyTx().unserialize(hex_to_binary(actualRawTx))
      self.assertEquals(TX_ID1, binary_to_hex(pyTx.getHash(), BIGENDIAN))

   def testBackupWallet(self):
      backupTestPath = os.path.join(self.armoryHomeDir, 'armory_%s_.wallet.backup.test' % TEST_WALLET_ID)
      # Remove backupTestPath in case it exists
      backupFileList = [backupTestPath, self.fileB]
      self.removeFileList(backupFileList)
      # Remove the backup test path that is to be created after tear down.
      self.addCleanup(self.removeFileList, backupFileList)
      self.jsonServer.jsonrpc_backupwallet(backupTestPath)
      self.assertTrue(os.path.exists(backupTestPath))
      self.wallet.backupWalletFile()
      self.assertTrue(os.path.exists(self.fileB))
      
   def testDecoderawtransaction(self):
      actualDD = self.jsonServer.jsonrpc_decoderawtransaction(RAW_TX1)
      # Test specific values pulled from bitcoin daemon's output for the test raw TX
      expectScriptStr = 'OP_DUP OP_HASH160 PUSHDATA(20) [62d978319c7d7ac6cceed722c3d08aa81b371012] OP_EQUALVERIFY OP_CHECKSIG'
      self.assertEqual(actualDD['locktime'], 0)
      self.assertEqual(actualDD['version'], 1)
      self.assertEqual(len(actualDD['vin']), 1)
      self.assertEqual(actualDD['vin'][0]['sequence'], 4294967295L)
      self.assertEqual(actualDD['vin'][0]['scriptSig']['hex'], '4830450220081341a4e803c7c8e64c3a3fd285dca34c9f7c71c4dfc2b576d761c5783ce735022100eea66ba382d00e628d86fc5bc1928a93765e26fd8252c4d01efe22147c12b91a01410458fec9d580b0c6842cae00aecd96e89af3ff56f5be49dae425046e64057e0f499acc35ec10e1b544e0f01072296c6fa60a68ea515e59d24ff794cf8923cd30f4')
      self.assertEqual(actualDD['vin'][0]['vout'], 1)
      self.assertEqual(actualDD['vin'][0]['txid'], '04b865ecf5fca3a56f6ce73a571a09a668f4b7aa5a7547a5f51fae08eadcdbb5')
      self.assertEqual(len(actualDD['vout']), 2)
      self.assertEqual(actualDD['vout'][0]['value'], 20.0)
      self.assertEqual(actualDD['vout'][0]['n'], 0)
      self.assertEqual(actualDD['vout'][0]['scriptPubKey']['reqSigs'], 1)
      self.assertEqual(actualDD['vout'][0]['scriptPubKey']['hex'], '76a91462d978319c7d7ac6cceed722c3d08aa81b37101288ac')
      self.assertEqual(actualDD['vout'][0]['scriptPubKey']['addresses'], ['mpXd2u8fPVYdL1Nf9bZ4EFnqhkNyghGLxL'])
      self.assertEqual(actualDD['vout'][0]['scriptPubKey']['asm'], expectScriptStr)
      self.assertEqual(actualDD['vout'][0]['scriptPubKey']['type'], 'Standard (PKH)')
      self.assertEqual(actualDD['vout'][1]['scriptPubKey']['type'], 'Standard (PKH)')

   def testDumpprivkey(self):
      testPrivKey = self.privKey.toBinStr()
      hash160 = convertKeyDataToAddress(testPrivKey)
      addr58 = hash160_to_addrStr(hash160)
      
      # Verify that a bogus addrss Raises InvalidBitcoinAddress Exception
      result =  self.jsonServer.jsonrpc_dumpprivkey('bogus', 'hex')
      self.assertEqual(result['Error Type'],'InvalidBitcoinAddress')

      result =  self.jsonServer.jsonrpc_dumpprivkey(addr58, 'hex')
      self.assertEqual(result['Error Type'],'PrivateKeyNotFound')

      # verify that the first private key can be found
      firstHash160 = self.wallet.getNextUnusedAddress().getAddr160()
      firstAddr58 = hash160_to_addrStr(firstHash160)
      actualPrivateKeyHex = self.jsonServer.jsonrpc_dumpprivkey(firstAddr58, \
                                                                'hex')
      actualPrivateKeyB58 = self.jsonServer.jsonrpc_dumpprivkey(firstAddr58, \
                                                                'base58')
      self.privKey = self.wallet.getAddrByHash160(firstHash160).serializePlainPrivateKey()
      expectedPrivateKeyHex = binary_to_hex(self.privKey)
      expectedPrivateKeyB58 = privKey_to_base58(self.privKey)
      self.assertEqual(actualPrivateKeyHex, expectedPrivateKeyHex)
      self.assertEqual(actualPrivateKeyB58, expectedPrivateKeyB58)

      # Verify that a locked wallet Raises WalletUnlockNeeded Exception
      kdfParams = self.wallet.computeSystemSpecificKdfParams(0.1)
      self.wallet.changeKdfParams(*kdfParams)
      self.wallet.changeWalletEncryption( securePassphrase=self.passphrase )
      self.wallet.lock()
      result = self.jsonServer.jsonrpc_dumpprivkey(addr58, 'hex')
      self.assertEqual(result['Error Type'],'WalletUnlockNeeded')
      
   def testEncryptwallet(self):
      kdfParams = self.wallet.computeSystemSpecificKdfParams(0.1)
      self.wallet.changeKdfParams(*kdfParams)
      self.jsonServer.jsonrpc_encryptwallet(PASSPHRASE1)
      self.assertTrue(self.wallet.isLocked)
      
      # Verify that a locked wallet Raises WalletUnlockNeeded Exception
      # self.assertRaises(WalletUnlockNeeded, self.jsonServer.jsonrpc_encryptwallet, PASSPHRASE1)
      result = self.jsonServer.jsonrpc_encryptwallet(PASSPHRASE1)
      print result
      
   def testUnlockwallet(self):
      kdfParams = self.wallet.computeSystemSpecificKdfParams(0.1)
      self.wallet.changeKdfParams(*kdfParams)
      self.jsonServer.jsonrpc_encryptwallet(PASSPHRASE1)
      self.assertTrue(self.wallet.isLocked)
      self.jsonServer.jsonrpc_walletpassphrase(PASSPHRASE1, UNLOCK_TIMEOUT)
      self.assertFalse(self.wallet.isLocked)
      time.sleep(UNLOCK_TIMEOUT+1)
      self.wallet.checkWalletLockTimeout()
      self.assertTrue(self.wallet.isLocked)
      
   def testGetWalletInfo(self):
      wltInfo = self.jsonServer.jsonrpc_getwalletinfo()
      self.assertEqual(wltInfo['name'], TEST_WALLET_NAME)
      self.assertEqual(wltInfo['description'], TEST_WALLET_DESCRIPTION)
      self.assertEqual(wltInfo['balance'], AmountToJSON(self.wallet.getBalance('Spend')))
      self.assertEqual(wltInfo['keypoolsize'], self.wallet.addrPoolSize)
      self.assertEqual(wltInfo['numaddrgen'], len(self.wallet.addrMap))
      self.assertEqual(wltInfo['highestusedindex'], self.wallet.highestUsedChainIndex)
   
   # This should always return 0 balance
   # Need to create our own test net to test with balances
   def testGetBalance(self):
      for ballanceType in ['spendable','spend', 'unconf', \
                           'unconfirmed', 'total', 'ultimate','unspent', 'full']:
         self.assertEqual(self.jsonServer.jsonrpc_getbalance(ballanceType),
                          AmountToJSON(self.wallet.getBalance(ballanceType)))
コード例 #11
0
class ArmoryDTiabTest(TiabTest):
   
   def setUp(self):
      self.verifyBlockHeight()
      # Load the primary file from the test net in a box
      self.fileA    = os.path.join(self.tiab.tiabDirectory, 'tiab\\armory\\armory_%s_.wallet' % TEST_WALLET_ID)
      self.wlt = PyBtcWallet().readWalletFile(self.fileA, doScanNow=True)
      self.jsonServer = Armory_Json_Rpc_Server(self.wlt)
      TheBDM.registerWallet(self.wlt)
   
   def  testReceivedfromaddress(self):
      result = self.jsonServer.jsonrpc_receivedfromaddress(TIAB_WLT_3_ADDR_3)
      self.assertEqual(result, 6)
      result = self.jsonServer.jsonrpc_receivedfromaddress(TIAB_WLT_1_ADDR_3)
      self.assertEqual(result, 0)
   
   def testGettransaction(self):
      tx = self.jsonServer.jsonrpc_gettransaction('db0ee46beff3a61f38bfc563f92c11449ed57c3d7d5cd5aafbe0114e5a9ceee4')
      self.assertEqual(tx, {'category': 'send', 'inputs': [{'fromtxid': '04b865ecf5fca3a56f6ce73a571a09a668f4b7aa5a7547a5f51fae08eadcdbb5',
                            'ismine': True, 'fromtxindex': 1, 'value': 1000.0, 'address': 'mtZ2d1jFZ9YNp3Ku5Fb2u8Tfu3RgimBHAD'}],
                            'direction': 'send', 'fee': 0.0001, 'totalinputs': 1000.0, 'outputs':
                             [{'address': 'mpXd2u8fPVYdL1Nf9bZ4EFnqhkNyghGLxL', 'value': 20.0, 'ismine': False},
                              {'address': 'mgLjhTCUtbeLPP9fDkBnG8oztWgJaXZQjn', 'value': 979.9999, 'ismine': True}],
                            'txid': 'db0ee46beff3a61f38bfc563f92c11449ed57c3d7d5cd5aafbe0114e5a9ceee4', 'confirmations': 10,
                            'orderinblock': 1, 'mainbranch': True, 'numtxin': 1, 'time': 3947917907L, 'numtxout': 2,
                            'netdiff': -20.0001, 'infomissing': False})
   
   def testGetblock(self):
      block = self.jsonServer.jsonrpc_getblock('0000000064a1ad1f15981a713a6ef08fd98f69854c781dc7b8789cc5f678e01f')
      # This method is broken in a couple ways.
      # For no just verify that raw transaction is correct
      self.assertEqual(block['rawheader'], '02000000d8778a50d43d3e02c4c20bdd0ed97077a3c4bef3e86ce58975f6f43a00000000d25912cfc67228748494d421512c7a6cc31668fa82b72265261558802a89f4c2e0350153ffff001d10bcc285',)
      
   def testGetinfo(self):
      info = self.jsonServer.jsonrpc_getinfo()
      self.assertEqual(info, {'blocks': 247, 'bdmstate': 'BlockchainReady', 'walletversion': 13500000,
                    'difficulty': 1.0, 'proxy': '', 'connections': 0, 'testnet': True, 'version': 9199002,
                    'protocolversion': 0, 'balance': EXPECTED_TIAB_BALANCE, 'keypoolsize': 10})
   
   def testListtransactions(self):
      txList = self.jsonServer.jsonrpc_listtransactions(100)
      self.assertTrue(len(txList)>10)
      self.assertEqual(txList[0], {'blockhash': '0000000064a1ad1f15981a713a6ef08fd98f69854c781dc7b8789cc5f678e01f',
                  'blockindex': 1, 'confirmations': 31, 'address': 'mtZ2d1jFZ9YNp3Ku5Fb2u8Tfu3RgimBHAD',
                  'category': 'receive', 'account': '',
                  'txid': '04b865ecf5fca3a56f6ce73a571a09a668f4b7aa5a7547a5f51fae08eadcdbb5',
                  'blocktime': 1392588256, 'amount': 1000.0, 'timereceived': 1392588256, 'time': 1392588256})
            
      
   def testGetledgersimple(self):
      ledger = self.jsonServer.jsonrpc_getledgersimple()
      self.assertTrue(len(ledger)>4)
      amountList = [row['amount'] for row in ledger]
      expectedAmountList = [1000.0, 20.0, 30.0, 0.8, 10.0]
      self.assertEqual(amountList[:5], expectedAmountList)
      
      
   def testGetledger(self):
      ledger = self.jsonServer.jsonrpc_getledger()
      self.assertTrue(len(ledger)>6)
      amountList = [row['amount'] for row in ledger]
      expectedAmountList = [1000.0, 20.0, 30.0, 0.8, 10.0, 6.0, 20.0]
      self.assertEqual(amountList, expectedAmountList)
      self.assertEqual(ledger[0]['direction'], 'receive')
      self.assertEqual(len(ledger[0]['recipme']), 1)
      self.assertEqual(ledger[0]['recipme'][0]['amount'], 1000.0)
      self.assertEqual(len(ledger[0]['recipother']), 1)
      self.assertEqual(ledger[0]['recipother'][0]['amount'], 49.997)
      self.assertEqual(len(ledger[0]['senderme']), 0)
      self.assertEqual(len(ledger[0]['senderother']), 21)
 
      self.assertEqual(ledger[1]['direction'], 'send')
      self.assertEqual(len(ledger[1]['senderother']), 0)
      self.assertEqual(len(ledger[1]['senderme']), 1)
      self.assertEqual(ledger[1]['senderme'][0]['amount'], 1000.0)
      
   def testSendtoaddress(self):
      # Send 1 BTC 
      serializedUnsignedTx = self.jsonServer.jsonrpc_sendtoaddress(TIAB_WLT_3_ADDR_3, BTC_TO_SEND)
      unsignedTx = UnsignedTransaction().unserializeAscii(serializedUnsignedTx)
      # Should have 2 txouts to TIAB_WLT_3_ADDR_3 and the change
      self.assertEqual(len(unsignedTx.decorTxOuts), 2)
      foundTxOut = False
      for txout in unsignedTx.decorTxOuts:
         if script_to_addrStr(txout.binScript) == TIAB_WLT_3_ADDR_3:
            self.assertEqual(txout.value, JSONtoAmount(BTC_TO_SEND))
            foundTxOut = True
      self.assertTrue(foundTxOut)

   def testSendmany(self):
      # Send 1 BTC 
      serializedUnsignedTx = self.jsonServer.jsonrpc_sendmany(':'.join([TIAB_WLT_3_ADDR_2, str(BTC_TO_SEND)]),
                                                              ':'.join([TIAB_WLT_3_ADDR_3, str(BTC_TO_SEND)]))
      unsignedTx = UnsignedTransaction().unserializeAscii(serializedUnsignedTx)
      # Should have 2 txouts to TIAB_WLT_3_ADDR_3 and the change
      self.assertEqual(len(unsignedTx.decorTxOuts), 3)
      txOutsFound = 0
      for txout in unsignedTx.decorTxOuts:
         if script_to_addrStr(txout.binScript) in [TIAB_WLT_3_ADDR_2, TIAB_WLT_3_ADDR_3]:
            self.assertEqual(txout.value, JSONtoAmount(BTC_TO_SEND))
            txOutsFound += 1
      self.assertEqual(txOutsFound, 2)

   def testListunspent(self):
      actualResult = self.jsonServer.jsonrpc_listunspent()
      self.assertEqual(len(actualResult), 5)
      self.assertEqual(binary_to_hex(actualResult[0]), EXPECTED_UNSPENT_TX)
      
   
   def testGetNewAddress(self):
      actualResult = self.jsonServer.jsonrpc_getnewaddress()
      self.assertEqual(actualResult, EXPECTED_TIAB_NEXT_ADDR)
      
   def testGetBalance(self):
      ballances = {'spendable' : EXPECTED_TIAB_BALANCE, \
                   'spend' : EXPECTED_TIAB_BALANCE, \
                   'unconf' : 0, \
                   'unconfirmed' :  0, \
                   'total' : EXPECTED_TIAB_BALANCE, \
                   'ultimate'  :  EXPECTED_TIAB_BALANCE, \
                   'unspent' :  EXPECTED_TIAB_BALANCE, \
                   'full' :  EXPECTED_TIAB_BALANCE}
      for ballanceType in ballances.keys():
         result = self.jsonServer.jsonrpc_getbalance(ballanceType)
         self.assertEqual(result,
                          AmountToJSON(self.wlt.getBalance(ballanceType)))
      self.assertEqual(self.jsonServer.jsonrpc_getbalance('bogus'), -1)
コード例 #12
0
class ArmoryDTest(TiabTest):
    def removeFileList(self, fileList):
        for f in fileList:
            if os.path.exists(f):
                os.remove(f)

    def armoryDTestCallback(self, action, args):
        if action == REFRESH_ACTION:
            self.walletIsScanned = True

    def setUp(self):

        self.verifyBlockHeight()
        self.fileA = os.path.join(self.armoryHomeDir,
                                  'armory_%s_.wallet' % TEST_WALLET_ID)
        self.fileB = os.path.join(self.armoryHomeDir,
                                  'armory_%s_backup.wallet' % TEST_WALLET_ID)
        self.fileAupd = os.path.join(
            self.armoryHomeDir,
            'armory_%s_backup_unsuccessful.wallet' % TEST_WALLET_ID)
        self.fileBupd = os.path.join(
            self.armoryHomeDir,
            'armory_%s_update_unsuccessful.wallet' % TEST_WALLET_ID)

        self.removeFileList(
            [self.fileA, self.fileB, self.fileAupd, self.fileBupd])

        # We need a controlled test, so we script the all the normally-random stuff
        self.privKey = SecureBinaryData('\xaa' * 32)
        self.privKey2 = SecureBinaryData('\x33' * 32)
        self.chainstr = SecureBinaryData('\xee' * 32)
        theIV = SecureBinaryData(hex_to_binary('77' * 16))
        self.passphrase = SecureBinaryData('A self.passphrase')
        self.passphrase2 = SecureBinaryData('A new self.passphrase')

        #register a callback
        TheBDM.registerCppNotification(self.armoryDTestCallback)

        #flag to check on wallet scan status
        self.walletIsScanned = False

        #create the wallet
        self.wallet = PyBtcWallet().createNewWallet(withEncrypt=False, \
                                            plainRootKey=self.privKey, \
                                            chaincode=self.chainstr,   \
                                            IV=theIV, \
                                            shortLabel=TEST_WALLET_NAME, \
                                            longLabel=TEST_WALLET_DESCRIPTION,
                                            armoryHomeDir = self.armoryHomeDir)
        self.jsonServer = Armory_Json_Rpc_Server(self.wallet)

        #register it
        self.wallet.registerWallet()

        #wait on scan for 2 min then raise if the scan hasn't finished yet
        i = 0
        while not self.walletIsScanned:
            time.sleep(0.5)
            i += 1
            if i >= 60 * 4:
                raise RuntimeError(
                    "Timeout waiting for TheBDM to register the wallet.")

    def tearDown(self):
        TheBDM.unregisterCppNotification(self.armoryDTestCallback)
        self.wallet.unregisterWallet()
        self.removeFileList(
            [self.fileA, self.fileB, self.fileAupd, self.fileBupd])

    # Can't test with actual transactions in this environment. See ARMORY-34.
    # This wallet has no txs
    # def testListunspent(self):
    #    actualResult = self.jsonServer.jsonrpc_listunspent()
    #    self.assertEqual(actualResult, [])
    def testImportprivkey(self):
        originalLength = len(self.wallet.linearAddr160List)
        self.jsonServer.jsonrpc_importprivkey(
            binary_to_hex(self.privKey2.toBinStr()))
        self.assertEqual(len(self.wallet.linearAddr160List),
                         originalLength + 1)

    # Requires Supernode
    @SkipTest
    def testGettxout(self):
        txOut = self.jsonServer.jsonrpc_gettxout(TX_ID1, 0)
        self.assertEquals(txOut['value'], TX_ID1_OUTPUT0_VALUE)
        txOut = self.jsonServer.jsonrpc_gettxout(TX_ID1, 1)
        self.assertEquals(txOut['value'], TX_ID1_OUTPUT1_VALUE)

    def testGetreceivedbyaddress(self):
        a160 = hash160(
            self.wallet.getNextUnusedAddress().binPublicKey65.toBinStr())
        testAddr = hash160_to_addrStr(a160)
        result = self.jsonServer.jsonrpc_getreceivedbyaddress(testAddr)
        self.assertEqual(result, 0)

    # Requires Supernode
    @SkipTest
    def testGetrawtransaction(self):
        actualRawTx = self.jsonServer.jsonrpc_getrawtransaction(TX_ID1)
        pyTx = PyTx().unserialize(hex_to_binary(actualRawTx))
        self.assertEquals(TX_ID1, binary_to_hex(pyTx.getHash(), BIGENDIAN))

    def testBackupWallet(self):
        backupTestPath = os.path.join(
            self.armoryHomeDir,
            'armory_%s_.wallet.backup.test' % TEST_WALLET_ID)
        # Remove backupTestPath in case it exists
        backupFileList = [backupTestPath, self.fileB]
        self.removeFileList(backupFileList)
        # Remove the backup test path that is to be created after tear down.
        self.addCleanup(self.removeFileList, backupFileList)
        self.jsonServer.jsonrpc_backupwallet(backupTestPath)
        self.assertTrue(os.path.exists(backupTestPath))
        self.wallet.backupWalletFile()
        self.assertTrue(os.path.exists(self.fileB))

    def testDecoderawtransaction(self):
        actualDD = self.jsonServer.jsonrpc_decoderawtransaction(RAW_TX1)
        # Test specific values pulled from bitcoin daemon's output for the test raw TX
        expectScriptStr = 'OP_DUP OP_HASH160 PUSHDATA(20) [62d978319c7d7ac6cceed722c3d08aa81b371012] OP_EQUALVERIFY OP_CHECKSIG'
        self.assertEqual(actualDD['locktime'], 0)
        self.assertEqual(actualDD['version'], 1)
        self.assertEqual(len(actualDD['vin']), 1)
        self.assertEqual(actualDD['vin'][0]['sequence'], 4294967295L)
        self.assertEqual(
            actualDD['vin'][0]['scriptSig']['hex'],
            '4830450220081341a4e803c7c8e64c3a3fd285dca34c9f7c71c4dfc2b576d761c5783ce735022100eea66ba382d00e628d86fc5bc1928a93765e26fd8252c4d01efe22147c12b91a01410458fec9d580b0c6842cae00aecd96e89af3ff56f5be49dae425046e64057e0f499acc35ec10e1b544e0f01072296c6fa60a68ea515e59d24ff794cf8923cd30f4'
        )
        self.assertEqual(actualDD['vin'][0]['vout'], 1)
        self.assertEqual(
            actualDD['vin'][0]['txid'],
            '04b865ecf5fca3a56f6ce73a571a09a668f4b7aa5a7547a5f51fae08eadcdbb5')
        self.assertEqual(len(actualDD['vout']), 2)
        self.assertEqual(actualDD['vout'][0]['value'], 20.0)
        self.assertEqual(actualDD['vout'][0]['n'], 0)
        self.assertEqual(actualDD['vout'][0]['scriptPubKey']['reqSigs'], 1)
        self.assertEqual(actualDD['vout'][0]['scriptPubKey']['hex'],
                         '76a91462d978319c7d7ac6cceed722c3d08aa81b37101288ac')
        self.assertEqual(actualDD['vout'][0]['scriptPubKey']['addresses'],
                         ['mpXd2u8fPVYdL1Nf9bZ4EFnqhkNyghGLxL'])
        self.assertEqual(actualDD['vout'][0]['scriptPubKey']['asm'],
                         expectScriptStr)
        self.assertEqual(actualDD['vout'][0]['scriptPubKey']['type'],
                         'Standard (PKH)')
        self.assertEqual(actualDD['vout'][1]['scriptPubKey']['type'],
                         'Standard (PKH)')

    def testDumpprivkey(self):
        testPrivKey = self.privKey.toBinStr()
        hash160 = convertKeyDataToAddress(testPrivKey)
        addr58 = hash160_to_addrStr(hash160)

        # Verify that a bogus addrss Raises InvalidBitcoinAddress Exception
        result = self.jsonServer.jsonrpc_dumpprivkey('bogus', 'hex')
        self.assertEqual(result['Error Type'], 'InvalidBitcoinAddress')

        result = self.jsonServer.jsonrpc_dumpprivkey(addr58, 'hex')
        self.assertEqual(result['Error Type'], 'PrivateKeyNotFound')

        # verify that the first private key can be found
        firstHash160 = self.wallet.getNextUnusedAddress().getAddr160()
        firstAddr58 = hash160_to_addrStr(firstHash160)
        actualPrivateKeyHex = self.jsonServer.jsonrpc_dumpprivkey(firstAddr58, \
                                                                  'hex')
        actualPrivateKeyB58 = self.jsonServer.jsonrpc_dumpprivkey(firstAddr58, \
                                                                  'base58')
        self.privKey = self.wallet.getAddrByHash160(
            firstHash160).serializePlainPrivateKey()
        expectedPrivateKeyHex = binary_to_hex(self.privKey)
        expectedPrivateKeyB58 = privKey_to_base58(self.privKey)
        self.assertEqual(actualPrivateKeyHex, expectedPrivateKeyHex)
        self.assertEqual(actualPrivateKeyB58, expectedPrivateKeyB58)

        # Verify that a locked wallet Raises WalletUnlockNeeded Exception
        kdfParams = self.wallet.computeSystemSpecificKdfParams(0.1)
        self.wallet.changeKdfParams(*kdfParams)
        self.wallet.changeWalletEncryption(securePassphrase=self.passphrase)
        self.wallet.lock()
        result = self.jsonServer.jsonrpc_dumpprivkey(addr58, 'hex')
        self.assertEqual(result['Error Type'], 'WalletUnlockNeeded')

    def testEncryptwallet(self):
        kdfParams = self.wallet.computeSystemSpecificKdfParams(0.1)
        self.wallet.changeKdfParams(*kdfParams)
        self.jsonServer.jsonrpc_encryptwallet(PASSPHRASE1)
        self.assertTrue(self.wallet.isLocked)

        # Verify that a locked wallet Raises WalletUnlockNeeded Exception
        # self.assertRaises(WalletUnlockNeeded, self.jsonServer.jsonrpc_encryptwallet, PASSPHRASE1)
        result = self.jsonServer.jsonrpc_encryptwallet(PASSPHRASE1)
        print result

    def testUnlockwallet(self):
        kdfParams = self.wallet.computeSystemSpecificKdfParams(0.1)
        self.wallet.changeKdfParams(*kdfParams)
        self.jsonServer.jsonrpc_encryptwallet(PASSPHRASE1)
        self.assertTrue(self.wallet.isLocked)
        self.jsonServer.jsonrpc_walletpassphrase(PASSPHRASE1, UNLOCK_TIMEOUT)
        self.assertFalse(self.wallet.isLocked)
        time.sleep(UNLOCK_TIMEOUT + 1)
        self.wallet.checkWalletLockTimeout()
        self.assertTrue(self.wallet.isLocked)

    def testGetWalletInfo(self):
        wltInfo = self.jsonServer.jsonrpc_getwalletinfo()
        self.assertEqual(wltInfo['name'], TEST_WALLET_NAME)
        self.assertEqual(wltInfo['description'], TEST_WALLET_DESCRIPTION)
        self.assertEqual(wltInfo['balance'],
                         AmountToJSON(self.wallet.getBalance('Spend')))
        self.assertEqual(wltInfo['keypoolsize'], self.wallet.addrPoolSize)
        self.assertEqual(wltInfo['numaddrgen'], len(self.wallet.addrMap))
        self.assertEqual(wltInfo['highestusedindex'],
                         self.wallet.highestUsedChainIndex)

    # This should always return 0 balance
    # Need to create our own test net to test with balances
    def testGetBalance(self):
        for ballanceType in ['spendable','spend', 'unconf', \
                             'unconfirmed', 'total', 'ultimate','unspent', 'full']:
            self.assertEqual(
                self.jsonServer.jsonrpc_getbalance(ballanceType),
                AmountToJSON(self.wallet.getBalance(ballanceType)))
コード例 #13
0
class ArmoryDTiabTest(TiabTest):
         
   def armoryDTiabTestCallback(self, action, args):
      if action == REFRESH_ACTION:
         for wltID in args:
            print wltID
            if wltID in self.wltIDs:
               self.numberOfWalletsScanned += 1
         
   def setUp(self):
      self.verifyBlockHeight()
      # Load the primary file from the test net in a box
      self.fileA = os.path.join(self.tiab.tiabDirectory, 'tiab', 'armory', \
                                'armory_%s_.wallet' % FIRST_WLT_NAME)
      self.wltA  = PyBtcWallet().readWalletFile(self.fileA)
      self.fileB = os.path.join(self.tiab.tiabDirectory, 'tiab', 'armory', \
                                'armory_%s_.wallet' % SECOND_WLT_NAME)
      self.wltB  = PyBtcWallet().readWalletFile(self.fileB)
      self.fileC = os.path.join(self.tiab.tiabDirectory, 'tiab', 'armory', \
                                'armory_%s_.wallet' % THIRD_WLT_NAME)
      self.wltC  = PyBtcWallet().readWalletFile(self.fileC)
      self.jsonServer = Armory_Json_Rpc_Server(self.wltA, \
                                    inWltMap={SECOND_WLT_NAME : self.wltB, \
                                              THIRD_WLT_NAME : self.wltC}, \
                       armoryHomeDir=os.path.join(self.tiab.tiabDirectory, \
                                                  'tiab','armory'))
      
      self.wltIDs = [self.wltA.uniqueIDB58, self.wltB.uniqueIDB58, self.wltC.uniqueIDB58]
      #register a callback
      TheBDM.registerCppNotification(self.armoryDTiabTestCallback)

      #flag to check on wallet scan status
      self.numberOfWalletsScanned = 0
      
      self.wltA.registerWallet()
      time.sleep(0.5)
      self.wltB.registerWallet()
      time.sleep(0.5)
      self.wltC.registerWallet()
      time.sleep(0.5)
      #wait on scan for 20sec then raise if the scan hasn't finished yet
      i = 0
      while self.numberOfWalletsScanned < 3:
         time.sleep(0.5)
         i += 1
         if i >= 40:
            raise RuntimeError("self.numberOfWalletsScanned = %d" % self.numberOfWalletsScanned)
      
   def tearDown(self):
      TheBDM.unregisterCppNotification(self.armoryDTiabTestCallback)
      self.wltA.unregisterWallet()
      self.wltB.unregisterWallet()
      self.wltC.unregisterWallet()
      self.resetWalletFiles()
      

   def testActiveWallet(self):
      self.jsonServer.jsonrpc_setactivewallet(FIRST_WLT_NAME)
      result = self.jsonServer.jsonrpc_getactivewallet()
      self.assertEqual(result, FIRST_WLT_NAME)

      bogusResult = self.jsonServer.jsonrpc_setactivewallet('bogus wallet name')
      self.assertTrue('does not exist' in bogusResult)


   # Tests all of the address meta data functions at once

   def testAddressMetaData(self):
      testInput = {TIAB_WLT_1_ADDR_1:
                     {'chain': 5,
                      'index': 2},
                  TIAB_WLT_1_ADDR_2:
                     {'CrazyField': 'what',
                      '1': 1,
                      '2': 2}}
      self.jsonServer.jsonrpc_setaddressmetadata(testInput)
      testOutput1=self.jsonServer.jsonrpc_getaddressmetadata()
      self.assertEqual(testOutput1, testInput)
      self.jsonServer.jsonrpc_clearaddressmetadata()
      testOutput2=self.jsonServer.jsonrpc_getaddressmetadata()
      self.assertEqual(testOutput2, {})



   def testListloadedwallets(self):
      result = self.jsonServer.jsonrpc_listloadedwallets()
      self.assertEqual(len(result.keys()), 3)
      self.assertTrue(FIRST_WLT_NAME in result.values())
      self.assertTrue(SECOND_WLT_NAME in result.values())
      self.assertTrue(THIRD_WLT_NAME in result.values())



   def getPrivateKey(self, address):
      hash160 = addrStr_to_hash160(address)[1]
      if self.wltA.isLocked:
         self.wltA.unlock(securePassphrase=SecureBinaryData(PASSPHRASE1),
                               tempKeyLifetime=1000000)
      return self.wltA.addrMap[hash160].binPrivKey32_Plain.toBinStr()


   # Test Create lockbox and list loaded lockbox at the same time.
   # Also test set and get active lockbox.

   def testLockboxMethods(self):
      self.assertEqual(self.jsonServer.jsonrpc_getactivelockbox(), None)
      addrFromFirstWlt = self.wltA.peekNextUnusedAddr().getPubKey().toHexStr()
      addrFromSecondWlt = self.wltB.peekNextUnusedAddr().getPubKey().toHexStr()
      addrFromThirdWlt = self.wltC.peekNextUnusedAddr().getPubKey().toHexStr()

      # This test should succeed.
      actualResult1 = self.jsonServer.jsonrpc_createlockbox(2, 3, \
                                                            addrFromFirstWlt, \
                                                            SECOND_WLT_NAME, \
                                                            THIRD_WLT_NAME)
      self.assertTrue(TWO_OF_THREE_LB_NAME in actualResult1.values())

      # This test should fail because the first createlockbox() used the 2nd &
      # 3rd addresses.
      actualResult2 = self.jsonServer.jsonrpc_createlockbox(2, 3, \
                                                            addrFromFirstWlt, \
                                                            addrFromSecondWlt, \
                                                            addrFromThirdWlt)
      self.assertTrue(TWO_OF_THREE_LB_NAME in actualResult2['Error'])

      # This test should succeed.
      actualResult3 = self.jsonServer.jsonrpc_createlockbox(2, 2, \
                                                            addrFromSecondWlt, \
                                                            addrFromThirdWlt)
      self.assertEqual(TWO_OF_TWO_LB_NAME, actualResult3['id'])
      listResult3 = self.jsonServer.jsonrpc_listloadedlockboxes()
      self.assertEqual(len(listResult3.keys()), 2)
      self.assertTrue(TWO_OF_TWO_LB_NAME in listResult3.values())

      # This test should fail because of a bad wallet name.
      actualResult4 = self.jsonServer.jsonrpc_createlockbox(2, 2, \
                                                            addrFromFirstWlt, \
                                                            BAD_WLT_NAME)
      self.assertTrue(BAD_WLT_NAME in actualResult4['Error'])

      # This test should fail because of a malformed, uncompressed public key.
      actualResult5 = self.jsonServer.jsonrpc_createlockbox(2, 2, \
                                                            addrFromFirstWlt, \
                                                            BAD_PK_UNCOMP_1)
      self.assertTrue(BAD_PK_UNCOMP_1 in actualResult5['Error'])

      # This test should fail because of a malformed, compressed public key.
      actualResult6 = self.jsonServer.jsonrpc_createlockbox(2, 2, \
                                                            addrFromFirstWlt, \
                                                            BAD_PK_COMP_1)
      self.assertTrue(BAD_PK_COMP_1 in actualResult6['Error'])

      # This test should fail due to a compressed public key being used.
      foundUncompAddr = False
      actualResult7 = self.jsonServer.jsonrpc_createlockbox(2, 2, \
                                                            addrFromFirstWlt, \
                                                            GOOD_PK_COMP_1)
      self.assertTrue(GOOD_PK_COMP_1 in actualResult7['Error'])

      # This test should fail due to a malformed public key (incorrect length).
      actualResult8 = self.jsonServer.jsonrpc_createlockbox(2, 2, \
                                                            addrFromFirstWlt, \
                                                            BAD_PK)
      self.assertTrue(BAD_PK in actualResult8['Error'])

      # These tests should fail for various reasons related to the # of inputs.
      actualResult09 = self.jsonServer.jsonrpc_createlockbox(3, 2, \
                                                             addrFromFirstWlt, \
                                                             addrFromThirdWlt)
      self.assertTrue(ERRSTR09 in actualResult09['Error'])
      actualResult10 = self.jsonServer.jsonrpc_createlockbox(8, 8, \
                                                             addrFromFirstWlt, \
                                                             addrFromSecondWlt, \
                                                             addrFromThirdWlt, \
                                                             FIRST_WLT_NAME, \
                                                             SECOND_WLT_NAME, \
                                                             THIRD_WLT_NAME, \
                                                             GOOD_PK_UNCOMP_1, \
                                                             GOOD_PK_UNCOMP_2)
      self.assertTrue(ERRSTR10 in actualResult10['Error'])
      actualResult11 = self.jsonServer.jsonrpc_createlockbox(1, 8, \
                                                             addrFromFirstWlt, \
                                                             addrFromSecondWlt, \
                                                             addrFromThirdWlt, \
                                                             FIRST_WLT_NAME, \
                                                             SECOND_WLT_NAME, \
                                                             THIRD_WLT_NAME, \
                                                             GOOD_PK_UNCOMP_1, \
                                                             GOOD_PK_UNCOMP_2)
      self.assertTrue(ERRSTR11 in actualResult11['Error'])
      actualResult12 = self.jsonServer.jsonrpc_createlockbox(1, 4)
      self.assertTrue(ERRSTR12 in actualResult12['Error'])
      actualResult13 = self.jsonServer.jsonrpc_createlockbox(1, 2, \
                                                             addrFromFirstWlt, \
                                                             addrFromSecondWlt, \
                                                             addrFromThirdWlt)
      self.assertTrue(ERRSTR13 in actualResult13['Error'])
      actualResult14 = self.jsonServer.jsonrpc_createlockbox(1, 2, \
                                                             addrFromFirstWlt)
      self.assertTrue(ERRSTR14 in actualResult14['Error'])

      # These tests should succeed.
      self.jsonServer.jsonrpc_setactivelockbox(TWO_OF_TWO_LB_NAME)
      self.assertEqual(self.jsonServer.jsonrpc_getactivelockbox(), \
                       TWO_OF_TWO_LB_NAME)
      self.jsonServer.jsonrpc_setactivelockbox(TWO_OF_THREE_LB_NAME)
      self.assertEqual(self.jsonServer.jsonrpc_getactivelockbox(), \
                       TWO_OF_THREE_LB_NAME)



   def  testVerifysignature(self):
      clearSignMessage = ASv1CS(self.getPrivateKey(TIAB_WLT_1_ADDR_1), \
                                TEST_MESSAGE)
      inMsg = '\"' + clearSignMessage + '\"'
      result = self.jsonServer.jsonrpc_verifysignature(inMsg)
      self.assertEqual(result['message'], TEST_MESSAGE)
      self.assertEqual(result['address'], TIAB_WLT_1_ADDR_1)

   # Requires Supernode
   @SkipTest
   def  testReceivedfromsigner(self):
      clearSignMessage2 = ASv1CS(self.getPrivateKey(TIAB_WLT_1_ADDR_3), \
                                 TEST_MESSAGE)
      inMsg2 = '\"' + clearSignMessage2 + '\"'
      result2 = self.jsonServer.jsonrpc_getreceivedfromsigner(inMsg2)
      self.assertEqual(result2['message'], TEST_MESSAGE)
      self.assertEqual(result2['amount'], 0)


   # Requires Supernode
   @SkipTest
   def  testReceivedfromaddress(self):
      result = self.jsonServer.jsonrpc_getreceivedfromaddress(TIAB_WLT_3_ADDR_3)
      self.assertEqual(result, 0)
      result = self.jsonServer.jsonrpc_getreceivedfromaddress(TIAB_WLT_1_ADDR_2)
      self.assertEqual(result, EXPECTED_RECEIVED_FROM_TIAB_WLT_1_ADDR_2)


   def testGettransaction(self):
      tx = self.jsonServer.jsonrpc_gettransaction('db0ee46beff3a61f38bfc563f92c11449ed57c3d7d5cd5aafbe0114e5a9ceee4')
      self.assertEqual(tx, {'category': 'send', 'inputs': [{'fromtxid': '04b865ecf5fca3a56f6ce73a571a09a668f4b7aa5a7547a5f51fae08eadcdbb5',
                            'ismine': True, 'fromtxindex': 1, 'value': 1000.0, 'address': 'mtZ2d1jFZ9YNp3Ku5Fb2u8Tfu3RgimBHAD'}],
                            'direction': 'send', 'fee': 0.0001, 'totalinputs': 1000.0, 'outputs':
                             [{'address': 'mpXd2u8fPVYdL1Nf9bZ4EFnqhkNyghGLxL', 'value': 20.0, 'ismine': False},
                              {'address': 'mgLjhTCUtbeLPP9fDkBnG8oztWgJaXZQjn', 'value': 979.9999, 'ismine': True}],
                            'txid': 'db0ee46beff3a61f38bfc563f92c11449ed57c3d7d5cd5aafbe0114e5a9ceee4', 'confirmations': 10,
                            'orderinblock': 1, 'mainbranch': True, 'numtxin': 1, 'numtxout': 2,
                            'netdiff': -20.0001, 'infomissing': False})


   def testGetblock(self):
      block = self.jsonServer.jsonrpc_getblock('0000000064a1ad1f15981a713a6ef08fd98f69854c781dc7b8789cc5f678e01f')
      # This method is broken in a couple ways.
      # For no just verify that raw transaction is correct
      self.assertEqual(block['rawheader'], '02000000d8778a50d43d3e02c4c20bdd0ed97077a3c4bef3e86ce58975f6f43a00000000d25912cfc67228748494d421512c7a6cc31668fa82b72265261558802a89f4c2e0350153ffff001d10bcc285',)



   def testGetinfo(self):
      info = self.jsonServer.jsonrpc_getarmorydinfo()
      self.assertEqual(info['blocks'], TOP_TIAB_BLOCK)
      self.assertEqual(info['bdmstate'], BDM_BLOCKCHAIN_READY)
      self.assertEqual(info['walletversionstr'], '1.35')
      self.assertEqual(info['difficulty'], 1.0)
      self.assertEqual(info['balance'], FIRST_WLT_BALANCE)



   def testListtransactions(self):
      #takes a history page count now, not an amount of transactions to return
      txList = self.jsonServer.jsonrpc_listtransactions(0) 
      self.assertTrue(len(txList)>10)
      self.assertEqual(txList[0], {'blockhash': '0000000064a1ad1f15981a713a6ef08fd98f69854c781dc7b8789cc5f678e01f',
                  'blockindex': 1, 'confirmations': 31, 'address': 'mtZ2d1jFZ9YNp3Ku5Fb2u8Tfu3RgimBHAD',
                  'category': 'receive', 'account': '',
                  'txid': '04b865ecf5fca3a56f6ce73a571a09a668f4b7aa5a7547a5f51fae08eadcdbb5',
                  'blocktime': 1392588256, 'amount': 1000.0, 'timereceived': 1392588256, 'time': 1392588256})



   def testGetledgersimple(self):
      ledger = self.jsonServer.jsonrpc_getledgersimple(FIRST_WLT_NAME)
      self.assertTrue(len(ledger)>4)
      amountList = [row['amount'] for row in ledger]
      expectedAmountList = [20.0, 6.0, 10.0, 0.8, 30.0]
      self.assertEqual(amountList[:5], expectedAmountList)



   def testGetledger(self):
      ledger = self.jsonServer.jsonrpc_getledger(FIRST_WLT_NAME)
      self.assertTrue(len(ledger)>6)
      amountList = [row['amount'] for row in ledger]
      #expectedAmountList = [1000.0, 20.0, 30.0, 0.8, 10.0, 6.0, 20.0]
      expectedAmountList = [20.0, 6.0, 10.0, 0.8, 30.0, 20.0, 1000.0]
      self.assertEqual(amountList, expectedAmountList)
      self.assertEqual(ledger[0]['direction'], 'receive')
      self.assertEqual(len(ledger[0]['recipme']), 1)
      self.assertEqual(ledger[0]['recipme'][0]['amount'], 20.0)
      self.assertEqual(len(ledger[0]['recipother']), 1)
      self.assertEqual(ledger[0]['recipother'][0]['amount'], 0.8998)
      self.assertEqual(len(ledger[0]['senderme']), 0)
      self.assertEqual(ledger[0]['senderother'][0]['amount'], 11.8999)

      self.assertEqual(ledger[5]['direction'], 'send')
      self.assertEqual(len(ledger[5]['senderother']), 0)
      self.assertEqual(len(ledger[5]['senderme']), 1)
      self.assertEqual(ledger[5]['senderme'][0]['amount'], 1000.0)



   def testSendtoaddress(self):
      # Send 1 BTC
      serializedUnsignedTx = \
         self.jsonServer.jsonrpc_createustxtoaddress(TIAB_WLT_3_ADDR_3, \
                                                     BTC_TO_SEND)
      unsignedTx = UnsignedTransaction().unserializeAscii(serializedUnsignedTx)
      # Should have 2 txouts to TIAB_WLT_3_ADDR_3 and the change
      self.assertEqual(len(unsignedTx.decorTxOuts), 2)
      foundTxOut = False
      for txout in unsignedTx.decorTxOuts:
         if script_to_addrStr(txout.binScript) == TIAB_WLT_3_ADDR_3:
            self.assertEqual(txout.value, JSONtoAmount(BTC_TO_SEND))
            foundTxOut = True
      self.assertTrue(foundTxOut)

      # Test two paths through signing method and make sure they are equal
      # Wallets in the TIAB start out unencrypted
      f = open(TX_FILENAME, 'w')
      f.write(serializedUnsignedTx)
      f.close()
      serializedSignedTxUnencrypted = \
            self.jsonServer.jsonrpc_signasciitransaction(TX_FILENAME) 
      self.jsonServer.jsonrpc_encryptwallet(PASSPHRASE1)
      self.jsonServer.jsonrpc_walletpassphrase(PASSPHRASE1)
      serializedSignedTxEncrypted = \
            self.jsonServer.jsonrpc_signasciitransaction(TX_FILENAME)
      # Other tests expect wallet to be unencrypted
      self.wltA.unlock(securePassphrase=SecureBinaryData(PASSPHRASE1),
                            tempKeyLifetime=1000000)
      self.wltA.changeWalletEncryption()
      signedTxUnencrypted = UnsignedTransaction().unserializeAscii(serializedSignedTxUnencrypted)
      signedTxEncrypted = UnsignedTransaction().unserializeAscii(serializedSignedTxEncrypted)
      # check number of outputs 1 Btc goes to a single output and the other goes to change
      self.assertEqual(len(signedTxUnencrypted.decorTxOuts), 2)
      self.assertEqual(len(signedTxEncrypted.decorTxOuts), 2)
      self.assertEqual(signedTxUnencrypted.asciiID, signedTxEncrypted.asciiID)
      self.assertTrue(JSONtoAmount(BTC_TO_SEND) in
             [signedTxEncrypted.decorTxOuts[0].value,
              signedTxEncrypted.decorTxOuts[1].value])
      self.assertTrue(JSONtoAmount(BTC_TO_SEND) in
             [signedTxUnencrypted.decorTxOuts[0].value,
              signedTxUnencrypted.decorTxOuts[1].value])
      f = open(TX_FILENAME, 'w')
      f.write(signedTxEncrypted.serializeAscii())
      f.close()
      txHexToBroadcast = self.jsonServer.jsonrpc_gethextxtobroadcast(TX_FILENAME)
      finalPyTx = PyTx().unserialize(hex_to_binary(txHexToBroadcast))
      self.assertEqual(len(finalPyTx.outputs), 2)
      self.assertTrue(JSONtoAmount(BTC_TO_SEND) in
             [finalPyTx.outputs[0].value,
              finalPyTx.outputs[1].value])


   def testSendmany(self):
      # Send 1 BTC
      serializedUnsignedTx = \
         self.jsonServer.jsonrpc_createustxformany(None, ','.join([TIAB_WLT_3_ADDR_2, str(BTC_TO_SEND)]), \
                                                   ','.join([TIAB_WLT_3_ADDR_3, str(BTC_TO_SEND)]))
      unsignedTx = UnsignedTransaction().unserializeAscii(serializedUnsignedTx)
      # Should have 2 txouts to TIAB_WLT_3_ADDR_3 and the change
      self.assertEqual(len(unsignedTx.decorTxOuts), 3)
      txOutsFound = 0
      for txout in unsignedTx.decorTxOuts:
         if script_to_addrStr(txout.binScript) in [TIAB_WLT_3_ADDR_2, TIAB_WLT_3_ADDR_3]:
            self.assertEqual(txout.value, JSONtoAmount(BTC_TO_SEND))
            txOutsFound += 1
      self.assertEqual(txOutsFound, 2)



   def testListUnspent(self):
      actualResult = self.jsonServer.jsonrpc_listunspent()

      tx1Found = False
      tx5Found = False
      for i in range(len(actualResult)):
         if actualResult[i]['txid'] == EXPECTED_UNSPENT_TX1_HEX:
            self.assertEqual(actualResult[i]['amount'], \
                             EXPECTED_UNSPENT_TX1_BAL)
            self.assertEqual(actualResult[i]['confirmations'], \
                             EXPECTED_UNSPENT_TX1_CONF)
            self.assertEqual(actualResult[i]['priority'], \
                             EXPECTED_UNSPENT_TX1_PRI)
            tx1Found = True
         elif actualResult[i]['txid'] == EXPECTED_UNSPENT_TX5_HEX:
            self.assertEqual(actualResult[i]['amount'], \
                             EXPECTED_UNSPENT_TX5_BAL)
            self.assertEqual(actualResult[i]['confirmations'], \
                             EXPECTED_UNSPENT_TX5_CONF)
            self.assertEqual(actualResult[i]['priority'], \
                             EXPECTED_UNSPENT_TX5_PRI)
            tx5Found = True
      self.assertTrue(tx1Found)
      self.assertTrue(tx5Found)
      



   def testListAddrUnspent(self):
      totStr = '%s,%s' % (TIAB_WLT_1_ADDR_3, TIAB_WLT_1_ADDR_8)
      actualResult = self.jsonServer.jsonrpc_listaddrunspent(totStr)

      self.assertEqual(actualResult['addrbalance'][TIAB_WLT_1_ADDR_3], \
                       TIAB_WLT_1_PK_UTXO_BAL_3)
      self.assertEqual(actualResult['addrbalance'][TIAB_WLT_1_ADDR_8], \
                       TIAB_WLT_1_PK_UTXO_BAL_8)
      # NB: Ideally, the TAB asserts would be against addresses with multiple
      # UTXOs. As is, this test case works but could be better.
      self.assertEqual(actualResult['totalbalance'], TIAB_WLT_1_PK_UTXO_BAL_3 + TIAB_WLT_1_PK_UTXO_BAL_8 )
      self.assertEqual(actualResult['numutxo'], 2)


   def testGetNewAddress(self):
      actualResult = self.jsonServer.jsonrpc_getnewaddress()
      self.assertEqual(actualResult, EXPECTED_TIAB_NEXT_ADDR)



   def testGetBalance(self):
      balances = {'spendable' : FIRST_WLT_BALANCE, \
                  'spend' : FIRST_WLT_BALANCE, \
                  'unconf' : 0, \
                  'unconfirmed' :  0, \
                  'total' : FIRST_WLT_BALANCE, \
                  'ultimate'  :  FIRST_WLT_BALANCE, \
                  'unspent' :  FIRST_WLT_BALANCE, \
                  'full' :  FIRST_WLT_BALANCE}
      for balanceType in balances.keys():
         result = self.jsonServer.jsonrpc_getbalance(balanceType)
         self.assertEqual(result,
                          AmountToJSON(self.wltA.getBalance(balanceType)))
コード例 #14
0
class ArmoryDTiabTest(TiabTest):
    def armoryDTiabTestCallback(self, action, args):
        if action == REFRESH_ACTION:
            for wltID in args:
                print wltID
                if wltID in self.wltIDs:
                    self.numberOfWalletsScanned += 1

    def setUp(self):
        self.verifyBlockHeight()
        # Load the primary file from the test net in a box
        self.fileA = os.path.join(self.tiab.tiabDirectory, 'tiab', 'armory', \
                                  'armory_%s_.wallet' % FIRST_WLT_NAME)
        self.wltA = PyBtcWallet().readWalletFile(self.fileA)
        self.fileB = os.path.join(self.tiab.tiabDirectory, 'tiab', 'armory', \
                                  'armory_%s_.wallet' % SECOND_WLT_NAME)
        self.wltB = PyBtcWallet().readWalletFile(self.fileB)
        self.fileC = os.path.join(self.tiab.tiabDirectory, 'tiab', 'armory', \
                                  'armory_%s_.wallet' % THIRD_WLT_NAME)
        self.wltC = PyBtcWallet().readWalletFile(self.fileC)
        self.jsonServer = Armory_Json_Rpc_Server(self.wltA, \
                                      inWltMap={SECOND_WLT_NAME : self.wltB, \
                                                THIRD_WLT_NAME : self.wltC}, \
                         armoryHomeDir=os.path.join(self.tiab.tiabDirectory, \
                                                    'tiab','armory'))

        self.wltIDs = [
            self.wltA.uniqueIDB58, self.wltB.uniqueIDB58, self.wltC.uniqueIDB58
        ]
        #register a callback
        TheBDM.registerCppNotification(self.armoryDTiabTestCallback)

        #flag to check on wallet scan status
        self.numberOfWalletsScanned = 0

        self.wltA.registerWallet()
        time.sleep(0.5)
        self.wltB.registerWallet()
        time.sleep(0.5)
        self.wltC.registerWallet()
        time.sleep(0.5)
        #wait on scan for 20sec then raise if the scan hasn't finished yet
        i = 0
        while self.numberOfWalletsScanned < 3:
            time.sleep(0.5)
            i += 1
            if i >= 40:
                raise RuntimeError("self.numberOfWalletsScanned = %d" %
                                   self.numberOfWalletsScanned)

    def tearDown(self):
        TheBDM.unregisterCppNotification(self.armoryDTiabTestCallback)
        self.wltA.unregisterWallet()
        self.wltB.unregisterWallet()
        self.wltC.unregisterWallet()
        self.resetWalletFiles()

    def testActiveWallet(self):
        self.jsonServer.jsonrpc_setactivewallet(FIRST_WLT_NAME)
        result = self.jsonServer.jsonrpc_getactivewallet()
        self.assertEqual(result, FIRST_WLT_NAME)

        bogusResult = self.jsonServer.jsonrpc_setactivewallet(
            'bogus wallet name')
        self.assertTrue('does not exist' in bogusResult)

    # Tests all of the address meta data functions at once

    def testAddressMetaData(self):
        testInput = {
            TIAB_WLT_1_ADDR_1: {
                'chain': 5,
                'index': 2
            },
            TIAB_WLT_1_ADDR_2: {
                'CrazyField': 'what',
                '1': 1,
                '2': 2
            }
        }
        self.jsonServer.jsonrpc_setaddressmetadata(testInput)
        testOutput1 = self.jsonServer.jsonrpc_getaddressmetadata()
        self.assertEqual(testOutput1, testInput)
        self.jsonServer.jsonrpc_clearaddressmetadata()
        testOutput2 = self.jsonServer.jsonrpc_getaddressmetadata()
        self.assertEqual(testOutput2, {})

    def testListloadedwallets(self):
        result = self.jsonServer.jsonrpc_listloadedwallets()
        self.assertEqual(len(result.keys()), 3)
        self.assertTrue(FIRST_WLT_NAME in result.values())
        self.assertTrue(SECOND_WLT_NAME in result.values())
        self.assertTrue(THIRD_WLT_NAME in result.values())

    def getPrivateKey(self, address):
        hash160 = addrStr_to_hash160(address)[1]
        if self.wltA.isLocked:
            self.wltA.unlock(securePassphrase=SecureBinaryData(PASSPHRASE1),
                             tempKeyLifetime=1000000)
        return self.wltA.addrMap[hash160].binPrivKey32_Plain.toBinStr()

    # Test Create lockbox and list loaded lockbox at the same time.
    # Also test set and get active lockbox.

    def testLockboxMethods(self):
        self.assertEqual(self.jsonServer.jsonrpc_getactivelockbox(), None)
        addrFromFirstWlt = self.wltA.peekNextUnusedAddr().getPubKey().toHexStr(
        )
        addrFromSecondWlt = self.wltB.peekNextUnusedAddr().getPubKey(
        ).toHexStr()
        addrFromThirdWlt = self.wltC.peekNextUnusedAddr().getPubKey().toHexStr(
        )

        # This test should succeed.
        actualResult1 = self.jsonServer.jsonrpc_createlockbox(2, 3, \
                                                              addrFromFirstWlt, \
                                                              SECOND_WLT_NAME, \
                                                              THIRD_WLT_NAME)
        self.assertTrue(TWO_OF_THREE_LB_NAME in actualResult1.values())

        # This test should fail because the first createlockbox() used the 2nd &
        # 3rd addresses.
        actualResult2 = self.jsonServer.jsonrpc_createlockbox(2, 3, \
                                                              addrFromFirstWlt, \
                                                              addrFromSecondWlt, \
                                                              addrFromThirdWlt)
        self.assertTrue(TWO_OF_THREE_LB_NAME in actualResult2['Error'])

        # This test should succeed.
        actualResult3 = self.jsonServer.jsonrpc_createlockbox(2, 2, \
                                                              addrFromSecondWlt, \
                                                              addrFromThirdWlt)
        self.assertEqual(TWO_OF_TWO_LB_NAME, actualResult3['id'])
        listResult3 = self.jsonServer.jsonrpc_listloadedlockboxes()
        self.assertEqual(len(listResult3.keys()), 2)
        self.assertTrue(TWO_OF_TWO_LB_NAME in listResult3.values())

        # This test should fail because of a bad wallet name.
        actualResult4 = self.jsonServer.jsonrpc_createlockbox(2, 2, \
                                                              addrFromFirstWlt, \
                                                              BAD_WLT_NAME)
        self.assertTrue(BAD_WLT_NAME in actualResult4['Error'])

        # This test should fail because of a malformed, uncompressed public key.
        actualResult5 = self.jsonServer.jsonrpc_createlockbox(2, 2, \
                                                              addrFromFirstWlt, \
                                                              BAD_PK_UNCOMP_1)
        self.assertTrue(BAD_PK_UNCOMP_1 in actualResult5['Error'])

        # This test should fail because of a malformed, compressed public key.
        actualResult6 = self.jsonServer.jsonrpc_createlockbox(2, 2, \
                                                              addrFromFirstWlt, \
                                                              BAD_PK_COMP_1)
        self.assertTrue(BAD_PK_COMP_1 in actualResult6['Error'])

        # This test should fail due to a compressed public key being used.
        foundUncompAddr = False
        actualResult7 = self.jsonServer.jsonrpc_createlockbox(2, 2, \
                                                              addrFromFirstWlt, \
                                                              GOOD_PK_COMP_1)
        self.assertTrue(GOOD_PK_COMP_1 in actualResult7['Error'])

        # This test should fail due to a malformed public key (incorrect length).
        actualResult8 = self.jsonServer.jsonrpc_createlockbox(2, 2, \
                                                              addrFromFirstWlt, \
                                                              BAD_PK)
        self.assertTrue(BAD_PK in actualResult8['Error'])

        # These tests should fail for various reasons related to the # of inputs.
        actualResult09 = self.jsonServer.jsonrpc_createlockbox(3, 2, \
                                                               addrFromFirstWlt, \
                                                               addrFromThirdWlt)
        self.assertTrue(ERRSTR09 in actualResult09['Error'])
        actualResult10 = self.jsonServer.jsonrpc_createlockbox(8, 8, \
                                                               addrFromFirstWlt, \
                                                               addrFromSecondWlt, \
                                                               addrFromThirdWlt, \
                                                               FIRST_WLT_NAME, \
                                                               SECOND_WLT_NAME, \
                                                               THIRD_WLT_NAME, \
                                                               GOOD_PK_UNCOMP_1, \
                                                               GOOD_PK_UNCOMP_2)
        self.assertTrue(ERRSTR10 in actualResult10['Error'])
        actualResult11 = self.jsonServer.jsonrpc_createlockbox(1, 8, \
                                                               addrFromFirstWlt, \
                                                               addrFromSecondWlt, \
                                                               addrFromThirdWlt, \
                                                               FIRST_WLT_NAME, \
                                                               SECOND_WLT_NAME, \
                                                               THIRD_WLT_NAME, \
                                                               GOOD_PK_UNCOMP_1, \
                                                               GOOD_PK_UNCOMP_2)
        self.assertTrue(ERRSTR11 in actualResult11['Error'])
        actualResult12 = self.jsonServer.jsonrpc_createlockbox(1, 4)
        self.assertTrue(ERRSTR12 in actualResult12['Error'])
        actualResult13 = self.jsonServer.jsonrpc_createlockbox(1, 2, \
                                                               addrFromFirstWlt, \
                                                               addrFromSecondWlt, \
                                                               addrFromThirdWlt)
        self.assertTrue(ERRSTR13 in actualResult13['Error'])
        actualResult14 = self.jsonServer.jsonrpc_createlockbox(1, 2, \
                                                               addrFromFirstWlt)
        self.assertTrue(ERRSTR14 in actualResult14['Error'])

        # These tests should succeed.
        self.jsonServer.jsonrpc_setactivelockbox(TWO_OF_TWO_LB_NAME)
        self.assertEqual(self.jsonServer.jsonrpc_getactivelockbox(), \
                         TWO_OF_TWO_LB_NAME)
        self.jsonServer.jsonrpc_setactivelockbox(TWO_OF_THREE_LB_NAME)
        self.assertEqual(self.jsonServer.jsonrpc_getactivelockbox(), \
                         TWO_OF_THREE_LB_NAME)

    def testVerifysignature(self):
        clearSignMessage = ASv1CS(self.getPrivateKey(TIAB_WLT_1_ADDR_1), \
                                  TEST_MESSAGE)
        inMsg = '\"' + clearSignMessage + '\"'
        result = self.jsonServer.jsonrpc_verifysignature(inMsg)
        self.assertEqual(result['message'], TEST_MESSAGE)
        self.assertEqual(result['address'], TIAB_WLT_1_ADDR_1)

    # Requires Supernode
    @SkipTest
    def testReceivedfromsigner(self):
        clearSignMessage2 = ASv1CS(self.getPrivateKey(TIAB_WLT_1_ADDR_3), \
                                   TEST_MESSAGE)
        inMsg2 = '\"' + clearSignMessage2 + '\"'
        result2 = self.jsonServer.jsonrpc_getreceivedfromsigner(inMsg2)
        self.assertEqual(result2['message'], TEST_MESSAGE)
        self.assertEqual(result2['amount'], 0)

    # Requires Supernode
    @SkipTest
    def testReceivedfromaddress(self):
        result = self.jsonServer.jsonrpc_getreceivedfromaddress(
            TIAB_WLT_3_ADDR_3)
        self.assertEqual(result, 0)
        result = self.jsonServer.jsonrpc_getreceivedfromaddress(
            TIAB_WLT_1_ADDR_2)
        self.assertEqual(result, EXPECTED_RECEIVED_FROM_TIAB_WLT_1_ADDR_2)

    def testGettransaction(self):
        tx = self.jsonServer.jsonrpc_gettransaction(
            'db0ee46beff3a61f38bfc563f92c11449ed57c3d7d5cd5aafbe0114e5a9ceee4')
        self.assertEqual(
            tx, {
                'category':
                'send',
                'inputs': [{
                    'fromtxid':
                    '04b865ecf5fca3a56f6ce73a571a09a668f4b7aa5a7547a5f51fae08eadcdbb5',
                    'ismine': True,
                    'fromtxindex': 1,
                    'value': 1000.0,
                    'address': 'mtZ2d1jFZ9YNp3Ku5Fb2u8Tfu3RgimBHAD'
                }],
                'direction':
                'send',
                'fee':
                0.0001,
                'totalinputs':
                1000.0,
                'outputs': [{
                    'address': 'mpXd2u8fPVYdL1Nf9bZ4EFnqhkNyghGLxL',
                    'value': 20.0,
                    'ismine': False
                }, {
                    'address': 'mgLjhTCUtbeLPP9fDkBnG8oztWgJaXZQjn',
                    'value': 979.9999,
                    'ismine': True
                }],
                'txid':
                'db0ee46beff3a61f38bfc563f92c11449ed57c3d7d5cd5aafbe0114e5a9ceee4',
                'confirmations':
                10,
                'orderinblock':
                1,
                'mainbranch':
                True,
                'numtxin':
                1,
                'numtxout':
                2,
                'netdiff':
                -20.0001,
                'infomissing':
                False
            })

    def testGetblock(self):
        block = self.jsonServer.jsonrpc_getblock(
            '0000000064a1ad1f15981a713a6ef08fd98f69854c781dc7b8789cc5f678e01f')
        # This method is broken in a couple ways.
        # For no just verify that raw transaction is correct
        self.assertEqual(
            block['rawheader'],
            '02000000d8778a50d43d3e02c4c20bdd0ed97077a3c4bef3e86ce58975f6f43a00000000d25912cfc67228748494d421512c7a6cc31668fa82b72265261558802a89f4c2e0350153ffff001d10bcc285',
        )

    def testGetinfo(self):
        info = self.jsonServer.jsonrpc_getarmorydinfo()
        self.assertEqual(info['blocks'], TOP_TIAB_BLOCK)
        self.assertEqual(info['bdmstate'], BDM_BLOCKCHAIN_READY)
        self.assertEqual(info['walletversionstr'], '1.35')
        self.assertEqual(info['difficulty'], 1.0)
        self.assertEqual(info['balance'], FIRST_WLT_BALANCE)

    def testListtransactions(self):
        #takes a history page count now, not an amount of transactions to return
        txList = self.jsonServer.jsonrpc_listtransactions(0)
        self.assertTrue(len(txList) > 10)
        self.assertEqual(
            txList[0], {
                'blockhash':
                '0000000064a1ad1f15981a713a6ef08fd98f69854c781dc7b8789cc5f678e01f',
                'blockindex': 1,
                'confirmations': 31,
                'address': 'mtZ2d1jFZ9YNp3Ku5Fb2u8Tfu3RgimBHAD',
                'category': 'receive',
                'account': '',
                'txid':
                '04b865ecf5fca3a56f6ce73a571a09a668f4b7aa5a7547a5f51fae08eadcdbb5',
                'blocktime': 1392588256,
                'amount': 1000.0,
                'timereceived': 1392588256,
                'time': 1392588256
            })

    def testGetledgersimple(self):
        ledger = self.jsonServer.jsonrpc_getledgersimple(FIRST_WLT_NAME)
        self.assertTrue(len(ledger) > 4)
        amountList = [row['amount'] for row in ledger]
        expectedAmountList = [20.0, 6.0, 10.0, 0.8, 30.0]
        self.assertEqual(amountList[:5], expectedAmountList)

    def testGetledger(self):
        ledger = self.jsonServer.jsonrpc_getledger(FIRST_WLT_NAME)
        self.assertTrue(len(ledger) > 6)
        amountList = [row['amount'] for row in ledger]
        #expectedAmountList = [1000.0, 20.0, 30.0, 0.8, 10.0, 6.0, 20.0]
        expectedAmountList = [20.0, 6.0, 10.0, 0.8, 30.0, 20.0, 1000.0]
        self.assertEqual(amountList, expectedAmountList)
        self.assertEqual(ledger[0]['direction'], 'receive')
        self.assertEqual(len(ledger[0]['recipme']), 1)
        self.assertEqual(ledger[0]['recipme'][0]['amount'], 20.0)
        self.assertEqual(len(ledger[0]['recipother']), 1)
        self.assertEqual(ledger[0]['recipother'][0]['amount'], 0.8998)
        self.assertEqual(len(ledger[0]['senderme']), 0)
        self.assertEqual(ledger[0]['senderother'][0]['amount'], 11.8999)

        self.assertEqual(ledger[5]['direction'], 'send')
        self.assertEqual(len(ledger[5]['senderother']), 0)
        self.assertEqual(len(ledger[5]['senderme']), 1)
        self.assertEqual(ledger[5]['senderme'][0]['amount'], 1000.0)

    def testSendtoaddress(self):
        # Send 1 BTC
        serializedUnsignedTx = \
           self.jsonServer.jsonrpc_createustxtoaddress(TIAB_WLT_3_ADDR_3, \
                                                       BTC_TO_SEND)
        unsignedTx = UnsignedTransaction().unserializeAscii(
            serializedUnsignedTx)
        # Should have 2 txouts to TIAB_WLT_3_ADDR_3 and the change
        self.assertEqual(len(unsignedTx.decorTxOuts), 2)
        foundTxOut = False
        for txout in unsignedTx.decorTxOuts:
            if script_to_addrStr(txout.binScript) == TIAB_WLT_3_ADDR_3:
                self.assertEqual(txout.value, JSONtoAmount(BTC_TO_SEND))
                foundTxOut = True
        self.assertTrue(foundTxOut)

        # Test two paths through signing method and make sure they are equal
        # Wallets in the TIAB start out unencrypted
        f = open(TX_FILENAME, 'w')
        f.write(serializedUnsignedTx)
        f.close()
        serializedSignedTxUnencrypted = \
              self.jsonServer.jsonrpc_signasciitransaction(TX_FILENAME)
        self.jsonServer.jsonrpc_encryptwallet(PASSPHRASE1)
        self.jsonServer.jsonrpc_walletpassphrase(PASSPHRASE1)
        serializedSignedTxEncrypted = \
              self.jsonServer.jsonrpc_signasciitransaction(TX_FILENAME)
        # Other tests expect wallet to be unencrypted
        self.wltA.unlock(securePassphrase=SecureBinaryData(PASSPHRASE1),
                         tempKeyLifetime=1000000)
        self.wltA.changeWalletEncryption()
        signedTxUnencrypted = UnsignedTransaction().unserializeAscii(
            serializedSignedTxUnencrypted)
        signedTxEncrypted = UnsignedTransaction().unserializeAscii(
            serializedSignedTxEncrypted)
        # check number of outputs 1 Btc goes to a single output and the other goes to change
        self.assertEqual(len(signedTxUnencrypted.decorTxOuts), 2)
        self.assertEqual(len(signedTxEncrypted.decorTxOuts), 2)
        self.assertEqual(signedTxUnencrypted.asciiID,
                         signedTxEncrypted.asciiID)
        self.assertTrue(
            JSONtoAmount(BTC_TO_SEND) in [
                signedTxEncrypted.decorTxOuts[0].value,
                signedTxEncrypted.decorTxOuts[1].value
            ])
        self.assertTrue(
            JSONtoAmount(BTC_TO_SEND) in [
                signedTxUnencrypted.decorTxOuts[0].value,
                signedTxUnencrypted.decorTxOuts[1].value
            ])
        f = open(TX_FILENAME, 'w')
        f.write(signedTxEncrypted.serializeAscii())
        f.close()
        txHexToBroadcast = self.jsonServer.jsonrpc_gethextxtobroadcast(
            TX_FILENAME)
        finalPyTx = PyTx().unserialize(hex_to_binary(txHexToBroadcast))
        self.assertEqual(len(finalPyTx.outputs), 2)
        self.assertTrue(
            JSONtoAmount(BTC_TO_SEND) in
            [finalPyTx.outputs[0].value, finalPyTx.outputs[1].value])

    def testSendmany(self):
        # Send 1 BTC
        serializedUnsignedTx = \
           self.jsonServer.jsonrpc_createustxformany(None, ','.join([TIAB_WLT_3_ADDR_2, str(BTC_TO_SEND)]), \
                                                     ','.join([TIAB_WLT_3_ADDR_3, str(BTC_TO_SEND)]))
        unsignedTx = UnsignedTransaction().unserializeAscii(
            serializedUnsignedTx)
        # Should have 2 txouts to TIAB_WLT_3_ADDR_3 and the change
        self.assertEqual(len(unsignedTx.decorTxOuts), 3)
        txOutsFound = 0
        for txout in unsignedTx.decorTxOuts:
            if script_to_addrStr(
                    txout.binScript) in [TIAB_WLT_3_ADDR_2, TIAB_WLT_3_ADDR_3]:
                self.assertEqual(txout.value, JSONtoAmount(BTC_TO_SEND))
                txOutsFound += 1
        self.assertEqual(txOutsFound, 2)

    def testListUnspent(self):
        actualResult = self.jsonServer.jsonrpc_listunspent()

        tx1Found = False
        tx5Found = False
        for i in range(len(actualResult)):
            if actualResult[i]['txid'] == EXPECTED_UNSPENT_TX1_HEX:
                self.assertEqual(actualResult[i]['amount'], \
                                 EXPECTED_UNSPENT_TX1_BAL)
                self.assertEqual(actualResult[i]['confirmations'], \
                                 EXPECTED_UNSPENT_TX1_CONF)
                self.assertEqual(actualResult[i]['priority'], \
                                 EXPECTED_UNSPENT_TX1_PRI)
                tx1Found = True
            elif actualResult[i]['txid'] == EXPECTED_UNSPENT_TX5_HEX:
                self.assertEqual(actualResult[i]['amount'], \
                                 EXPECTED_UNSPENT_TX5_BAL)
                self.assertEqual(actualResult[i]['confirmations'], \
                                 EXPECTED_UNSPENT_TX5_CONF)
                self.assertEqual(actualResult[i]['priority'], \
                                 EXPECTED_UNSPENT_TX5_PRI)
                tx5Found = True
        self.assertTrue(tx1Found)
        self.assertTrue(tx5Found)

    def testListAddrUnspent(self):
        totStr = '%s,%s' % (TIAB_WLT_1_ADDR_3, TIAB_WLT_1_ADDR_8)
        actualResult = self.jsonServer.jsonrpc_listaddrunspent(totStr)

        self.assertEqual(actualResult['addrbalance'][TIAB_WLT_1_ADDR_3], \
                         TIAB_WLT_1_PK_UTXO_BAL_3)
        self.assertEqual(actualResult['addrbalance'][TIAB_WLT_1_ADDR_8], \
                         TIAB_WLT_1_PK_UTXO_BAL_8)
        # NB: Ideally, the TAB asserts would be against addresses with multiple
        # UTXOs. As is, this test case works but could be better.
        self.assertEqual(actualResult['totalbalance'],
                         TIAB_WLT_1_PK_UTXO_BAL_3 + TIAB_WLT_1_PK_UTXO_BAL_8)
        self.assertEqual(actualResult['numutxo'], 2)

    def testGetNewAddress(self):
        actualResult = self.jsonServer.jsonrpc_getnewaddress()
        self.assertEqual(actualResult, EXPECTED_TIAB_NEXT_ADDR)

    def testGetBalance(self):
        balances = {'spendable' : FIRST_WLT_BALANCE, \
                    'spend' : FIRST_WLT_BALANCE, \
                    'unconf' : 0, \
                    'unconfirmed' :  0, \
                    'total' : FIRST_WLT_BALANCE, \
                    'ultimate'  :  FIRST_WLT_BALANCE, \
                    'unspent' :  FIRST_WLT_BALANCE, \
                    'full' :  FIRST_WLT_BALANCE}
        for balanceType in balances.keys():
            result = self.jsonServer.jsonrpc_getbalance(balanceType)
            self.assertEqual(result,
                             AmountToJSON(self.wltA.getBalance(balanceType)))
コード例 #15
0
class ArmoryDTest(unittest.TestCase):
    def removeFileList(self, fileList):
        for f in fileList:
            if os.path.exists(f):
                os.remove(f)

    @classmethod
    def setUpClass(self):
        # This is not a UI so no need to worry about the main thread being blocked.
        # Any UI that uses this Daemon can put the call to the Daemon on it's own thread.
        TheBDM.setBlocking(True)
        TheBDM.setOnlineMode(True)
        while not TheBDM.getBDMState() == 'BlockchainReady':
            time.sleep(2)

    def setUp(self):
        self.fileA = os.path.join(ARMORY_HOME_DIR,
                                  'armory_%s_.wallet' % TEST_WALLET_ID)
        self.fileB = os.path.join(ARMORY_HOME_DIR,
                                  'armory_%s_backup.wallet' % TEST_WALLET_ID)
        self.fileAupd = os.path.join(
            ARMORY_HOME_DIR,
            'armory_%s_backup_unsuccessful.wallet' % TEST_WALLET_ID)
        self.fileBupd = os.path.join(
            ARMORY_HOME_DIR,
            'armory_%s_update_unsuccessful.wallet' % TEST_WALLET_ID)

        self.removeFileList(
            [self.fileA, self.fileB, self.fileAupd, self.fileBupd])

        # We need a controlled test, so we script the all the normally-random stuff
        self.privKey = SecureBinaryData('\xaa' * 32)
        self.privKey2 = SecureBinaryData('\x33' * 32)
        self.chainstr = SecureBinaryData('\xee' * 32)
        theIV = SecureBinaryData(hex_to_binary('77' * 16))
        self.passphrase = SecureBinaryData('A self.passphrase')
        self.passphrase2 = SecureBinaryData('A new self.passphrase')

        self.wallet = PyBtcWallet().createNewWallet(withEncrypt=False, \
                                            plainRootKey=self.privKey, \
                                            chaincode=self.chainstr,   \
                                            IV=theIV, \
                                            shortLabel=TEST_WALLET_NAME, \
                                            longLabel=TEST_WALLET_DESCRIPTION)
        self.jsonServer = Armory_Json_Rpc_Server(self.wallet)
        TheBDM.registerWallet(self.wallet)

    def tearDown(self):
        self.removeFileList(
            [self.fileA, self.fileB, self.fileAupd, self.fileBupd])

    # Can't test with actual transactions in this environment. See ARMORY-34.
    # This wallet has no txs
    def testListunspent(self):
        actualResult = self.jsonServer.jsonrpc_listunspent()
        self.assertEqual(actualResult, [])

    def testImportprivkey(self):
        originalLength = len(self.wallet.linearAddr160List)
        self.jsonServer.jsonrpc_importprivkey(self.privKey2)
        self.assertEqual(len(self.wallet.linearAddr160List),
                         originalLength + 1)

    def testGettxout(self):
        txOut = self.jsonServer.jsonrpc_gettxout(TX_ID1, 0)
        self.assertEquals(TX_ID1_OUTPUT0_VALUE, txOut.value)
        txOut = self.jsonServer.jsonrpc_gettxout(TX_ID1, 1)
        self.assertEquals(TX_ID1_OUTPUT1_VALUE, txOut.value)

    # Cannot unit test actual balances. Only verify that getreceivedbyaddress return a 0 result.
    def testGetreceivedbyaddress(self):
        a160 = hash160(
            self.wallet.getNextUnusedAddress().binPublicKey65.toBinStr())
        testAddr = hash160_to_addrStr(a160)
        result = self.jsonServer.jsonrpc_getreceivedbyaddress(testAddr)
        self.assertEqual(result, 0)

    def testGetrawtransaction(self):
        actualRawTx = self.jsonServer.jsonrpc_getrawtransaction(TX_ID1)
        pyTx = PyTx().unserialize(hex_to_binary(actualRawTx))
        self.assertEquals(TX_ID1, binary_to_hex(pyTx.getHash(), BIGENDIAN))

    def testBackupWallet(self):
        backupTestPath = os.path.join(
            ARMORY_HOME_DIR, 'armory_%s_.wallet.backup.test' % TEST_WALLET_ID)
        # Remove backupTestPath in case it exists
        backupFileList = [backupTestPath, self.fileB]
        self.removeFileList(backupFileList)
        # Remove the backup test path that is to be created after tear down.
        self.addCleanup(self.removeFileList, backupFileList)
        self.jsonServer.jsonrpc_backupwallet(backupTestPath)
        self.assertTrue(os.path.exists(backupTestPath))
        self.wallet.backupWalletFile()
        self.assertTrue(os.path.exists(self.fileB))

    def testDecoderawtransaction(self):
        actualDD = self.jsonServer.jsonrpc_decoderawtransaction(RAW_TX1)
        # Test specific values pulled from bitcoin daemon's output for the test raw TX
        expectScriptStr = 'OP_DUP OP_HASH160 PUSHDATA(20) [be17ec0fc1f8aa029223dbe5f53109d0faf8c797] OP_EQUALVERIFY OP_CHECKSIG'
        self.assertEqual(actualDD['locktime'], 0)
        self.assertEqual(actualDD['version'], 1)
        self.assertEqual(actualDD['vin'][0]['sequence'], 4294967295L)
        self.assertEqual(actualDD['vin'][0]['scriptSig']['hex'], '')
        self.assertEqual(actualDD['vin'][0]['scriptSig']['asm'], '')
        self.assertEqual(actualDD['vin'][0]['vout'], 1201)
        self.assertEqual(
            actualDD['vin'][0]['txid'],
            'e450dc7394f8432d89c68d0df6a5506cb81eac60c977bfc7932633aaf835a31f')
        self.assertEqual(actualDD['vin'][1]['vout'], 294)
        self.assertEqual(
            actualDD['vin'][1]['txid'],
            '8867f0f84e80588ed00a05e604487442546ef42ab4c93445a09b00a6d487e74b')
        self.assertEqual(actualDD['vout'][0]['value'], 0.0001944)
        self.assertEqual(actualDD['vout'][0]['n'], 0)
        self.assertEqual(actualDD['vout'][0]['scriptPubKey']['reqSigs'], 1)
        self.assertEqual(actualDD['vout'][0]['scriptPubKey']['hex'],
                         '76a914be17ec0fc1f8aa029223dbe5f53109d0faf8c79788ac')
        self.assertEqual(actualDD['vout'][0]['scriptPubKey']['addresses'],
                         ['mxr5Le3bt7dfbFqmpK6saUYPt5xtcDB7Yw'])
        self.assertEqual(actualDD['vout'][0]['scriptPubKey']['asm'],
                         expectScriptStr)
        self.assertEqual(actualDD['vout'][0]['scriptPubKey']['type'],
                         'Standard (PKH)')
        self.assertEqual(actualDD['vout'][1]['scriptPubKey']['type'],
                         'Standard (PKH)')
        self.assertEqual(actualDD['vout'][2]['scriptPubKey']['type'],
                         'Non-Standard')

    def testDumpprivkey(self):

        testPrivKey = self.privKey.toBinStr()
        hash160 = convertKeyDataToAddress(testPrivKey)
        addr58 = hash160_to_addrStr(hash160)

        # Verify that a bogus addrss Raises InvalidBitcoinAddress Exception
        self.assertRaises(InvalidBitcoinAddress,
                          self.jsonServer.jsonrpc_dumpprivkey, 'bogus')

        # verify that the root private key is not found
        self.assertRaises(PrivateKeyNotFound,
                          self.jsonServer.jsonrpc_dumpprivkey, addr58)

        # verify that the first private key can be found
        firstHash160 = self.wallet.getNextUnusedAddress().getAddr160()
        firstAddr58 = hash160_to_addrStr(firstHash160)
        actualPrivateKey = self.jsonServer.jsonrpc_dumpprivkey(firstAddr58)
        expectedPrivateKey = self.wallet.getAddrByHash160(
            firstHash160).serializePlainPrivateKey()
        self.assertEqual(actualPrivateKey, expectedPrivateKey)

        # Verify that a locked wallet Raises WalletUnlockNeeded Exception
        kdfParams = self.wallet.computeSystemSpecificKdfParams(0.1)
        self.wallet.changeKdfParams(*kdfParams)
        self.wallet.changeWalletEncryption(securePassphrase=self.passphrase)
        self.wallet.lock()
        self.assertRaises(WalletUnlockNeeded,
                          self.jsonServer.jsonrpc_dumpprivkey, addr58)

    def testEncryptwallet(self):
        kdfParams = self.wallet.computeSystemSpecificKdfParams(0.1)
        self.wallet.changeKdfParams(*kdfParams)
        self.jsonServer.jsonrpc_encryptwallet(PASSPHRASE1)
        self.assertTrue(self.wallet.isLocked)

        # Verify that a locked wallet Raises WalletUnlockNeeded Exception
        self.assertRaises(WalletUnlockNeeded,
                          self.jsonServer.jsonrpc_encryptwallet, PASSPHRASE1)

    def testUnlockwallet(self):
        kdfParams = self.wallet.computeSystemSpecificKdfParams(0.1)
        self.wallet.changeKdfParams(*kdfParams)
        self.jsonServer.jsonrpc_encryptwallet(PASSPHRASE1)
        self.assertTrue(self.wallet.isLocked)
        self.jsonServer.jsonrpc_unlockwallet(PASSPHRASE1, UNLOCK_TIMEOUT)
        self.assertFalse(self.wallet.isLocked)
        time.sleep(UNLOCK_TIMEOUT + 1)
        self.wallet.checkWalletLockTimeout()
        self.assertTrue(self.wallet.isLocked)

    def testGetWalletInfo(self):
        wltInfo = self.jsonServer.jsonrpc_getwalletinfo()
        self.assertEqual(wltInfo['name'], TEST_WALLET_NAME)
        self.assertEqual(wltInfo['description'], TEST_WALLET_DESCRIPTION)
        self.assertEqual(wltInfo['balance'],
                         AmountToJSON(self.wallet.getBalance('Spend')))
        self.assertEqual(wltInfo['keypoolsize'], self.wallet.addrPoolSize)
        self.assertEqual(wltInfo['numaddrgen'], len(self.wallet.addrMap))
        self.assertEqual(wltInfo['highestusedindex'],
                         self.wallet.highestUsedChainIndex)

    # This should always return 0 balance
    # Need to create our own test net to test with balances
    def testGetBalance(self):
        for ballanceType in ['spendable','spend', 'unconf', \
                             'unconfirmed', 'total', 'ultimate','unspent', 'full']:
            self.assertEqual(
                self.jsonServer.jsonrpc_getbalance(ballanceType),
                AmountToJSON(self.wallet.getBalance(ballanceType)))
        self.assertEqual(self.jsonServer.jsonrpc_getbalance('bogus'), -1)
コード例 #16
0
ファイル: ArmoryDTest.py プロジェクト: 007pig/BitcoinArmory
class ArmoryDTest(unittest.TestCase):      
   def removeFileList(self, fileList):
      for f in fileList:
         if os.path.exists(f):
            os.remove(f)
            
   @classmethod
   def setUpClass(self):
      # This is not a UI so no need to worry about the main thread being blocked.
      # Any UI that uses this Daemon can put the call to the Daemon on it's own thread.
      TheBDM.Reset()
      TheBDM.setBlocking(True)
      TheBDM.setOnlineMode(True)
      while not TheBDM.getBDMState()=='BlockchainReady':
         time.sleep(2)

   def setUp(self):
      self.fileA    = os.path.join(ARMORY_HOME_DIR, 'armory_%s_.wallet' % TEST_WALLET_ID)
      self.fileB    = os.path.join(ARMORY_HOME_DIR, 'armory_%s_backup.wallet' % TEST_WALLET_ID)
      self.fileAupd = os.path.join(ARMORY_HOME_DIR, 'armory_%s_backup_unsuccessful.wallet' % TEST_WALLET_ID)
      self.fileBupd = os.path.join(ARMORY_HOME_DIR, 'armory_%s_update_unsuccessful.wallet' % TEST_WALLET_ID)

      self.removeFileList([self.fileA, self.fileB, self.fileAupd, self.fileBupd])
   
      # We need a controlled test, so we script the all the normally-random stuff
      self.privKey   = SecureBinaryData('\xaa'*32)
      self.privKey2  = SecureBinaryData('\x33'*32)
      self.chainstr  = SecureBinaryData('\xee'*32)
      theIV     = SecureBinaryData(hex_to_binary('77'*16))
      self.passphrase  = SecureBinaryData('A self.passphrase')
      self.passphrase2 = SecureBinaryData('A new self.passphrase')
      
      self.wallet = PyBtcWallet().createNewWallet(withEncrypt=False, \
                                          plainRootKey=self.privKey, \
                                          chaincode=self.chainstr,   \
                                          IV=theIV, \
                                          shortLabel=TEST_WALLET_NAME, \
                                          longLabel=TEST_WALLET_DESCRIPTION)
      self.jsonServer = Armory_Json_Rpc_Server(self.wallet)
      TheBDM.registerWallet(self.wallet)
      
   def tearDown(self):
      self.removeFileList([self.fileA, self.fileB, self.fileAupd, self.fileBupd])
   

   # Can't test with actual transactions in this environment. See ARMORY-34.
   # This wallet has no txs
   # def testListunspent(self):
   #    actualResult = self.jsonServer.jsonrpc_listunspent()
   #    self.assertEqual(actualResult, [])
      
   def testImportprivkey(self):
      originalLength = len(self.wallet.linearAddr160List)
      self.jsonServer.jsonrpc_importprivkey(self.privKey2)
      self.assertEqual(len(self.wallet.linearAddr160List), originalLength+1)
      
   def testGettxout(self):
      txOut = self.jsonServer.jsonrpc_gettxout(TX_ID1, 0)
      self.assertEquals(TX_ID1_OUTPUT0_VALUE, txOut.value)
      txOut = self.jsonServer.jsonrpc_gettxout(TX_ID1, 1)
      self.assertEquals(TX_ID1_OUTPUT1_VALUE, txOut.value)
         
   # Cannot unit test actual balances. Only verify that getreceivedbyaddress return a 0 result.
   def testGetreceivedbyaddress(self):
      a160 = hash160(self.wallet.getNextUnusedAddress().binPublicKey65.toBinStr())
      testAddr = hash160_to_addrStr(a160)
      result = self.jsonServer.jsonrpc_getreceivedbyaddress(testAddr)
      self.assertEqual(result, 0)
      
   def testGetrawtransaction(self):
      actualRawTx = self.jsonServer.jsonrpc_getrawtransaction(TX_ID1)
      pyTx = PyTx().unserialize(hex_to_binary(actualRawTx))
      self.assertEquals(TX_ID1, binary_to_hex(pyTx.getHash(), BIGENDIAN))

   def testBackupWallet(self):
      backupTestPath = os.path.join(ARMORY_HOME_DIR, 'armory_%s_.wallet.backup.test' % TEST_WALLET_ID)
      # Remove backupTestPath in case it exists
      backupFileList = [backupTestPath, self.fileB]
      self.removeFileList(backupFileList)
      # Remove the backup test path that is to be created after tear down.
      self.addCleanup(self.removeFileList, backupFileList)
      self.jsonServer.jsonrpc_backupwallet(backupTestPath)
      self.assertTrue(os.path.exists(backupTestPath))
      self.wallet.backupWalletFile()
      self.assertTrue(os.path.exists(self.fileB))
      
   def testDecoderawtransaction(self):
      actualDD = self.jsonServer.jsonrpc_decoderawtransaction(RAW_TX1)
      # Test specific values pulled from bitcoin daemon's output for the test raw TX
      expectScriptStr = 'OP_DUP OP_HASH160 PUSHDATA(20) [be17ec0fc1f8aa029223dbe5f53109d0faf8c797] OP_EQUALVERIFY OP_CHECKSIG'
      self.assertEqual(actualDD['locktime'], 0)
      self.assertEqual(actualDD['version'], 1)
      self.assertEqual(actualDD['vin'][0]['sequence'], 4294967295L)
      self.assertEqual(actualDD['vin'][0]['scriptSig']['hex'], '')
      self.assertEqual(actualDD['vin'][0]['scriptSig']['asm'], '')
      self.assertEqual(actualDD['vin'][0]['vout'], 1201)
      self.assertEqual(actualDD['vin'][0]['txid'], 'e450dc7394f8432d89c68d0df6a5506cb81eac60c977bfc7932633aaf835a31f')
      self.assertEqual(actualDD['vin'][1]['vout'], 294)
      self.assertEqual(actualDD['vin'][1]['txid'], '8867f0f84e80588ed00a05e604487442546ef42ab4c93445a09b00a6d487e74b')
      self.assertEqual(actualDD['vout'][0]['value'], 0.0001944)
      self.assertEqual(actualDD['vout'][0]['n'], 0)
      self.assertEqual(actualDD['vout'][0]['scriptPubKey']['reqSigs'], 1)
      self.assertEqual(actualDD['vout'][0]['scriptPubKey']['hex'], '76a914be17ec0fc1f8aa029223dbe5f53109d0faf8c79788ac')
      self.assertEqual(actualDD['vout'][0]['scriptPubKey']['addresses'], ['mxr5Le3bt7dfbFqmpK6saUYPt5xtcDB7Yw'])
      self.assertEqual(actualDD['vout'][0]['scriptPubKey']['asm'], expectScriptStr)
      self.assertEqual(actualDD['vout'][0]['scriptPubKey']['type'], 'Standard (PKH)')
      self.assertEqual(actualDD['vout'][1]['scriptPubKey']['type'], 'Standard (PKH)')
      self.assertEqual(actualDD['vout'][2]['scriptPubKey']['type'], 'Non-Standard')
      
      
   def testDumpprivkey(self):

      testPrivKey = self.privKey.toBinStr()
      hash160 = convertKeyDataToAddress(testPrivKey)
      addr58 = hash160_to_addrStr(hash160)
      
      # Verify that a bogus addrss Raises InvalidBitcoinAddress Exception
      self.assertRaises(InvalidBitcoinAddress, self.jsonServer.jsonrpc_dumpprivkey, 'bogus')
      
      # verify that the root private key is not found
      self.assertRaises(PrivateKeyNotFound, self.jsonServer.jsonrpc_dumpprivkey, addr58)
      
      # verify that the first private key can be found
      firstHash160 = self.wallet.getNextUnusedAddress().getAddr160()
      firstAddr58 = hash160_to_addrStr(firstHash160)
      actualPrivateKey = self.jsonServer.jsonrpc_dumpprivkey(firstAddr58)
      expectedPrivateKey = self.wallet.getAddrByHash160(firstHash160).serializePlainPrivateKey()
      self.assertEqual(actualPrivateKey, expectedPrivateKey)
      
      # Verify that a locked wallet Raises WalletUnlockNeeded Exception
      kdfParams = self.wallet.computeSystemSpecificKdfParams(0.1)
      self.wallet.changeKdfParams(*kdfParams)
      self.wallet.changeWalletEncryption( securePassphrase=self.passphrase )
      self.wallet.lock()
      self.assertRaises(WalletUnlockNeeded, self.jsonServer.jsonrpc_dumpprivkey, addr58)

   def testEncryptwallet(self):
      kdfParams = self.wallet.computeSystemSpecificKdfParams(0.1)
      self.wallet.changeKdfParams(*kdfParams)
      self.jsonServer.jsonrpc_encryptwallet(PASSPHRASE1)
      self.assertTrue(self.wallet.isLocked)
      
      # Verify that a locked wallet Raises WalletUnlockNeeded Exception
      self.assertRaises(WalletUnlockNeeded, self.jsonServer.jsonrpc_encryptwallet, PASSPHRASE1)
      
   def testUnlockwallet(self):
      kdfParams = self.wallet.computeSystemSpecificKdfParams(0.1)
      self.wallet.changeKdfParams(*kdfParams)
      self.jsonServer.jsonrpc_encryptwallet(PASSPHRASE1)
      self.assertTrue(self.wallet.isLocked)
      self.jsonServer.jsonrpc_unlockwallet(PASSPHRASE1, UNLOCK_TIMEOUT)
      self.assertFalse(self.wallet.isLocked)
      time.sleep(UNLOCK_TIMEOUT+1)
      self.wallet.checkWalletLockTimeout()
      self.assertTrue(self.wallet.isLocked)
      
   def testGetWalletInfo(self):
      wltInfo = self.jsonServer.jsonrpc_getwalletinfo()
      self.assertEqual(wltInfo['name'], TEST_WALLET_NAME)
      self.assertEqual(wltInfo['description'], TEST_WALLET_DESCRIPTION)
      self.assertEqual(wltInfo['balance'], AmountToJSON(self.wallet.getBalance('Spend')))
      self.assertEqual(wltInfo['keypoolsize'], self.wallet.addrPoolSize)
      self.assertEqual(wltInfo['numaddrgen'], len(self.wallet.addrMap))
      self.assertEqual(wltInfo['highestusedindex'], self.wallet.highestUsedChainIndex)
   
   # This should always return 0 balance
   # Need to create our own test net to test with balances
   def testGetBalance(self):
      for ballanceType in ['spendable','spend', 'unconf', \
                           'unconfirmed', 'total', 'ultimate','unspent', 'full']:
         self.assertEqual(self.jsonServer.jsonrpc_getbalance(ballanceType),
                          AmountToJSON(self.wallet.getBalance(ballanceType)))
      self.assertEqual(self.jsonServer.jsonrpc_getbalance('bogus'), -1)