src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
BridgeSupport { public boolean increaseLockingCap(Transaction tx, Coin newCap) { AddressBasedAuthorizer authorizer = bridgeConstants.getIncreaseLockingCapAuthorizer(); if (!authorizer.isAuthorized(tx)) { logger.warn("not authorized address tried to increase locking cap. Address: {}", tx.getSender()); return false; } Coin currentLockingCap = this.getLockingCap(); if (newCap.compareTo(currentLockingCap) < 0) { logger.warn("attempted value doesn't increase locking cap. Attempted: {}", newCap.value); return false; } Coin maxLockingCap = currentLockingCap.multiply(bridgeConstants.getLockingCapIncrementsMultiplier()); if (newCap.compareTo(maxLockingCap) > 0) { logger.warn("attempted value increases locking cap above its limit. Attempted: {}", newCap.value); return false; } logger.info("increased locking cap: {}", newCap.value); this.provider.setLockingCap(newCap); return true; } BridgeSupport(
BridgeConstants bridgeConstants,
BridgeStorageProvider provider,
BridgeEventLogger eventLogger,
BtcLockSenderProvider btcLockSenderProvider,
Repository repository,
Block executionBlock,
Context btcContext,
FederationSupport federationSupport,
BtcBlockStoreWithCache.Factory btcBlockStoreFactory,
ActivationConfig.ForBlock activations); List<ProgramSubtrace> getSubtraces(); void save(); void receiveHeaders(BtcBlock[] headers); Wallet getActiveFederationWallet(); Wallet getRetiringFederationWallet(); Wallet getUTXOBasedWalletForLiveFederations(List<UTXO> utxos); Wallet getNoSpendWalletForLiveFederations(); void registerBtcTransaction(Transaction rskTx, byte[] btcTxSerialized, int height, byte[] pmtSerialized); void releaseBtc(Transaction rskTx); Coin getFeePerKb(); void updateCollections(Transaction rskTx); void addSignature(BtcECKey federatorPublicKey, List<byte[]> signatures, byte[] rskTxHash); byte[] getStateForBtcReleaseClient(); byte[] getStateForDebugging(); int getBtcBlockchainBestChainHeight(); int getBtcBlockchainInitialBlockHeight(); @Deprecated List<Sha256Hash> getBtcBlockchainBlockLocator(); Sha256Hash getBtcBlockchainBlockHashAtDepth(int depth); Long getBtcTransactionConfirmationsGetCost(Object[] args); Integer getBtcTransactionConfirmations(Sha256Hash btcTxHash, Sha256Hash btcBlockHash, MerkleBranch merkleBranch); Boolean isBtcTxHashAlreadyProcessed(Sha256Hash btcTxHash); Long getBtcTxHashProcessedHeight(Sha256Hash btcTxHash); boolean isAlreadyBtcTxHashProcessed(Sha256Hash btcTxHash); Federation getActiveFederation(); @Nullable Federation getRetiringFederation(); Address getFederationAddress(); Integer getFederationSize(); Integer getFederationThreshold(); byte[] getFederatorPublicKey(int index); byte[] getFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getFederationCreationTime(); long getFederationCreationBlockNumber(); Address getRetiringFederationAddress(); Integer getRetiringFederationSize(); Integer getRetiringFederationThreshold(); byte[] getRetiringFederatorPublicKey(int index); byte[] getRetiringFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getRetiringFederationCreationTime(); long getRetiringFederationCreationBlockNumber(); Integer voteFederationChange(Transaction tx, ABICallSpec callSpec); byte[] getPendingFederationHash(); Integer getPendingFederationSize(); byte[] getPendingFederatorPublicKey(int index); byte[] getPendingFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Integer getLockWhitelistSize(); LockWhitelistEntry getLockWhitelistEntryByIndex(int index); LockWhitelistEntry getLockWhitelistEntryByAddress(String addressBase58); Integer addOneOffLockWhitelistAddress(Transaction tx, String addressBase58, BigInteger maxTransferValue); Integer addUnlimitedLockWhitelistAddress(Transaction tx, String addressBase58); Integer removeLockWhitelistAddress(Transaction tx, String addressBase58); Coin getMinimumLockTxValue(); Integer voteFeePerKbChange(Transaction tx, Coin feePerKb); Integer setLockWhitelistDisableBlockDelay(Transaction tx, BigInteger disableBlockDelayBI); Coin getLockingCap(); boolean increaseLockingCap(Transaction tx, Coin newCap); void registerBtcCoinbaseTransaction(byte[] btcTxSerialized, Sha256Hash blockHash, byte[] pmtSerialized, Sha256Hash witnessMerkleRoot, byte[] witnessReservedValue); boolean hasBtcBlockCoinbaseTransactionInformation(Sha256Hash blockHash); static final RskAddress BURN_ADDRESS; static final int MAX_RELEASE_ITERATIONS; static final Integer FEDERATION_CHANGE_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_INVALID_ADDRESS_FORMAT_ERROR_CODE; static final Integer LOCK_WHITELIST_ALREADY_EXISTS_ERROR_CODE; static final Integer LOCK_WHITELIST_UNKNOWN_ERROR_CODE; static final Integer LOCK_WHITELIST_SUCCESS_CODE; static final Integer FEE_PER_KB_GENERIC_ERROR_CODE; static final Integer NEGATIVE_FEE_PER_KB_ERROR_CODE; static final Integer EXCESSIVE_FEE_PER_KB_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INEXISTENT_BLOCK_HASH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_NOT_IN_BEST_CHAIN_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INCONSISTENT_BLOCK_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_TOO_OLD_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INVALID_MERKLE_BRANCH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_MAX_DEPTH; } | @Test public void increaseLockingCap_unauthorized() { AddressBasedAuthorizer authorizer = mock(AddressBasedAuthorizer.class); when(authorizer.isAuthorized(any(Transaction.class))).thenReturn(false); BridgeConstants constants = mock(BridgeConstants.class); when(constants.getIncreaseLockingCapAuthorizer()).thenReturn(authorizer); BridgeSupport bridgeSupport = getBridgeSupport(constants, mock(BridgeStorageProvider.class), ActivationConfigsForTest.all().forBlock(0)); assertFalse(bridgeSupport.increaseLockingCap(mock(Transaction.class), Coin.SATOSHI)); }
@Test public void increaseLockingCap() { Coin lastValue = Coin.COIN; BridgeStorageProvider provider = mock(BridgeStorageProvider.class); when(provider.getLockingCap()).thenReturn(lastValue); AddressBasedAuthorizer authorizer = mock(AddressBasedAuthorizer.class); when(authorizer.isAuthorized(any(Transaction.class))).thenReturn(true); BridgeConstants constants = mock(BridgeConstants.class); when(constants.getIncreaseLockingCapAuthorizer()).thenReturn(authorizer); int multiplier = 2; when(constants.getLockingCapIncrementsMultiplier()).thenReturn(multiplier); BridgeSupport bridgeSupport = getBridgeSupport(constants, provider, ActivationConfigsForTest.all().forBlock(0)); assertTrue(bridgeSupport.increaseLockingCap(mock(Transaction.class), lastValue)); assertTrue(bridgeSupport.increaseLockingCap(mock(Transaction.class), lastValue.plus(Coin.SATOSHI))); assertTrue(bridgeSupport.increaseLockingCap(mock(Transaction.class), lastValue.plus(Coin.CENT))); assertTrue(bridgeSupport.increaseLockingCap(mock(Transaction.class), lastValue.multiply(multiplier))); } |
BridgeSupport { public Boolean isBtcTxHashAlreadyProcessed(Sha256Hash btcTxHash) throws IOException { return provider.getHeightIfBtcTxhashIsAlreadyProcessed(btcTxHash).isPresent(); } BridgeSupport(
BridgeConstants bridgeConstants,
BridgeStorageProvider provider,
BridgeEventLogger eventLogger,
BtcLockSenderProvider btcLockSenderProvider,
Repository repository,
Block executionBlock,
Context btcContext,
FederationSupport federationSupport,
BtcBlockStoreWithCache.Factory btcBlockStoreFactory,
ActivationConfig.ForBlock activations); List<ProgramSubtrace> getSubtraces(); void save(); void receiveHeaders(BtcBlock[] headers); Wallet getActiveFederationWallet(); Wallet getRetiringFederationWallet(); Wallet getUTXOBasedWalletForLiveFederations(List<UTXO> utxos); Wallet getNoSpendWalletForLiveFederations(); void registerBtcTransaction(Transaction rskTx, byte[] btcTxSerialized, int height, byte[] pmtSerialized); void releaseBtc(Transaction rskTx); Coin getFeePerKb(); void updateCollections(Transaction rskTx); void addSignature(BtcECKey federatorPublicKey, List<byte[]> signatures, byte[] rskTxHash); byte[] getStateForBtcReleaseClient(); byte[] getStateForDebugging(); int getBtcBlockchainBestChainHeight(); int getBtcBlockchainInitialBlockHeight(); @Deprecated List<Sha256Hash> getBtcBlockchainBlockLocator(); Sha256Hash getBtcBlockchainBlockHashAtDepth(int depth); Long getBtcTransactionConfirmationsGetCost(Object[] args); Integer getBtcTransactionConfirmations(Sha256Hash btcTxHash, Sha256Hash btcBlockHash, MerkleBranch merkleBranch); Boolean isBtcTxHashAlreadyProcessed(Sha256Hash btcTxHash); Long getBtcTxHashProcessedHeight(Sha256Hash btcTxHash); boolean isAlreadyBtcTxHashProcessed(Sha256Hash btcTxHash); Federation getActiveFederation(); @Nullable Federation getRetiringFederation(); Address getFederationAddress(); Integer getFederationSize(); Integer getFederationThreshold(); byte[] getFederatorPublicKey(int index); byte[] getFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getFederationCreationTime(); long getFederationCreationBlockNumber(); Address getRetiringFederationAddress(); Integer getRetiringFederationSize(); Integer getRetiringFederationThreshold(); byte[] getRetiringFederatorPublicKey(int index); byte[] getRetiringFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getRetiringFederationCreationTime(); long getRetiringFederationCreationBlockNumber(); Integer voteFederationChange(Transaction tx, ABICallSpec callSpec); byte[] getPendingFederationHash(); Integer getPendingFederationSize(); byte[] getPendingFederatorPublicKey(int index); byte[] getPendingFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Integer getLockWhitelistSize(); LockWhitelistEntry getLockWhitelistEntryByIndex(int index); LockWhitelistEntry getLockWhitelistEntryByAddress(String addressBase58); Integer addOneOffLockWhitelistAddress(Transaction tx, String addressBase58, BigInteger maxTransferValue); Integer addUnlimitedLockWhitelistAddress(Transaction tx, String addressBase58); Integer removeLockWhitelistAddress(Transaction tx, String addressBase58); Coin getMinimumLockTxValue(); Integer voteFeePerKbChange(Transaction tx, Coin feePerKb); Integer setLockWhitelistDisableBlockDelay(Transaction tx, BigInteger disableBlockDelayBI); Coin getLockingCap(); boolean increaseLockingCap(Transaction tx, Coin newCap); void registerBtcCoinbaseTransaction(byte[] btcTxSerialized, Sha256Hash blockHash, byte[] pmtSerialized, Sha256Hash witnessMerkleRoot, byte[] witnessReservedValue); boolean hasBtcBlockCoinbaseTransactionInformation(Sha256Hash blockHash); static final RskAddress BURN_ADDRESS; static final int MAX_RELEASE_ITERATIONS; static final Integer FEDERATION_CHANGE_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_INVALID_ADDRESS_FORMAT_ERROR_CODE; static final Integer LOCK_WHITELIST_ALREADY_EXISTS_ERROR_CODE; static final Integer LOCK_WHITELIST_UNKNOWN_ERROR_CODE; static final Integer LOCK_WHITELIST_SUCCESS_CODE; static final Integer FEE_PER_KB_GENERIC_ERROR_CODE; static final Integer NEGATIVE_FEE_PER_KB_ERROR_CODE; static final Integer EXCESSIVE_FEE_PER_KB_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INEXISTENT_BLOCK_HASH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_NOT_IN_BEST_CHAIN_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INCONSISTENT_BLOCK_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_TOO_OLD_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INVALID_MERKLE_BRANCH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_MAX_DEPTH; } | @Test public void isBtcTxHashAlreadyProcessed() throws IOException { BridgeConstants bridgeConstants = BridgeRegTestConstants.getInstance(); ActivationConfig.ForBlock activations = ActivationConfigsForTest.all().forBlock(0l); Sha256Hash hash1 = Sha256Hash.ZERO_HASH; Sha256Hash hash2 = Sha256Hash.wrap("0000000000000000000000000000000000000000000000000000000000000001"); BridgeStorageProvider bridgeStorageProvider = mock(BridgeStorageProvider.class); when(bridgeStorageProvider.getHeightIfBtcTxhashIsAlreadyProcessed(hash1)).thenReturn(Optional.of(1l)); BridgeSupport bridgeSupport = getBridgeSupport(bridgeConstants, bridgeStorageProvider, activations); assertTrue(bridgeSupport.isBtcTxHashAlreadyProcessed(hash1)); assertFalse(bridgeSupport.isBtcTxHashAlreadyProcessed(hash2)); } |
BridgeSupport { public Long getBtcTxHashProcessedHeight(Sha256Hash btcTxHash) throws IOException { return provider.getHeightIfBtcTxhashIsAlreadyProcessed(btcTxHash).orElse(-1L); } BridgeSupport(
BridgeConstants bridgeConstants,
BridgeStorageProvider provider,
BridgeEventLogger eventLogger,
BtcLockSenderProvider btcLockSenderProvider,
Repository repository,
Block executionBlock,
Context btcContext,
FederationSupport federationSupport,
BtcBlockStoreWithCache.Factory btcBlockStoreFactory,
ActivationConfig.ForBlock activations); List<ProgramSubtrace> getSubtraces(); void save(); void receiveHeaders(BtcBlock[] headers); Wallet getActiveFederationWallet(); Wallet getRetiringFederationWallet(); Wallet getUTXOBasedWalletForLiveFederations(List<UTXO> utxos); Wallet getNoSpendWalletForLiveFederations(); void registerBtcTransaction(Transaction rskTx, byte[] btcTxSerialized, int height, byte[] pmtSerialized); void releaseBtc(Transaction rskTx); Coin getFeePerKb(); void updateCollections(Transaction rskTx); void addSignature(BtcECKey federatorPublicKey, List<byte[]> signatures, byte[] rskTxHash); byte[] getStateForBtcReleaseClient(); byte[] getStateForDebugging(); int getBtcBlockchainBestChainHeight(); int getBtcBlockchainInitialBlockHeight(); @Deprecated List<Sha256Hash> getBtcBlockchainBlockLocator(); Sha256Hash getBtcBlockchainBlockHashAtDepth(int depth); Long getBtcTransactionConfirmationsGetCost(Object[] args); Integer getBtcTransactionConfirmations(Sha256Hash btcTxHash, Sha256Hash btcBlockHash, MerkleBranch merkleBranch); Boolean isBtcTxHashAlreadyProcessed(Sha256Hash btcTxHash); Long getBtcTxHashProcessedHeight(Sha256Hash btcTxHash); boolean isAlreadyBtcTxHashProcessed(Sha256Hash btcTxHash); Federation getActiveFederation(); @Nullable Federation getRetiringFederation(); Address getFederationAddress(); Integer getFederationSize(); Integer getFederationThreshold(); byte[] getFederatorPublicKey(int index); byte[] getFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getFederationCreationTime(); long getFederationCreationBlockNumber(); Address getRetiringFederationAddress(); Integer getRetiringFederationSize(); Integer getRetiringFederationThreshold(); byte[] getRetiringFederatorPublicKey(int index); byte[] getRetiringFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getRetiringFederationCreationTime(); long getRetiringFederationCreationBlockNumber(); Integer voteFederationChange(Transaction tx, ABICallSpec callSpec); byte[] getPendingFederationHash(); Integer getPendingFederationSize(); byte[] getPendingFederatorPublicKey(int index); byte[] getPendingFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Integer getLockWhitelistSize(); LockWhitelistEntry getLockWhitelistEntryByIndex(int index); LockWhitelistEntry getLockWhitelistEntryByAddress(String addressBase58); Integer addOneOffLockWhitelistAddress(Transaction tx, String addressBase58, BigInteger maxTransferValue); Integer addUnlimitedLockWhitelistAddress(Transaction tx, String addressBase58); Integer removeLockWhitelistAddress(Transaction tx, String addressBase58); Coin getMinimumLockTxValue(); Integer voteFeePerKbChange(Transaction tx, Coin feePerKb); Integer setLockWhitelistDisableBlockDelay(Transaction tx, BigInteger disableBlockDelayBI); Coin getLockingCap(); boolean increaseLockingCap(Transaction tx, Coin newCap); void registerBtcCoinbaseTransaction(byte[] btcTxSerialized, Sha256Hash blockHash, byte[] pmtSerialized, Sha256Hash witnessMerkleRoot, byte[] witnessReservedValue); boolean hasBtcBlockCoinbaseTransactionInformation(Sha256Hash blockHash); static final RskAddress BURN_ADDRESS; static final int MAX_RELEASE_ITERATIONS; static final Integer FEDERATION_CHANGE_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_INVALID_ADDRESS_FORMAT_ERROR_CODE; static final Integer LOCK_WHITELIST_ALREADY_EXISTS_ERROR_CODE; static final Integer LOCK_WHITELIST_UNKNOWN_ERROR_CODE; static final Integer LOCK_WHITELIST_SUCCESS_CODE; static final Integer FEE_PER_KB_GENERIC_ERROR_CODE; static final Integer NEGATIVE_FEE_PER_KB_ERROR_CODE; static final Integer EXCESSIVE_FEE_PER_KB_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INEXISTENT_BLOCK_HASH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_NOT_IN_BEST_CHAIN_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INCONSISTENT_BLOCK_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_TOO_OLD_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INVALID_MERKLE_BRANCH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_MAX_DEPTH; } | @Test public void getBtcTxHashProcessedHeight() throws IOException { BridgeConstants bridgeConstants = BridgeRegTestConstants.getInstance(); ActivationConfig.ForBlock activations = ActivationConfigsForTest.all().forBlock(0l); Sha256Hash hash1 = Sha256Hash.ZERO_HASH; Sha256Hash hash2 = Sha256Hash.wrap("0000000000000000000000000000000000000000000000000000000000000001"); BridgeStorageProvider bridgeStorageProvider = mock(BridgeStorageProvider.class); when(bridgeStorageProvider.getHeightIfBtcTxhashIsAlreadyProcessed(hash1)).thenReturn(Optional.of(1l)); BridgeSupport bridgeSupport = getBridgeSupport(bridgeConstants, bridgeStorageProvider, activations); assertEquals(Long.valueOf(1), bridgeSupport.getBtcTxHashProcessedHeight(hash1)); assertEquals(Long.valueOf(-1), bridgeSupport.getBtcTxHashProcessedHeight(hash2)); } |
BridgeSupport { public void registerBtcTransaction(Transaction rskTx, byte[] btcTxSerialized, int height, byte[] pmtSerialized) throws IOException, BlockStoreException { Context.propagate(btcContext); Sha256Hash btcTxHash = BtcTransactionFormatUtils.calculateBtcTxHash(btcTxSerialized); try { if (isAlreadyBtcTxHashProcessed(btcTxHash)) { throw new RegisterBtcTransactionException("Transaction already processed"); } if (!validationsForRegisterBtcTransaction(btcTxHash, height, pmtSerialized, btcTxSerialized)) { throw new RegisterBtcTransactionException("Could not validate transaction"); } BtcTransaction btcTx = new BtcTransaction(bridgeConstants.getBtcParams(), btcTxSerialized); btcTx.verify(); if (isAlreadyBtcTxHashProcessed(btcTx.getHash(false))) { throw new RegisterBtcTransactionException("Transaction already processed"); } switch (getTransactionType(btcTx)) { case PEGIN: processPegIn(btcTx, rskTx, height, btcTxHash); break; case PEGOUT: processRelease(btcTx, btcTxHash); break; case MIGRATION: processMigration(btcTx, btcTxHash); break; default: logger.warn("[registerBtcTransaction] This is not a lock, a release nor a migration tx {}", btcTx); panicProcessor.panic("btclock", "This is not a lock, a release nor a migration tx " + btcTx); } } catch (RegisterBtcTransactionException e) { logger.warn("[registerBtcTransaction] Could not register transaction {}. Message: {}", btcTxHash, e.getMessage()); } } BridgeSupport(
BridgeConstants bridgeConstants,
BridgeStorageProvider provider,
BridgeEventLogger eventLogger,
BtcLockSenderProvider btcLockSenderProvider,
Repository repository,
Block executionBlock,
Context btcContext,
FederationSupport federationSupport,
BtcBlockStoreWithCache.Factory btcBlockStoreFactory,
ActivationConfig.ForBlock activations); List<ProgramSubtrace> getSubtraces(); void save(); void receiveHeaders(BtcBlock[] headers); Wallet getActiveFederationWallet(); Wallet getRetiringFederationWallet(); Wallet getUTXOBasedWalletForLiveFederations(List<UTXO> utxos); Wallet getNoSpendWalletForLiveFederations(); void registerBtcTransaction(Transaction rskTx, byte[] btcTxSerialized, int height, byte[] pmtSerialized); void releaseBtc(Transaction rskTx); Coin getFeePerKb(); void updateCollections(Transaction rskTx); void addSignature(BtcECKey federatorPublicKey, List<byte[]> signatures, byte[] rskTxHash); byte[] getStateForBtcReleaseClient(); byte[] getStateForDebugging(); int getBtcBlockchainBestChainHeight(); int getBtcBlockchainInitialBlockHeight(); @Deprecated List<Sha256Hash> getBtcBlockchainBlockLocator(); Sha256Hash getBtcBlockchainBlockHashAtDepth(int depth); Long getBtcTransactionConfirmationsGetCost(Object[] args); Integer getBtcTransactionConfirmations(Sha256Hash btcTxHash, Sha256Hash btcBlockHash, MerkleBranch merkleBranch); Boolean isBtcTxHashAlreadyProcessed(Sha256Hash btcTxHash); Long getBtcTxHashProcessedHeight(Sha256Hash btcTxHash); boolean isAlreadyBtcTxHashProcessed(Sha256Hash btcTxHash); Federation getActiveFederation(); @Nullable Federation getRetiringFederation(); Address getFederationAddress(); Integer getFederationSize(); Integer getFederationThreshold(); byte[] getFederatorPublicKey(int index); byte[] getFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getFederationCreationTime(); long getFederationCreationBlockNumber(); Address getRetiringFederationAddress(); Integer getRetiringFederationSize(); Integer getRetiringFederationThreshold(); byte[] getRetiringFederatorPublicKey(int index); byte[] getRetiringFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getRetiringFederationCreationTime(); long getRetiringFederationCreationBlockNumber(); Integer voteFederationChange(Transaction tx, ABICallSpec callSpec); byte[] getPendingFederationHash(); Integer getPendingFederationSize(); byte[] getPendingFederatorPublicKey(int index); byte[] getPendingFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Integer getLockWhitelistSize(); LockWhitelistEntry getLockWhitelistEntryByIndex(int index); LockWhitelistEntry getLockWhitelistEntryByAddress(String addressBase58); Integer addOneOffLockWhitelistAddress(Transaction tx, String addressBase58, BigInteger maxTransferValue); Integer addUnlimitedLockWhitelistAddress(Transaction tx, String addressBase58); Integer removeLockWhitelistAddress(Transaction tx, String addressBase58); Coin getMinimumLockTxValue(); Integer voteFeePerKbChange(Transaction tx, Coin feePerKb); Integer setLockWhitelistDisableBlockDelay(Transaction tx, BigInteger disableBlockDelayBI); Coin getLockingCap(); boolean increaseLockingCap(Transaction tx, Coin newCap); void registerBtcCoinbaseTransaction(byte[] btcTxSerialized, Sha256Hash blockHash, byte[] pmtSerialized, Sha256Hash witnessMerkleRoot, byte[] witnessReservedValue); boolean hasBtcBlockCoinbaseTransactionInformation(Sha256Hash blockHash); static final RskAddress BURN_ADDRESS; static final int MAX_RELEASE_ITERATIONS; static final Integer FEDERATION_CHANGE_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_INVALID_ADDRESS_FORMAT_ERROR_CODE; static final Integer LOCK_WHITELIST_ALREADY_EXISTS_ERROR_CODE; static final Integer LOCK_WHITELIST_UNKNOWN_ERROR_CODE; static final Integer LOCK_WHITELIST_SUCCESS_CODE; static final Integer FEE_PER_KB_GENERIC_ERROR_CODE; static final Integer NEGATIVE_FEE_PER_KB_ERROR_CODE; static final Integer EXCESSIVE_FEE_PER_KB_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INEXISTENT_BLOCK_HASH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_NOT_IN_BEST_CHAIN_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INCONSISTENT_BLOCK_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_TOO_OLD_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INVALID_MERKLE_BRANCH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_MAX_DEPTH; } | @Test public void eventLoggerLogLockBtc_before_rskip_146_activation() throws Exception { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP146)).thenReturn(false); BridgeEventLogger mockedEventLogger = mock(BridgeEventLogger.class); BridgeStorageProvider mockBridgeStorageProvider = mock(BridgeStorageProvider.class); when(mockBridgeStorageProvider.getHeightIfBtcTxhashIsAlreadyProcessed(any(Sha256Hash.class))).thenReturn(Optional.empty()); LockWhitelist lockWhitelist = mock(LockWhitelist.class); when(lockWhitelist.isWhitelistedFor(any(Address.class), any(Coin.class), any(int.class))).thenReturn(true); when(mockBridgeStorageProvider.getLockWhitelist()).thenReturn(lockWhitelist); when(mockBridgeStorageProvider.getNewFederation()).thenReturn(bridgeConstants.getGenesisFederation()); Block executionBlock = mock(Block.class); NetworkParameters params = RegTestParams.get(); Context btcContext = new Context(params); FederationSupport federationSupport = new FederationSupport(bridgeConstants, mockBridgeStorageProvider, executionBlock); BtcBlockStoreWithCache.Factory btcBlockStoreFactory = mock(BtcBlockStoreWithCache.Factory.class); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); when(btcBlockStoreFactory.newInstance(any(Repository.class))).thenReturn(btcBlockStore); Coin lockValue = Coin.COIN; BtcTransaction tx = new BtcTransaction(bridgeConstants.getBtcParams()); tx.addOutput(lockValue, mockBridgeStorageProvider.getNewFederation().getAddress()); BtcECKey srcKey = new BtcECKey(); tx.addInput(PegTestUtils.createHash(1), 0, ScriptBuilder.createInputScript(null, srcKey)); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(tx.getHash()); PartialMerkleTree pmt = new PartialMerkleTree(bridgeConstants.getBtcParams(), bits, hashes, 1); Sha256Hash merkleRoot = pmt.getTxnHashAndMerkleRoot(new ArrayList<>()); co.rsk.bitcoinj.core.BtcBlock btcBlock = new co.rsk.bitcoinj.core.BtcBlock(bridgeConstants.getBtcParams(), 1, PegTestUtils.createHash(), merkleRoot, 1, 1, 1, new ArrayList<>()); int height = 1; mockChainOfStoredBlocks(btcBlockStore, btcBlock, height + bridgeConstants.getBtc2RskMinimumAcceptableConfirmations(), height); BridgeSupport bridgeSupport = new BridgeSupport( bridgeConstants, mockBridgeStorageProvider, mockedEventLogger, new BtcLockSenderProvider(), mock(Repository.class), executionBlock, btcContext, federationSupport, btcBlockStoreFactory, activations ); bridgeSupport.registerBtcTransaction(mock(Transaction.class), tx.bitcoinSerialize(), height, pmt.bitcoinSerialize()); verify(mockedEventLogger, never()).logLockBtc(any(RskAddress.class), any(BtcTransaction.class), any(Address.class), any(Coin.class)); }
@Test public void eventLoggerLogLockBtc_after_rskip_146_activation() throws Exception { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP146)).thenReturn(true); BridgeEventLogger mockedEventLogger = mock(BridgeEventLogger.class); BridgeStorageProvider mockBridgeStorageProvider = mock(BridgeStorageProvider.class); when(mockBridgeStorageProvider.getHeightIfBtcTxhashIsAlreadyProcessed(any(Sha256Hash.class))).thenReturn(Optional.empty()); LockWhitelist lockWhitelist = mock(LockWhitelist.class); when(lockWhitelist.isWhitelistedFor(any(Address.class), any(Coin.class), any(int.class))).thenReturn(true); when(mockBridgeStorageProvider.getLockWhitelist()).thenReturn(lockWhitelist); when(mockBridgeStorageProvider.getNewFederation()).thenReturn(bridgeConstants.getGenesisFederation()); Block executionBlock = mock(Block.class); NetworkParameters params = RegTestParams.get(); Context btcContext = new Context(params); FederationSupport federationSupport = new FederationSupport(bridgeConstants, mockBridgeStorageProvider, executionBlock); BtcBlockStoreWithCache.Factory btcBlockStoreFactory = mock(BtcBlockStoreWithCache.Factory.class); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); when(btcBlockStoreFactory.newInstance(any(Repository.class))).thenReturn(btcBlockStore); Coin lockValue = Coin.COIN; BtcTransaction tx = new BtcTransaction(bridgeConstants.getBtcParams()); tx.addOutput(lockValue, mockBridgeStorageProvider.getNewFederation().getAddress()); BtcECKey srcKey = new BtcECKey(); tx.addInput(PegTestUtils.createHash(1), 0, ScriptBuilder.createInputScript(null, srcKey)); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(tx.getHash()); PartialMerkleTree pmt = new PartialMerkleTree(bridgeConstants.getBtcParams(), bits, hashes, 1); Sha256Hash merkleRoot = pmt.getTxnHashAndMerkleRoot(new ArrayList<>()); co.rsk.bitcoinj.core.BtcBlock btcBlock = new co.rsk.bitcoinj.core.BtcBlock(bridgeConstants.getBtcParams(), 1, PegTestUtils.createHash(), merkleRoot, 1, 1, 1, new ArrayList<>()); int height = 1; mockChainOfStoredBlocks(btcBlockStore, btcBlock, height + bridgeConstants.getBtc2RskMinimumAcceptableConfirmations(), height); BridgeSupport bridgeSupport = new BridgeSupport( bridgeConstants, mockBridgeStorageProvider, mockedEventLogger, new BtcLockSenderProvider(), mock(Repository.class), executionBlock, btcContext, federationSupport, btcBlockStoreFactory, activations ); bridgeSupport.registerBtcTransaction(mock(Transaction.class), tx.bitcoinSerialize(), height, pmt.bitcoinSerialize()); verify(mockedEventLogger, atLeastOnce()).logLockBtc(any(RskAddress.class), any(BtcTransaction.class), any(Address.class), any(Coin.class)); }
@Test public void when_registerBtcTransaction_sender_not_recognized_no_lock_and_no_refund() throws Exception { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); List<BtcECKey> federation1Keys = Arrays.asList( BtcECKey.fromPrivate(Hex.decode("fa01")), BtcECKey.fromPrivate(Hex.decode("fa02")) ); federation1Keys.sort(BtcECKey.PUBKEY_COMPARATOR); Federation federation1 = new Federation( FederationTestUtils.getFederationMembersWithBtcKeys(federation1Keys), Instant.ofEpochMilli(1000L), 0L, btcParams ); Repository repository = createRepository(); repository.addBalance(PrecompiledContracts.BRIDGE_ADDR, LIMIT_MONETARY_BASE); Block executionBlock = mock(Block.class); when(executionBlock.getNumber()).thenReturn(10L); BtcECKey srcKey1 = new BtcECKey(); ECKey key = ECKey.fromPublicOnly(srcKey1.getPubKey()); RskAddress rskAddress = new RskAddress(key.getAddress()); Coin amountToLock = Coin.COIN.multiply(5); BtcTransaction tx1 = new BtcTransaction(btcParams); tx1.addOutput(amountToLock, federation1.getAddress()); tx1.addInput(PegTestUtils.createHash(1), 0, ScriptBuilder.createInputScript(null, srcKey1)); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); BridgeStorageProvider provider = new BridgeStorageProvider(repository, contractAddress, bridgeConstants, activations); provider.setNewFederation(federation1); BtcLockSenderProvider btcLockSenderProvider = mock(BtcLockSenderProvider.class); when(btcLockSenderProvider.tryGetBtcLockSender(any())).thenReturn(Optional.empty()); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(repository)).thenReturn(btcBlockStore); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, btcLockSenderProvider, executionBlock, mockFactory, activations ); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(tx1.getHash()); PartialMerkleTree pmt = new PartialMerkleTree(btcParams, bits, hashes, 1); List<Sha256Hash> hashlist = new ArrayList<>(); Sha256Hash merkleRoot = pmt.getTxnHashAndMerkleRoot(hashlist); co.rsk.bitcoinj.core.BtcBlock registerHeader = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(1), merkleRoot, 1, 1, 1, new ArrayList<>() ); int height = 30; mockChainOfStoredBlocks(btcBlockStore, registerHeader, 35, height); bridgeSupport.registerBtcTransaction(mock(Transaction.class), tx1.bitcoinSerialize(), height, pmt.bitcoinSerialize()); Assert.assertEquals(co.rsk.core.Coin.ZERO, repository.getBalance(rskAddress)); Assert.assertEquals(LIMIT_MONETARY_BASE, repository.getBalance(PrecompiledContracts.BRIDGE_ADDR)); Assert.assertEquals(0, provider.getNewFederationBtcUTXOs().size()); Assert.assertEquals(0, provider.getReleaseRequestQueue().getEntries().size()); Assert.assertEquals(0, provider.getReleaseTransactionSet().getEntries().size()); Assert.assertTrue(provider.getRskTxsWaitingForSignatures().isEmpty()); Assert.assertFalse(provider.getHeightIfBtcTxhashIsAlreadyProcessed(tx1.getHash()).isPresent()); }
@Test public void when_registerBtcTransaction_usesLegacyType_beforeFork_lock_and_no_refund() throws Exception { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(false); List<BtcECKey> federation1Keys = Arrays.asList( BtcECKey.fromPrivate(Hex.decode("fa01")), BtcECKey.fromPrivate(Hex.decode("fa02")) ); federation1Keys.sort(BtcECKey.PUBKEY_COMPARATOR); Federation federation1 = new Federation( FederationTestUtils.getFederationMembersWithBtcKeys(federation1Keys), Instant.ofEpochMilli(1000L), 0L, btcParams ); Repository repository = createRepository(); repository.addBalance(PrecompiledContracts.BRIDGE_ADDR, LIMIT_MONETARY_BASE); Block executionBlock = mock(Block.class); when(executionBlock.getNumber()).thenReturn(10L); BtcECKey srcKey1 = new BtcECKey(); ECKey key = ECKey.fromPublicOnly(srcKey1.getPubKey()); Address btcAddress = srcKey1.toAddress(btcParams); RskAddress rskAddress = new RskAddress(key.getAddress()); Coin amountToLock = Coin.COIN.multiply(5); BtcTransaction tx1 = new BtcTransaction(btcParams); tx1.addOutput(amountToLock, federation1.getAddress()); tx1.addInput(PegTestUtils.createHash(1), 0, ScriptBuilder.createInputScript(null, srcKey1)); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); BridgeStorageProvider provider = new BridgeStorageProvider(repository, contractAddress, bridgeConstants, activations); provider.setNewFederation(federation1); LockWhitelist whitelist = provider.getLockWhitelist(); whitelist.put(btcAddress, new OneOffWhiteListEntry(btcAddress, Coin.COIN.multiply(5))); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(repository)).thenReturn(btcBlockStore); BtcLockSenderProvider btcLockSenderProvider = getBtcLockSenderProvider(BtcLockSender.TxType.P2PKH, btcAddress, rskAddress); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, btcLockSenderProvider, executionBlock, mockFactory, activations ); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(tx1.getHash()); PartialMerkleTree pmt = new PartialMerkleTree(btcParams, bits, hashes, 1); List<Sha256Hash> hashlist = new ArrayList<>(); Sha256Hash merkleRoot = pmt.getTxnHashAndMerkleRoot(hashlist); co.rsk.bitcoinj.core.BtcBlock registerHeader = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(1), merkleRoot, 1, 1, 1, new ArrayList<>() ); int height = 30; mockChainOfStoredBlocks(btcBlockStore, registerHeader, 35, height); bridgeSupport.registerBtcTransaction(mock(Transaction.class), tx1.bitcoinSerialize(), height, pmt.bitcoinSerialize()); co.rsk.core.Coin totalAmountExpectedToHaveBeenLocked = co.rsk.core.Coin.fromBitcoin(Coin.valueOf(5, 0)); Assert.assertThat(whitelist.isWhitelisted(btcAddress), is(false)); Assert.assertEquals(totalAmountExpectedToHaveBeenLocked, repository.getBalance(rskAddress)); Assert.assertEquals(LIMIT_MONETARY_BASE.subtract(totalAmountExpectedToHaveBeenLocked), repository.getBalance(PrecompiledContracts.BRIDGE_ADDR)); Assert.assertEquals(1, provider.getNewFederationBtcUTXOs().size()); Assert.assertEquals(amountToLock, provider.getNewFederationBtcUTXOs().get(0).getValue()); Assert.assertEquals(0, provider.getReleaseRequestQueue().getEntries().size()); Assert.assertEquals(0, provider.getReleaseTransactionSet().getEntries().size()); Assert.assertTrue(provider.getRskTxsWaitingForSignatures().isEmpty()); Assert.assertTrue(provider.getHeightIfBtcTxhashIsAlreadyProcessed(tx1.getHash()).isPresent()); }
@Test public void when_registerBtcTransaction_usesLegacyType_afterFork_notWhitelisted_no_lock_and_refund() throws Exception { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); List<BtcECKey> federation1Keys = Arrays.asList( BtcECKey.fromPrivate(Hex.decode("fa01")), BtcECKey.fromPrivate(Hex.decode("fa02")) ); federation1Keys.sort(BtcECKey.PUBKEY_COMPARATOR); Federation federation1 = new Federation( FederationTestUtils.getFederationMembersWithBtcKeys(federation1Keys), Instant.ofEpochMilli(1000L), 0L, btcParams ); Repository repository = createRepository(); repository.addBalance(PrecompiledContracts.BRIDGE_ADDR, LIMIT_MONETARY_BASE); Block executionBlock = mock(Block.class); when(executionBlock.getNumber()).thenReturn(10L); BtcTransaction tx1 = new BtcTransaction(btcParams); BtcECKey srcKey1 = new BtcECKey(); ECKey key = ECKey.fromPublicOnly(srcKey1.getPubKey()); Address btcAddress = srcKey1.toAddress(btcParams); RskAddress rskAddress = new RskAddress(key.getAddress()); Coin amountToLock = Coin.COIN.multiply(5); tx1.addOutput(amountToLock, federation1.getAddress()); tx1.addInput(PegTestUtils.createHash(1), 0, ScriptBuilder.createInputScript(null, srcKey1)); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); BridgeStorageProvider provider = new BridgeStorageProvider(repository, contractAddress, bridgeConstants, activations); provider.setNewFederation(federation1); LockWhitelist whitelist = provider.getLockWhitelist(); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(repository)).thenReturn(btcBlockStore); BtcLockSenderProvider btcLockSenderProvider = getBtcLockSenderProvider(BtcLockSender.TxType.P2PKH, btcAddress, rskAddress); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, btcLockSenderProvider, executionBlock, mockFactory, activations ); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(tx1.getHash()); PartialMerkleTree pmt = new PartialMerkleTree(btcParams, bits, hashes, 1); List<Sha256Hash> hashlist = new ArrayList<>(); Sha256Hash merkleRoot = pmt.getTxnHashAndMerkleRoot(hashlist); co.rsk.bitcoinj.core.BtcBlock registerHeader = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(1), merkleRoot, 1, 1, 1, new ArrayList<>() ); int height = 30; mockChainOfStoredBlocks(btcBlockStore, registerHeader, 35, height); bridgeSupport.registerBtcTransaction(mock(Transaction.class), tx1.bitcoinSerialize(), height, pmt.bitcoinSerialize()); Assert.assertThat(whitelist.isWhitelisted(btcAddress), is(false)); Assert.assertEquals(co.rsk.core.Coin.ZERO, repository.getBalance(rskAddress)); Assert.assertEquals(LIMIT_MONETARY_BASE, repository.getBalance(PrecompiledContracts.BRIDGE_ADDR)); Assert.assertEquals(0, provider.getNewFederationBtcUTXOs().size()); Assert.assertEquals(1, provider.getReleaseTransactionSet().getEntries().size()); List<BtcTransaction> releaseTxs = provider.getReleaseTransactionSet().getEntries() .stream() .map(ReleaseTransactionSet.Entry::getTransaction) .sorted(Comparator.comparing(BtcTransaction::getOutputSum)) .collect(Collectors.toList()); BtcTransaction releaseTx = releaseTxs.get(0); Assert.assertEquals(1, releaseTx.getOutputs().size()); Assert.assertThat(amountToLock.subtract(releaseTx.getOutput(0).getValue()), is(lessThanOrEqualTo(Coin.MILLICOIN))); Assert.assertEquals(btcAddress, releaseTx.getOutput(0).getAddressFromP2PKHScript(btcParams)); Assert.assertEquals(1, releaseTx.getInputs().size()); Assert.assertEquals(tx1.getHash(), releaseTx.getInput(0).getOutpoint().getHash()); Assert.assertEquals(0, releaseTx.getInput(0).getOutpoint().getIndex()); Assert.assertTrue(provider.getRskTxsWaitingForSignatures().isEmpty()); Assert.assertTrue(provider.getHeightIfBtcTxhashIsAlreadyProcessed(tx1.getHash()).isPresent()); }
@Test public void when_registerBtcTransaction_usesLegacyType_afterFork_lock_and_no_refund() throws Exception { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); List<BtcECKey> federation1Keys = Arrays.asList( BtcECKey.fromPrivate(Hex.decode("fa01")), BtcECKey.fromPrivate(Hex.decode("fa02")) ); federation1Keys.sort(BtcECKey.PUBKEY_COMPARATOR); Federation federation1 = new Federation( FederationTestUtils.getFederationMembersWithBtcKeys(federation1Keys), Instant.ofEpochMilli(1000L), 0L, btcParams ); Repository repository = createRepository(); repository.addBalance(PrecompiledContracts.BRIDGE_ADDR, LIMIT_MONETARY_BASE); Block executionBlock = mock(Block.class); when(executionBlock.getNumber()).thenReturn(10L); BtcECKey srcKey1 = new BtcECKey(); ECKey key = ECKey.fromPublicOnly(srcKey1.getPubKey()); Address btcAddress = srcKey1.toAddress(btcParams); RskAddress rskAddress = new RskAddress(key.getAddress()); BtcTransaction tx1 = new BtcTransaction(btcParams); tx1.addOutput(Coin.COIN.multiply(5), federation1.getAddress()); tx1.addInput(PegTestUtils.createHash(1), 0, ScriptBuilder.createInputScript(null, srcKey1)); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); BridgeStorageProvider provider = new BridgeStorageProvider(repository, contractAddress, bridgeConstants, activations); provider.setNewFederation(federation1); LockWhitelist whitelist = provider.getLockWhitelist(); whitelist.put(btcAddress, new OneOffWhiteListEntry(btcAddress, Coin.COIN.multiply(5))); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(repository)).thenReturn(btcBlockStore); BtcLockSenderProvider btcLockSenderProvider = getBtcLockSenderProvider(BtcLockSender.TxType.P2PKH, btcAddress, rskAddress); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, btcLockSenderProvider, executionBlock, mockFactory, activations ); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(tx1.getHash()); PartialMerkleTree pmt = new PartialMerkleTree(btcParams, bits, hashes, 1); List<Sha256Hash> hashlist = new ArrayList<>(); Sha256Hash merkleRoot = pmt.getTxnHashAndMerkleRoot(hashlist); co.rsk.bitcoinj.core.BtcBlock registerHeader = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(1), merkleRoot, 1, 1, 1, new ArrayList<>() ); int height = 30; mockChainOfStoredBlocks(btcBlockStore, registerHeader, 35, height); bridgeSupport.registerBtcTransaction(mock(Transaction.class), tx1.bitcoinSerialize(), height, pmt.bitcoinSerialize()); co.rsk.core.Coin totalAmountExpectedToHaveBeenLocked = co.rsk.core.Coin.fromBitcoin(Coin.valueOf(5, 0)); Assert.assertThat(whitelist.isWhitelisted(btcAddress), is(false)); Assert.assertEquals(totalAmountExpectedToHaveBeenLocked, repository.getBalance(rskAddress)); Assert.assertEquals(LIMIT_MONETARY_BASE.subtract(totalAmountExpectedToHaveBeenLocked), repository.getBalance(PrecompiledContracts.BRIDGE_ADDR)); Assert.assertEquals(1, provider.getNewFederationBtcUTXOs().size()); Assert.assertEquals(Coin.COIN.multiply(5), provider.getNewFederationBtcUTXOs().get(0).getValue()); Assert.assertEquals(0, provider.getReleaseRequestQueue().getEntries().size()); Assert.assertEquals(0, provider.getReleaseTransactionSet().getEntries().size()); Assert.assertTrue(provider.getRskTxsWaitingForSignatures().isEmpty()); Assert.assertTrue(provider.getHeightIfBtcTxhashIsAlreadyProcessed(tx1.getHash()).isPresent()); }
@Test public void when_registerBtcTransaction_usesSegCompatibilityType_beforeFork_no_lock_and_no_refund() throws Exception { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(false); List<BtcECKey> federation1Keys = Arrays.asList( BtcECKey.fromPrivate(Hex.decode("fa01")), BtcECKey.fromPrivate(Hex.decode("fa02")) ); federation1Keys.sort(BtcECKey.PUBKEY_COMPARATOR); Federation federation1 = new Federation( FederationTestUtils.getFederationMembersWithBtcKeys(federation1Keys), Instant.ofEpochMilli(1000L), 0L, btcParams ); Repository repository = createRepository(); repository.addBalance(PrecompiledContracts.BRIDGE_ADDR, LIMIT_MONETARY_BASE); Block executionBlock = mock(Block.class); when(executionBlock.getNumber()).thenReturn(10L); BtcECKey srcKey1 = new BtcECKey(); ECKey key = ECKey.fromPublicOnly(srcKey1.getPubKey()); Address btcAddress = srcKey1.toAddress(btcParams); RskAddress rskAddress = new RskAddress(key.getAddress()); BtcTransaction tx1 = new BtcTransaction(btcParams); tx1.addOutput(Coin.COIN.multiply(5), federation1.getAddress()); tx1.addInput(PegTestUtils.createHash(1), 0, ScriptBuilder.createInputScript(null, srcKey1)); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); BridgeStorageProvider provider = new BridgeStorageProvider(repository, contractAddress, bridgeConstants, activations); provider.setNewFederation(federation1); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(repository)).thenReturn(btcBlockStore); BtcLockSenderProvider btcLockSenderProvider = getBtcLockSenderProvider(BtcLockSender.TxType.P2SHP2WPKH, btcAddress, rskAddress); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, btcLockSenderProvider, executionBlock, mockFactory, activations ); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(tx1.getHash()); PartialMerkleTree pmt = new PartialMerkleTree(btcParams, bits, hashes, 1); List<Sha256Hash> hashlist = new ArrayList<>(); Sha256Hash merkleRoot = pmt.getTxnHashAndMerkleRoot(hashlist); co.rsk.bitcoinj.core.BtcBlock registerHeader = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(1), merkleRoot, 1, 1, 1, new ArrayList<>() ); int height = 30; mockChainOfStoredBlocks(btcBlockStore, registerHeader, 35, height); bridgeSupport.registerBtcTransaction(mock(Transaction.class), tx1.bitcoinSerialize(), height, pmt.bitcoinSerialize()); Assert.assertEquals(co.rsk.core.Coin.ZERO, repository.getBalance(rskAddress)); Assert.assertEquals(LIMIT_MONETARY_BASE, repository.getBalance(PrecompiledContracts.BRIDGE_ADDR)); Assert.assertEquals(0, provider.getNewFederationBtcUTXOs().size()); Assert.assertEquals(0, provider.getReleaseRequestQueue().getEntries().size()); Assert.assertEquals(0, provider.getReleaseTransactionSet().getEntries().size()); Assert.assertTrue(provider.getRskTxsWaitingForSignatures().isEmpty()); Assert.assertFalse(provider.getHeightIfBtcTxhashIsAlreadyProcessed(tx1.getHash()).isPresent()); }
@Test public void when_registerBtcTransaction_usesSegCompatibilityType_afterFork_lock_and_no_refund() throws Exception { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); List<BtcECKey> federation1Keys = Arrays.asList( BtcECKey.fromPrivate(Hex.decode("fa01")), BtcECKey.fromPrivate(Hex.decode("fa02")) ); federation1Keys.sort(BtcECKey.PUBKEY_COMPARATOR); Federation federation1 = new Federation( FederationTestUtils.getFederationMembersWithBtcKeys(federation1Keys), Instant.ofEpochMilli(1000L), 0L, btcParams ); Repository repository = createRepository(); repository.addBalance(PrecompiledContracts.BRIDGE_ADDR, LIMIT_MONETARY_BASE); Block executionBlock = mock(Block.class); when(executionBlock.getNumber()).thenReturn(10L); BtcTransaction tx1 = new BtcTransaction(btcParams); BtcECKey srcKey1 = new BtcECKey(); ECKey key = ECKey.fromPublicOnly(srcKey1.getPubKey()); Address btcAddress = srcKey1.toAddress(btcParams); RskAddress rskAddress = new RskAddress(key.getAddress()); Coin amountToLock = Coin.COIN.multiply(5); tx1.addOutput(amountToLock, federation1.getAddress()); tx1.addInput(PegTestUtils.createHash(1), 0, ScriptBuilder.createInputScript(null, srcKey1)); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); BridgeStorageProvider provider = new BridgeStorageProvider(repository, contractAddress, bridgeConstants, activations); provider.setNewFederation(federation1); LockWhitelist whitelist = provider.getLockWhitelist(); whitelist.put(btcAddress, new OneOffWhiteListEntry(btcAddress, amountToLock)); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(repository)).thenReturn(btcBlockStore); BtcLockSenderProvider btcLockSenderProvider = getBtcLockSenderProvider(BtcLockSender.TxType.P2SHP2WPKH, btcAddress, rskAddress); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, btcLockSenderProvider, executionBlock, mockFactory, activations ); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(tx1.getHash()); PartialMerkleTree pmt = new PartialMerkleTree(btcParams, bits, hashes, 1); List<Sha256Hash> hashlist = new ArrayList<>(); Sha256Hash merkleRoot = pmt.getTxnHashAndMerkleRoot(hashlist); co.rsk.bitcoinj.core.BtcBlock registerHeader = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(1), merkleRoot, 1, 1, 1, new ArrayList<>() ); int height = 30; mockChainOfStoredBlocks(btcBlockStore, registerHeader, 35, height); bridgeSupport.registerBtcTransaction(mock(Transaction.class), tx1.bitcoinSerialize(), height, pmt.bitcoinSerialize()); co.rsk.core.Coin totalAmountExpectedToHaveBeenLocked = co.rsk.core.Coin.fromBitcoin(Coin.valueOf(5, 0)); Assert.assertThat(whitelist.isWhitelisted(btcAddress), is(false)); Assert.assertEquals(totalAmountExpectedToHaveBeenLocked, repository.getBalance(rskAddress)); Assert.assertEquals(LIMIT_MONETARY_BASE.subtract(totalAmountExpectedToHaveBeenLocked), repository.getBalance(PrecompiledContracts.BRIDGE_ADDR)); Assert.assertEquals(1, provider.getNewFederationBtcUTXOs().size()); Assert.assertEquals(amountToLock, provider.getNewFederationBtcUTXOs().get(0).getValue()); Assert.assertEquals(0, provider.getReleaseRequestQueue().getEntries().size()); Assert.assertEquals(0, provider.getReleaseTransactionSet().getEntries().size()); Assert.assertTrue(provider.getRskTxsWaitingForSignatures().isEmpty()); Assert.assertTrue(provider.getHeightIfBtcTxhashIsAlreadyProcessed(tx1.getHash()).isPresent()); }
@Test public void when_registerBtcTransaction_usesSegCompatibilityType_afterFork_notWhitelisted_no_lock_and_refund() throws Exception { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); List<BtcECKey> federation1Keys = Arrays.asList( BtcECKey.fromPrivate(Hex.decode("fa01")), BtcECKey.fromPrivate(Hex.decode("fa02")) ); federation1Keys.sort(BtcECKey.PUBKEY_COMPARATOR); Federation federation1 = new Federation( FederationTestUtils.getFederationMembersWithBtcKeys(federation1Keys), Instant.ofEpochMilli(1000L), 0L, btcParams ); Repository repository = createRepository(); repository.addBalance(PrecompiledContracts.BRIDGE_ADDR, LIMIT_MONETARY_BASE); Block executionBlock = mock(Block.class); when(executionBlock.getNumber()).thenReturn(10L); BtcTransaction tx1 = new BtcTransaction(btcParams); BtcECKey srcKey1 = new BtcECKey(); ECKey key = ECKey.fromPublicOnly(srcKey1.getPubKey()); Address btcAddress = srcKey1.toAddress(btcParams); RskAddress rskAddress = new RskAddress(key.getAddress()); Coin amountToLock = Coin.COIN.multiply(5); tx1.addOutput(amountToLock, federation1.getAddress()); tx1.addInput(PegTestUtils.createHash(1), 0, ScriptBuilder.createInputScript(null, srcKey1)); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); BridgeStorageProvider provider = new BridgeStorageProvider(repository, contractAddress, bridgeConstants, activations); provider.setNewFederation(federation1); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(repository)).thenReturn(btcBlockStore); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, getBtcLockSenderProvider(BtcLockSender.TxType.P2SHP2WPKH, btcAddress, rskAddress), executionBlock, mockFactory, activations ); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(tx1.getHash()); PartialMerkleTree pmt = new PartialMerkleTree(btcParams, bits, hashes, 1); List<Sha256Hash> hashlist = new ArrayList<>(); Sha256Hash merkleRoot = pmt.getTxnHashAndMerkleRoot(hashlist); co.rsk.bitcoinj.core.BtcBlock registerHeader = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(1), merkleRoot, 1, 1, 1, new ArrayList<>() ); int height = 30; mockChainOfStoredBlocks(btcBlockStore, registerHeader, 35, height); bridgeSupport.registerBtcTransaction(mock(Transaction.class), tx1.bitcoinSerialize(), height, pmt.bitcoinSerialize()); Assert.assertEquals(co.rsk.core.Coin.ZERO, repository.getBalance(rskAddress)); Assert.assertEquals(LIMIT_MONETARY_BASE, repository.getBalance(PrecompiledContracts.BRIDGE_ADDR)); Assert.assertEquals(0, provider.getNewFederationBtcUTXOs().size()); Assert.assertEquals(1, provider.getReleaseTransactionSet().getEntries().size()); List<BtcTransaction> releaseTxs = provider.getReleaseTransactionSet().getEntries() .stream() .map(ReleaseTransactionSet.Entry::getTransaction) .sorted(Comparator.comparing(BtcTransaction::getOutputSum)) .collect(Collectors.toList()); BtcTransaction releaseTx = releaseTxs.get(0); Assert.assertEquals(1, releaseTx.getOutputs().size()); Assert.assertThat(amountToLock.subtract(releaseTx.getOutput(0).getValue()), is(lessThanOrEqualTo(Coin.MILLICOIN))); Assert.assertEquals(btcAddress, releaseTx.getOutput(0).getAddressFromP2PKHScript(btcParams)); Assert.assertEquals(1, releaseTx.getInputs().size()); Assert.assertEquals(tx1.getHash(), releaseTx.getInput(0).getOutpoint().getHash()); Assert.assertEquals(0, releaseTx.getInput(0).getOutpoint().getIndex()); Assert.assertTrue(provider.getRskTxsWaitingForSignatures().isEmpty()); Assert.assertTrue(provider.getHeightIfBtcTxhashIsAlreadyProcessed(tx1.getHash()).isPresent()); }
@Test public void when_registerBtcTransaction_usesMultisigType_beforeFork_no_lock_and_no_refund() throws Exception { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(false); List<BtcECKey> federation1Keys = Arrays.asList( BtcECKey.fromPrivate(Hex.decode("fa01")), BtcECKey.fromPrivate(Hex.decode("fa02")) ); federation1Keys.sort(BtcECKey.PUBKEY_COMPARATOR); Federation federation1 = new Federation( FederationTestUtils.getFederationMembersWithBtcKeys(federation1Keys), Instant.ofEpochMilli(1000L), 0L, btcParams ); Repository repository = createRepository(); repository.addBalance(PrecompiledContracts.BRIDGE_ADDR, LIMIT_MONETARY_BASE); Block executionBlock = mock(Block.class); when(executionBlock.getNumber()).thenReturn(10L); BtcECKey srcKey1 = new BtcECKey(); ECKey key = ECKey.fromPublicOnly(srcKey1.getPubKey()); Address btcAddress = srcKey1.toAddress(btcParams); RskAddress rskAddress = new RskAddress(key.getAddress()); BtcTransaction tx1 = new BtcTransaction(btcParams); tx1.addOutput(Coin.COIN.multiply(5), federation1.getAddress()); tx1.addInput(PegTestUtils.createHash(1), 0, ScriptBuilder.createInputScript(null, srcKey1)); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); BridgeStorageProvider provider = new BridgeStorageProvider(repository, contractAddress, bridgeConstants, activations); provider.setNewFederation(federation1); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(repository)).thenReturn(btcBlockStore); BtcLockSenderProvider btcLockSenderProvider = getBtcLockSenderProvider(BtcLockSender.TxType.P2SHMULTISIG, btcAddress, rskAddress); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, btcLockSenderProvider, executionBlock, mockFactory, activations ); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(tx1.getHash()); PartialMerkleTree pmt = new PartialMerkleTree(btcParams, bits, hashes, 1); List<Sha256Hash> hashlist = new ArrayList<>(); Sha256Hash merkleRoot = pmt.getTxnHashAndMerkleRoot(hashlist); co.rsk.bitcoinj.core.BtcBlock registerHeader = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(1), merkleRoot, 1, 1, 1, new ArrayList<>() ); int height = 30; mockChainOfStoredBlocks(btcBlockStore, registerHeader, 35, height); bridgeSupport.registerBtcTransaction(mock(Transaction.class), tx1.bitcoinSerialize(), height, pmt.bitcoinSerialize()); Assert.assertEquals(co.rsk.core.Coin.ZERO, repository.getBalance(rskAddress)); Assert.assertEquals(LIMIT_MONETARY_BASE, repository.getBalance(PrecompiledContracts.BRIDGE_ADDR)); Assert.assertEquals(0, provider.getNewFederationBtcUTXOs().size()); Assert.assertEquals(0, provider.getReleaseRequestQueue().getEntries().size()); Assert.assertEquals(0, provider.getReleaseTransactionSet().getEntries().size()); Assert.assertTrue(provider.getRskTxsWaitingForSignatures().isEmpty()); Assert.assertFalse(provider.getHeightIfBtcTxhashIsAlreadyProcessed(tx1.getHash()).isPresent()); }
@Test public void when_registerBtcTransaction_usesMultisigType_afterFork_no_lock_and_refund() throws Exception { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); List<BtcECKey> federation1Keys = Arrays.asList( BtcECKey.fromPrivate(Hex.decode("fa01")), BtcECKey.fromPrivate(Hex.decode("fa02")) ); federation1Keys.sort(BtcECKey.PUBKEY_COMPARATOR); Federation federation1 = new Federation( FederationTestUtils.getFederationMembersWithBtcKeys(federation1Keys), Instant.ofEpochMilli(1000L), 0L, btcParams ); Repository repository = createRepository(); repository.addBalance(PrecompiledContracts.BRIDGE_ADDR, LIMIT_MONETARY_BASE); Block executionBlock = mock(Block.class); when(executionBlock.getNumber()).thenReturn(10L); BtcECKey srcKey1 = new BtcECKey(); Address btcAddress = srcKey1.toAddress(btcParams); Coin amountToLock = Coin.COIN.multiply(5); BtcTransaction tx1 = new BtcTransaction(btcParams); tx1.addOutput(amountToLock, federation1.getAddress()); tx1.addInput(PegTestUtils.createHash(1), 0, ScriptBuilder.createInputScript(null, srcKey1)); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); BridgeStorageProvider provider = new BridgeStorageProvider(repository, contractAddress, bridgeConstants, activations); provider.setNewFederation(federation1); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(repository)).thenReturn(btcBlockStore); BtcLockSenderProvider btcLockSenderProvider = getBtcLockSenderProvider(BtcLockSender.TxType.P2SHMULTISIG, btcAddress, null); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, btcLockSenderProvider, executionBlock, mockFactory, activations ); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(tx1.getHash()); PartialMerkleTree pmt = new PartialMerkleTree(btcParams, bits, hashes, 1); List<Sha256Hash> hashlist = new ArrayList<>(); Sha256Hash merkleRoot = pmt.getTxnHashAndMerkleRoot(hashlist); co.rsk.bitcoinj.core.BtcBlock registerHeader = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(1), merkleRoot, 1, 1, 1, new ArrayList<>() ); int height = 30; mockChainOfStoredBlocks(btcBlockStore, registerHeader, 35, height); bridgeSupport.registerBtcTransaction(mock(Transaction.class), tx1.bitcoinSerialize(), height, pmt.bitcoinSerialize()); Assert.assertEquals(LIMIT_MONETARY_BASE, repository.getBalance(PrecompiledContracts.BRIDGE_ADDR)); Assert.assertEquals(0, provider.getNewFederationBtcUTXOs().size()); Assert.assertEquals(0, provider.getReleaseRequestQueue().getEntries().size()); Assert.assertEquals(1, provider.getReleaseTransactionSet().getEntries().size()); List<BtcTransaction> releaseTxs = provider.getReleaseTransactionSet().getEntries() .stream() .map(ReleaseTransactionSet.Entry::getTransaction) .collect(Collectors.toList()); BtcTransaction releaseTx = releaseTxs.get(0); Assert.assertEquals(1, releaseTx.getOutputs().size()); Assert.assertThat(amountToLock.subtract(releaseTx.getOutput(0).getValue()), is(lessThanOrEqualTo(Coin.MILLICOIN))); Assert.assertEquals(btcAddress, releaseTx.getOutput(0).getScriptPubKey().getToAddress(btcParams)); Assert.assertEquals(1, releaseTx.getInputs().size()); Assert.assertEquals(tx1.getHash(), releaseTx.getInput(0).getOutpoint().getHash()); Assert.assertEquals(0, releaseTx.getInput(0).getOutpoint().getIndex()); Assert.assertTrue(provider.getRskTxsWaitingForSignatures().isEmpty()); Assert.assertTrue(provider.getHeightIfBtcTxhashIsAlreadyProcessed(tx1.getHash()).isPresent()); }
@Test public void when_registerBtcTransaction_usesMultisigWithWitnessType_beforeFork_no_lock_and_no_refund() throws Exception { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(false); List<BtcECKey> federation1Keys = Arrays.asList( BtcECKey.fromPrivate(Hex.decode("fa01")), BtcECKey.fromPrivate(Hex.decode("fa02")) ); federation1Keys.sort(BtcECKey.PUBKEY_COMPARATOR); Federation federation1 = new Federation( FederationTestUtils.getFederationMembersWithBtcKeys(federation1Keys), Instant.ofEpochMilli(1000L), 0L, btcParams ); Repository repository = createRepository(); repository.addBalance(PrecompiledContracts.BRIDGE_ADDR, LIMIT_MONETARY_BASE); Block executionBlock = mock(Block.class); when(executionBlock.getNumber()).thenReturn(10L); BtcECKey srcKey1 = new BtcECKey(); ECKey key = ECKey.fromPublicOnly(srcKey1.getPubKey()); Address btcAddress = srcKey1.toAddress(btcParams); RskAddress rskAddress = new RskAddress(key.getAddress()); Coin amountToLock = Coin.COIN.multiply(5); BtcTransaction tx1 = new BtcTransaction(btcParams); tx1.addOutput(amountToLock, federation1.getAddress()); tx1.addInput(PegTestUtils.createHash(1), 0, ScriptBuilder.createInputScript(null, srcKey1)); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); BridgeStorageProvider provider = new BridgeStorageProvider(repository, contractAddress, bridgeConstants, activations); provider.setNewFederation(federation1); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(repository)).thenReturn(btcBlockStore); BtcLockSenderProvider btcLockSenderProvider = getBtcLockSenderProvider(BtcLockSender.TxType.P2SHP2WSH, btcAddress, rskAddress); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, btcLockSenderProvider, executionBlock, mockFactory, activations ); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(tx1.getHash()); PartialMerkleTree pmt = new PartialMerkleTree(btcParams, bits, hashes, 1); List<Sha256Hash> hashlist = new ArrayList<>(); Sha256Hash merkleRoot = pmt.getTxnHashAndMerkleRoot(hashlist); co.rsk.bitcoinj.core.BtcBlock registerHeader = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(1), merkleRoot, 1, 1, 1, new ArrayList<>() ); int height = 30; mockChainOfStoredBlocks(btcBlockStore, registerHeader, 35, height); bridgeSupport.registerBtcTransaction(mock(Transaction.class), tx1.bitcoinSerialize(), height, pmt.bitcoinSerialize()); Assert.assertEquals(co.rsk.core.Coin.ZERO, repository.getBalance(rskAddress)); Assert.assertEquals(LIMIT_MONETARY_BASE, repository.getBalance(PrecompiledContracts.BRIDGE_ADDR)); Assert.assertEquals(0, provider.getNewFederationBtcUTXOs().size()); Assert.assertEquals(0, provider.getReleaseRequestQueue().getEntries().size()); Assert.assertEquals(0, provider.getReleaseTransactionSet().getEntries().size()); Assert.assertTrue(provider.getRskTxsWaitingForSignatures().isEmpty()); Assert.assertFalse(provider.getHeightIfBtcTxhashIsAlreadyProcessed(tx1.getHash()).isPresent()); }
@Test public void when_registerBtcTransaction_usesMultisigWithWitnessType_afterFork_no_lock_and_refund() throws Exception { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); List<BtcECKey> federation1Keys = Arrays.asList( BtcECKey.fromPrivate(Hex.decode("fa01")), BtcECKey.fromPrivate(Hex.decode("fa02")) ); federation1Keys.sort(BtcECKey.PUBKEY_COMPARATOR); Federation federation1 = new Federation( FederationTestUtils.getFederationMembersWithBtcKeys(federation1Keys), Instant.ofEpochMilli(1000L), 0L, btcParams ); Repository repository = createRepository(); repository.addBalance(PrecompiledContracts.BRIDGE_ADDR, LIMIT_MONETARY_BASE); Block executionBlock = mock(Block.class); when(executionBlock.getNumber()).thenReturn(10L); BtcECKey srcKey1 = new BtcECKey(); Address btcAddress = srcKey1.toAddress(btcParams); Coin amountToLock = Coin.COIN.multiply(5); BtcTransaction tx1 = new BtcTransaction(btcParams); tx1.addOutput(amountToLock, federation1.getAddress()); tx1.addInput(PegTestUtils.createHash(1), 0, ScriptBuilder.createInputScript(null, srcKey1)); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); BridgeStorageProvider provider = new BridgeStorageProvider(repository, contractAddress, bridgeConstants, activations); provider.setNewFederation(federation1); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(repository)).thenReturn(btcBlockStore); BtcLockSenderProvider btcLockSenderProvider = getBtcLockSenderProvider(BtcLockSender.TxType.P2SHP2WSH, btcAddress, null); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, btcLockSenderProvider, executionBlock, mockFactory, activations ); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(tx1.getHash()); PartialMerkleTree pmt = new PartialMerkleTree(btcParams, bits, hashes, 1); List<Sha256Hash> hashlist = new ArrayList<>(); Sha256Hash merkleRoot = pmt.getTxnHashAndMerkleRoot(hashlist); co.rsk.bitcoinj.core.BtcBlock registerHeader = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(1), merkleRoot, 1, 1, 1, new ArrayList<>() ); int height = 30; mockChainOfStoredBlocks(btcBlockStore, registerHeader, 35, height); bridgeSupport.registerBtcTransaction(mock(Transaction.class), tx1.bitcoinSerialize(), height, pmt.bitcoinSerialize()); Assert.assertEquals(LIMIT_MONETARY_BASE, repository.getBalance(PrecompiledContracts.BRIDGE_ADDR)); Assert.assertEquals(0, provider.getNewFederationBtcUTXOs().size()); Assert.assertEquals(0, provider.getReleaseRequestQueue().getEntries().size()); Assert.assertEquals(1, provider.getReleaseTransactionSet().getEntries().size()); List<BtcTransaction> releaseTxs = provider.getReleaseTransactionSet().getEntries() .stream() .map(ReleaseTransactionSet.Entry::getTransaction) .collect(Collectors.toList()); BtcTransaction releaseTx = releaseTxs.get(0); Assert.assertEquals(1, releaseTx.getOutputs().size()); Assert.assertThat(amountToLock.subtract(releaseTx.getOutput(0).getValue()), is(lessThanOrEqualTo(Coin.MILLICOIN))); Assert.assertEquals(btcAddress, releaseTx.getOutput(0).getScriptPubKey().getToAddress(btcParams)); Assert.assertEquals(1, releaseTx.getInputs().size()); Assert.assertEquals(tx1.getHash(), releaseTx.getInput(0).getOutpoint().getHash()); Assert.assertEquals(0, releaseTx.getInput(0).getOutpoint().getIndex()); Assert.assertTrue(provider.getRskTxsWaitingForSignatures().isEmpty()); Assert.assertTrue(provider.getHeightIfBtcTxhashIsAlreadyProcessed(tx1.getHash()).isPresent()); }
@Test(expected = VerificationException.EmptyInputsOrOutputs.class) public void registerBtcTransaction_rejects_tx_with_witness_before_rskip_143_activation() throws BlockStoreException, IOException { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(false); Repository repository = createRepository(); BtcTransaction tx1 = new BtcTransaction(btcParams); tx1.addInput(Sha256Hash.ZERO_HASH, 0, new Script(new byte[]{})); TransactionWitness txWit = new TransactionWitness(1); txWit.setPush(0, new byte[]{}); tx1.setWitness(0, txWit); tx1.addOutput(Coin.COIN, Address.fromBase58(BridgeRegTestConstants.getInstance().getBtcParams(), "mvbnrCX3bg1cDRUu8pkecrvP6vQkSLDSou")); byte[] bits = new byte[1]; bits[0] = 0x3f; co.rsk.bitcoinj.core.BtcBlock registerHeader = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(1), Sha256Hash.ZERO_HASH, 1, 1, 1, new ArrayList<>() ); List<Sha256Hash> hashes2 = new ArrayList<>(); hashes2.add(tx1.getHash(true)); PartialMerkleTree pmtWithWitness = new PartialMerkleTree(btcParams, bits, hashes2, 1); int height = 50; StoredBlock block = new StoredBlock(registerHeader, new BigInteger("0"), height); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); when(btcBlockStore.getFromCache(registerHeader.getHash())).thenReturn(block); co.rsk.bitcoinj.core.BtcBlock headBlock = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(2), Sha256Hash.of(new byte[]{1}), 1, 1, 1, new ArrayList<>() ); StoredBlock chainHead = new StoredBlock(headBlock, new BigInteger("0"), 132); when(btcBlockStore.getChainHead()).thenReturn(chainHead); when(btcBlockStore.getStoredBlockAtMainChainHeight(block.getHeight())).thenReturn(block); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(any())).thenReturn(btcBlockStore); BridgeStorageProvider provider = mock(BridgeStorageProvider.class); BridgeSupport bridgeSupport = getBridgeSupport(provider, repository, mockFactory); bridgeSupport.registerBtcTransaction(mock(Transaction.class), tx1.bitcoinSerialize(), height, pmtWithWitness.bitcoinSerialize()); verify(btcBlockStore, never()).getStoredBlockAtMainChainHeight(height); }
@Test public void registerBtcTransaction_accepts_lock_tx_with_witness_after_rskip_143_activation() throws BlockStoreException, IOException { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); List<BtcECKey> federation1Keys = Arrays.asList( BtcECKey.fromPrivate(Hex.decode("fa01")), BtcECKey.fromPrivate(Hex.decode("fa02")) ); federation1Keys.sort(BtcECKey.PUBKEY_COMPARATOR); Federation federation1 = new Federation( FederationTestUtils.getFederationMembersWithBtcKeys(federation1Keys), Instant.ofEpochMilli(1000L), 0L, btcParams ); Repository repository = createRepository(); BtcTransaction tx1 = new BtcTransaction(btcParams); BtcECKey srcKey1 = new BtcECKey(); ECKey key = ECKey.fromPublicOnly(srcKey1.getPubKey()); Address btcAddress = srcKey1.toAddress(btcParams); RskAddress rskAddress = new RskAddress(key.getAddress()); Coin amountToLock = Coin.COIN.multiply(10); tx1.addOutput(amountToLock, federation1.getAddress()); tx1.addInput(PegTestUtils.createHash(1), 0, new Script(new byte[]{})); TransactionWitness txWit = new TransactionWitness(1); txWit.setPush(0, new byte[]{}); tx1.setWitness(0, txWit); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(tx1.getHash()); PartialMerkleTree pmtWithoutWitness = new PartialMerkleTree(btcParams, bits, hashes, 1); List<Sha256Hash> hashlist = new ArrayList<>(); Sha256Hash blockMerkleRoot = pmtWithoutWitness.getTxnHashAndMerkleRoot(hashlist); co.rsk.bitcoinj.core.BtcBlock registerHeader = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(1), blockMerkleRoot, 1, 1, 1, new ArrayList<>() ); List<Sha256Hash> hashes2 = new ArrayList<>(); hashes2.add(tx1.getHash(true)); PartialMerkleTree pmtWithWitness = new PartialMerkleTree(btcParams, bits, hashes2, 1); List<Sha256Hash> hashlist2 = new ArrayList<>(); Sha256Hash witnessMerkleRoot = pmtWithWitness.getTxnHashAndMerkleRoot(hashlist2); int height = 50; StoredBlock block = new StoredBlock(registerHeader, new BigInteger("0"), height); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); co.rsk.bitcoinj.core.BtcBlock headBlock = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(2), Sha256Hash.of(new byte[]{1}), 1, 1, 1, new ArrayList<>() ); StoredBlock chainHead = new StoredBlock(headBlock, new BigInteger("0"), 132); when(btcBlockStore.getChainHead()).thenReturn(chainHead); when(btcBlockStore.getStoredBlockAtMainChainHeight(block.getHeight())).thenReturn(block); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(any())).thenReturn(btcBlockStore); BridgeStorageProvider provider = new BridgeStorageProvider(repository, contractAddress, bridgeConstants, activations); provider.setNewFederation(federation1); LockWhitelist whitelist = provider.getLockWhitelist(); whitelist.put(btcAddress, new OneOffWhiteListEntry(btcAddress, Coin.COIN.multiply(10))); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, getBtcLockSenderProvider(BtcLockSender.TxType.P2SHP2WPKH, btcAddress, rskAddress), mock(Block.class), mockFactory, activations ); CoinbaseInformation coinbaseInformation = new CoinbaseInformation(witnessMerkleRoot); provider.setCoinbaseInformation(registerHeader.getHash(), coinbaseInformation); bridgeSupport.registerBtcTransaction(mock(Transaction.class), tx1.bitcoinSerialize(), height, pmtWithWitness.bitcoinSerialize()); co.rsk.core.Coin totalAmountExpectedToHaveBeenLocked = co.rsk.core.Coin.fromBitcoin(amountToLock); Assert.assertEquals(totalAmountExpectedToHaveBeenLocked, repository.getBalance(rskAddress)); Assert.assertEquals(1, provider.getNewFederationBtcUTXOs().size()); Assert.assertEquals(amountToLock, provider.getNewFederationBtcUTXOs().get(0).getValue()); Assert.assertEquals(0, provider.getReleaseRequestQueue().getEntries().size()); Assert.assertEquals(0, provider.getReleaseTransactionSet().getEntries().size()); Assert.assertTrue(provider.getRskTxsWaitingForSignatures().isEmpty()); Assert.assertTrue(provider.getHeightIfBtcTxhashIsAlreadyProcessed(tx1.getHash(false)).isPresent()); }
@Test public void registerBtcTransaction_rejects_tx_with_witness_and_unregistered_coinbase_after_rskip_143_activation() throws BlockStoreException, IOException { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); Repository repository = createRepository(); BtcTransaction tx1 = new BtcTransaction(btcParams); BtcECKey srcKey1 = new BtcECKey(); ECKey key = ECKey.fromPublicOnly(srcKey1.getPubKey()); Address btcAddress = srcKey1.toAddress(btcParams); RskAddress rskAddress = new RskAddress(key.getAddress()); Coin amountToLock = Coin.COIN.multiply(10); tx1.addOutput(amountToLock, Address.fromBase58(BridgeRegTestConstants.getInstance().getBtcParams(), "mvbnrCX3bg1cDRUu8pkecrvP6vQkSLDSou")); tx1.addInput(PegTestUtils.createHash(1), 0, new Script(new byte[]{})); TransactionWitness txWit = new TransactionWitness(1); txWit.setPush(0, new byte[]{}); tx1.setWitness(0, txWit); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(tx1.getHash()); PartialMerkleTree pmtWithoutWitness = new PartialMerkleTree(btcParams, bits, hashes, 1); List<Sha256Hash> hashlist = new ArrayList<>(); Sha256Hash blockMerkleRoot = pmtWithoutWitness.getTxnHashAndMerkleRoot(hashlist); co.rsk.bitcoinj.core.BtcBlock registerHeader = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(1), blockMerkleRoot, 1, 1, 1, new ArrayList<>() ); List<Sha256Hash> hashes2 = new ArrayList<>(); hashes2.add(tx1.getHash(true)); PartialMerkleTree pmtWithWitness = new PartialMerkleTree(btcParams, bits, hashes2, 1); int height = 50; StoredBlock block = new StoredBlock(registerHeader, new BigInteger("0"), height); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); co.rsk.bitcoinj.core.BtcBlock headBlock = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(2), Sha256Hash.of(new byte[]{1}), 1, 1, 1, new ArrayList<>() ); StoredBlock chainHead = new StoredBlock(headBlock, new BigInteger("0"), 132); when(btcBlockStore.getChainHead()).thenReturn(chainHead); when(btcBlockStore.getStoredBlockAtMainChainHeight(block.getHeight())).thenReturn(block); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(any())).thenReturn(btcBlockStore); BridgeStorageProvider provider = spy(new BridgeStorageProvider(repository, contractAddress, bridgeConstants, activations)); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, getBtcLockSenderProvider(BtcLockSender.TxType.P2SHP2WPKH, btcAddress, rskAddress), mock(Block.class), mockFactory, activations ); bridgeSupport.registerBtcTransaction(mock(Transaction.class), tx1.bitcoinSerialize(), height, pmtWithWitness.bitcoinSerialize()); verify(provider, never()).setHeightBtcTxhashAlreadyProcessed(tx1.getHash(true), height); verify(provider, never()).setHeightBtcTxhashAlreadyProcessed(any(Sha256Hash.class), anyLong()); }
@Test public void registerBtcTransaction_rejects_tx_with_witness_and_unqual_witness_root_after_rskip_143_activation() throws BlockStoreException, IOException { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); Repository repository = createRepository(); BtcTransaction tx1 = new BtcTransaction(btcParams); BtcECKey srcKey1 = new BtcECKey(); ECKey key = ECKey.fromPublicOnly(srcKey1.getPubKey()); Address btcAddress = srcKey1.toAddress(btcParams); RskAddress rskAddress = new RskAddress(key.getAddress()); Coin amountToLock = Coin.COIN.multiply(10); tx1.addOutput(amountToLock, Address.fromBase58(BridgeRegTestConstants.getInstance().getBtcParams(), "mvbnrCX3bg1cDRUu8pkecrvP6vQkSLDSou")); tx1.addInput(PegTestUtils.createHash(1), 0, new Script(new byte[]{})); TransactionWitness txWit = new TransactionWitness(1); txWit.setPush(0, new byte[]{}); tx1.setWitness(0, txWit); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(tx1.getHash()); PartialMerkleTree pmtWithoutWitness = new PartialMerkleTree(btcParams, bits, hashes, 1); List<Sha256Hash> hashlist = new ArrayList<>(); Sha256Hash blockMerkleRoot = pmtWithoutWitness.getTxnHashAndMerkleRoot(hashlist); co.rsk.bitcoinj.core.BtcBlock registerHeader = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(1), blockMerkleRoot, 1, 1, 1, new ArrayList<>() ); List<Sha256Hash> hashes2 = new ArrayList<>(); hashes2.add(tx1.getHash(true)); PartialMerkleTree pmtWithWitness = new PartialMerkleTree(btcParams, bits, hashes2, 1); int height = 50; StoredBlock block = new StoredBlock(registerHeader, new BigInteger("0"), height); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); co.rsk.bitcoinj.core.BtcBlock headBlock = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(2), Sha256Hash.of(new byte[]{1}), 1, 1, 1, new ArrayList<>() ); StoredBlock chainHead = new StoredBlock(headBlock, new BigInteger("0"), 132); when(btcBlockStore.getChainHead()).thenReturn(chainHead); when(btcBlockStore.getStoredBlockAtMainChainHeight(block.getHeight())).thenReturn(block); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(any())).thenReturn(btcBlockStore); BridgeStorageProvider provider = spy(new BridgeStorageProvider(repository, contractAddress, bridgeConstants, activations)); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, getBtcLockSenderProvider(BtcLockSender.TxType.P2SHP2WPKH, btcAddress, rskAddress), mock(Block.class), mockFactory, activations ); CoinbaseInformation coinbaseInformation = new CoinbaseInformation(Sha256Hash.ZERO_HASH); provider.setCoinbaseInformation(registerHeader.getHash(), coinbaseInformation); bridgeSupport.registerBtcTransaction(mock(Transaction.class), tx1.bitcoinSerialize(), height, pmtWithWitness.bitcoinSerialize()); verify(provider, never()).setHeightBtcTxhashAlreadyProcessed(tx1.getHash(true), height); verify(provider, never()).setHeightBtcTxhashAlreadyProcessed(any(Sha256Hash.class), anyLong()); }
@Test public void registerBtcTransaction_rejects_tx_without_witness_unequal_roots_after_rskip_143() throws BlockStoreException, IOException { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); Repository repository = createRepository(); BtcTransaction tx1 = new BtcTransaction(btcParams); BtcECKey srcKey1 = new BtcECKey(); ECKey key = ECKey.fromPublicOnly(srcKey1.getPubKey()); Address btcAddress = srcKey1.toAddress(btcParams); RskAddress rskAddress = new RskAddress(key.getAddress()); Coin amountToLock = Coin.COIN.multiply(10); tx1.addOutput(amountToLock, Address.fromBase58(BridgeRegTestConstants.getInstance().getBtcParams(), "mvbnrCX3bg1cDRUu8pkecrvP6vQkSLDSou")); tx1.addInput(PegTestUtils.createHash(1), 0, new Script(new byte[]{})); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(tx1.getHash()); PartialMerkleTree pmtWithoutWitness = new PartialMerkleTree(btcParams, bits, hashes, 1); List<Sha256Hash> hashlist = new ArrayList<>(); Sha256Hash blockMerkleRoot = pmtWithoutWitness.getTxnHashAndMerkleRoot(hashlist); co.rsk.bitcoinj.core.BtcBlock registerHeader = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(1), blockMerkleRoot, 1, 1, 1, new ArrayList<>() ); int height = 50; StoredBlock block = new StoredBlock(registerHeader, new BigInteger("0"), height); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); co.rsk.bitcoinj.core.BtcBlock headBlock = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(2), Sha256Hash.of(new byte[]{1}), 1, 1, 1, new ArrayList<>() ); StoredBlock chainHead = new StoredBlock(headBlock, new BigInteger("0"), 132); when(btcBlockStore.getChainHead()).thenReturn(chainHead); when(btcBlockStore.getStoredBlockAtMainChainHeight(block.getHeight())).thenReturn(block); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(any())).thenReturn(btcBlockStore); BridgeStorageProvider provider = spy(new BridgeStorageProvider(repository, contractAddress, bridgeConstants, activations)); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, getBtcLockSenderProvider(BtcLockSender.TxType.P2PKH, btcAddress, rskAddress), mock(Block.class), mockFactory, activations ); bridgeSupport.registerBtcTransaction(mock(Transaction.class), tx1.bitcoinSerialize(), height, pmtWithoutWitness.bitcoinSerialize()); verify(provider, never()).setHeightBtcTxhashAlreadyProcessed(tx1.getHash(), height); verify(provider, never()).setHeightBtcTxhashAlreadyProcessed(any(Sha256Hash.class), anyLong()); }
@Test public void registerBtcTransaction_accepts_lock_tx_without_witness_after_rskip_143_activation() throws BlockStoreException, IOException { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); List<BtcECKey> federation1Keys = Arrays.asList( BtcECKey.fromPrivate(Hex.decode("fa01")), BtcECKey.fromPrivate(Hex.decode("fa02")) ); federation1Keys.sort(BtcECKey.PUBKEY_COMPARATOR); Federation federation1 = new Federation( FederationTestUtils.getFederationMembersWithBtcKeys(federation1Keys), Instant.ofEpochMilli(1000L), 0L, btcParams ); Repository repository = createRepository(); BtcTransaction tx1 = new BtcTransaction(btcParams); BtcECKey srcKey1 = new BtcECKey(); ECKey key = ECKey.fromPublicOnly(srcKey1.getPubKey()); Address btcAddress = srcKey1.toAddress(btcParams); RskAddress rskAddress = new RskAddress(key.getAddress()); Coin amountToLock = Coin.COIN.multiply(10); tx1.addOutput(amountToLock, federation1.getAddress()); tx1.addInput(PegTestUtils.createHash(1), 0, new Script(new byte[]{})); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(tx1.getHash()); PartialMerkleTree pmtWithoutWitness = new PartialMerkleTree(btcParams, bits, hashes, 1); List<Sha256Hash> hashlist = new ArrayList<>(); Sha256Hash blockMerkleRoot = pmtWithoutWitness.getTxnHashAndMerkleRoot(hashlist); co.rsk.bitcoinj.core.BtcBlock registerHeader = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(1), blockMerkleRoot, 1, 1, 1, new ArrayList<>() ); int height = 50; StoredBlock block = new StoredBlock(registerHeader, new BigInteger("0"), height); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); co.rsk.bitcoinj.core.BtcBlock headBlock = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(2), Sha256Hash.of(new byte[]{1}), 1, 1, 1, new ArrayList<>() ); StoredBlock chainHead = new StoredBlock(headBlock, new BigInteger("0"), 132); when(btcBlockStore.getChainHead()).thenReturn(chainHead); when(btcBlockStore.getStoredBlockAtMainChainHeight(block.getHeight())).thenReturn(block); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(any())).thenReturn(btcBlockStore); BridgeStorageProvider provider = new BridgeStorageProvider(repository, contractAddress, bridgeConstants, activations); provider.setNewFederation(federation1); LockWhitelist whitelist = provider.getLockWhitelist(); whitelist.put(btcAddress, new OneOffWhiteListEntry(btcAddress, Coin.COIN.multiply(10))); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, getBtcLockSenderProvider(BtcLockSender.TxType.P2PKH, btcAddress, rskAddress), mock(Block.class), mockFactory, activations ); bridgeSupport.registerBtcTransaction(mock(Transaction.class), tx1.bitcoinSerialize(), height, pmtWithoutWitness.bitcoinSerialize()); co.rsk.core.Coin totalAmountExpectedToHaveBeenLocked = co.rsk.core.Coin.fromBitcoin(amountToLock); Assert.assertEquals(totalAmountExpectedToHaveBeenLocked, repository.getBalance(rskAddress)); Assert.assertEquals(1, provider.getNewFederationBtcUTXOs().size()); Assert.assertEquals(amountToLock, provider.getNewFederationBtcUTXOs().get(0).getValue()); Assert.assertEquals(0, provider.getReleaseRequestQueue().getEntries().size()); Assert.assertEquals(0, provider.getReleaseTransactionSet().getEntries().size()); Assert.assertTrue(provider.getRskTxsWaitingForSignatures().isEmpty()); Assert.assertTrue(provider.getHeightIfBtcTxhashIsAlreadyProcessed(tx1.getHash(true)).isPresent()); } |
BridgeSupport { public void updateCollections(Transaction rskTx) throws IOException { Context.propagate(btcContext); eventLogger.logUpdateCollections(rskTx); processFundsMigration(rskTx); processReleaseRequests(); processReleaseTransactions(rskTx); } BridgeSupport(
BridgeConstants bridgeConstants,
BridgeStorageProvider provider,
BridgeEventLogger eventLogger,
BtcLockSenderProvider btcLockSenderProvider,
Repository repository,
Block executionBlock,
Context btcContext,
FederationSupport federationSupport,
BtcBlockStoreWithCache.Factory btcBlockStoreFactory,
ActivationConfig.ForBlock activations); List<ProgramSubtrace> getSubtraces(); void save(); void receiveHeaders(BtcBlock[] headers); Wallet getActiveFederationWallet(); Wallet getRetiringFederationWallet(); Wallet getUTXOBasedWalletForLiveFederations(List<UTXO> utxos); Wallet getNoSpendWalletForLiveFederations(); void registerBtcTransaction(Transaction rskTx, byte[] btcTxSerialized, int height, byte[] pmtSerialized); void releaseBtc(Transaction rskTx); Coin getFeePerKb(); void updateCollections(Transaction rskTx); void addSignature(BtcECKey federatorPublicKey, List<byte[]> signatures, byte[] rskTxHash); byte[] getStateForBtcReleaseClient(); byte[] getStateForDebugging(); int getBtcBlockchainBestChainHeight(); int getBtcBlockchainInitialBlockHeight(); @Deprecated List<Sha256Hash> getBtcBlockchainBlockLocator(); Sha256Hash getBtcBlockchainBlockHashAtDepth(int depth); Long getBtcTransactionConfirmationsGetCost(Object[] args); Integer getBtcTransactionConfirmations(Sha256Hash btcTxHash, Sha256Hash btcBlockHash, MerkleBranch merkleBranch); Boolean isBtcTxHashAlreadyProcessed(Sha256Hash btcTxHash); Long getBtcTxHashProcessedHeight(Sha256Hash btcTxHash); boolean isAlreadyBtcTxHashProcessed(Sha256Hash btcTxHash); Federation getActiveFederation(); @Nullable Federation getRetiringFederation(); Address getFederationAddress(); Integer getFederationSize(); Integer getFederationThreshold(); byte[] getFederatorPublicKey(int index); byte[] getFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getFederationCreationTime(); long getFederationCreationBlockNumber(); Address getRetiringFederationAddress(); Integer getRetiringFederationSize(); Integer getRetiringFederationThreshold(); byte[] getRetiringFederatorPublicKey(int index); byte[] getRetiringFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getRetiringFederationCreationTime(); long getRetiringFederationCreationBlockNumber(); Integer voteFederationChange(Transaction tx, ABICallSpec callSpec); byte[] getPendingFederationHash(); Integer getPendingFederationSize(); byte[] getPendingFederatorPublicKey(int index); byte[] getPendingFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Integer getLockWhitelistSize(); LockWhitelistEntry getLockWhitelistEntryByIndex(int index); LockWhitelistEntry getLockWhitelistEntryByAddress(String addressBase58); Integer addOneOffLockWhitelistAddress(Transaction tx, String addressBase58, BigInteger maxTransferValue); Integer addUnlimitedLockWhitelistAddress(Transaction tx, String addressBase58); Integer removeLockWhitelistAddress(Transaction tx, String addressBase58); Coin getMinimumLockTxValue(); Integer voteFeePerKbChange(Transaction tx, Coin feePerKb); Integer setLockWhitelistDisableBlockDelay(Transaction tx, BigInteger disableBlockDelayBI); Coin getLockingCap(); boolean increaseLockingCap(Transaction tx, Coin newCap); void registerBtcCoinbaseTransaction(byte[] btcTxSerialized, Sha256Hash blockHash, byte[] pmtSerialized, Sha256Hash witnessMerkleRoot, byte[] witnessReservedValue); boolean hasBtcBlockCoinbaseTransactionInformation(Sha256Hash blockHash); static final RskAddress BURN_ADDRESS; static final int MAX_RELEASE_ITERATIONS; static final Integer FEDERATION_CHANGE_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_INVALID_ADDRESS_FORMAT_ERROR_CODE; static final Integer LOCK_WHITELIST_ALREADY_EXISTS_ERROR_CODE; static final Integer LOCK_WHITELIST_UNKNOWN_ERROR_CODE; static final Integer LOCK_WHITELIST_SUCCESS_CODE; static final Integer FEE_PER_KB_GENERIC_ERROR_CODE; static final Integer NEGATIVE_FEE_PER_KB_ERROR_CODE; static final Integer EXCESSIVE_FEE_PER_KB_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INEXISTENT_BLOCK_HASH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_NOT_IN_BEST_CHAIN_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INCONSISTENT_BLOCK_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_TOO_OLD_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INVALID_MERKLE_BRANCH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_MAX_DEPTH; } | @Test public void rskTxWaitingForSignature_uses_updateCollection_rskTxHash_before_rskip_146_activation() throws IOException { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP146)).thenReturn(false); BridgeConstants spiedBridgeConstants = spy(BridgeRegTestConstants.getInstance()); doReturn(1).when(spiedBridgeConstants).getRsk2BtcMinimumAcceptableConfirmations(); BridgeStorageProvider provider = mock(BridgeStorageProvider.class); BtcTransaction btcTx = mock(BtcTransaction.class); Set<ReleaseTransactionSet.Entry> set = new HashSet<>(); set.add(new ReleaseTransactionSet.Entry(btcTx, 1L)); when(provider.getReleaseTransactionSet()).thenReturn(new ReleaseTransactionSet(set)); when(provider.getReleaseRequestQueue()).thenReturn(new ReleaseRequestQueue(Collections.emptyList())); when(provider.getRskTxsWaitingForSignatures()).thenReturn(new TreeMap<>()); Block executionBlock = mock(Block.class); when(executionBlock.getNumber()).thenReturn(2L); BridgeSupport bridgeSupport = getBridgeSupport(spiedBridgeConstants, provider, mock(Repository.class), mock(BridgeEventLogger.class), executionBlock, null, activations ); Transaction tx = new Transaction(TO_ADDRESS, DUST_AMOUNT, NONCE, GAS_PRICE, GAS_LIMIT, DATA, Constants.REGTEST_CHAIN_ID); bridgeSupport.updateCollections(tx); assertEquals(btcTx, provider.getRskTxsWaitingForSignatures().get(tx.getHash())); assertEquals(0, provider.getReleaseTransactionSet().getEntries().size()); }
@Test public void rskTxWaitingForSignature_uses_updateCollection_rskTxHash_after_rskip_146_activation_if_release_transaction_doesnt_have_rstTxHash() throws IOException { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP146)).thenReturn(true); BridgeConstants spiedBridgeConstants = spy(BridgeRegTestConstants.getInstance()); doReturn(1).when(spiedBridgeConstants).getRsk2BtcMinimumAcceptableConfirmations(); BridgeStorageProvider provider = mock(BridgeStorageProvider.class); BtcTransaction btcTx = mock(BtcTransaction.class); Set<ReleaseTransactionSet.Entry> set = new HashSet<>(); set.add(new ReleaseTransactionSet.Entry(btcTx, 1L)); when(provider.getReleaseTransactionSet()).thenReturn(new ReleaseTransactionSet(set)); when(provider.getReleaseRequestQueue()).thenReturn(new ReleaseRequestQueue(Collections.emptyList())); when(provider.getRskTxsWaitingForSignatures()).thenReturn(new TreeMap<>()); Block executionBlock = mock(Block.class); when(executionBlock.getNumber()).thenReturn(2L); BridgeSupport bridgeSupport = getBridgeSupport(spiedBridgeConstants, provider, mock(Repository.class), mock(BridgeEventLogger.class), executionBlock, null, activations ); Transaction tx = new Transaction(TO_ADDRESS, DUST_AMOUNT, NONCE, GAS_PRICE, GAS_LIMIT, DATA, Constants.REGTEST_CHAIN_ID); bridgeSupport.updateCollections(tx); assertEquals(btcTx, provider.getRskTxsWaitingForSignatures().get(tx.getHash())); assertEquals(0, provider.getReleaseTransactionSet().getEntries().size()); }
@Test public void rskTxWaitingForSignature_uses_release_transaction_rstTxHash_after_rskip_146_activation() throws IOException { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP146)).thenReturn(true); BridgeConstants spiedBridgeConstants = spy(BridgeRegTestConstants.getInstance()); doReturn(1).when(spiedBridgeConstants).getRsk2BtcMinimumAcceptableConfirmations(); BridgeStorageProvider provider = mock(BridgeStorageProvider.class); BtcTransaction btcTx = mock(BtcTransaction.class); Set<ReleaseTransactionSet.Entry> set = new HashSet<>(); Keccak256 rskTxHash = Keccak256.ZERO_HASH; set.add(new ReleaseTransactionSet.Entry(btcTx, 1L, rskTxHash)); when(provider.getReleaseTransactionSet()).thenReturn(new ReleaseTransactionSet(set)); when(provider.getReleaseRequestQueue()).thenReturn(new ReleaseRequestQueue(Collections.emptyList())); when(provider.getRskTxsWaitingForSignatures()).thenReturn(new TreeMap<>()); Block executionBlock = mock(Block.class); when(executionBlock.getNumber()).thenReturn(2L); BridgeSupport bridgeSupport = getBridgeSupport(spiedBridgeConstants, provider, mock(Repository.class), mock(BridgeEventLogger.class), executionBlock, null, activations ); Transaction tx = new Transaction(TO_ADDRESS, DUST_AMOUNT, NONCE, GAS_PRICE, GAS_LIMIT, DATA, Constants.REGTEST_CHAIN_ID); bridgeSupport.updateCollections(tx); assertEquals(btcTx, provider.getRskTxsWaitingForSignatures().get(rskTxHash)); assertEquals(0, provider.getReleaseTransactionSet().getEntries().size()); } |
Value { public String toString() { StringBuilder stringBuilder = new StringBuilder(); if (isList()) { Object[] list = (Object[]) value; if (list.length == 2) { stringBuilder.append("[ "); Value key = new Value(list[0]); byte[] keyNibbles = CompactEncoder.binToNibblesNoTerminator(key.asBytes()); String keyString = ByteUtil.nibblesToPrettyString(keyNibbles); stringBuilder.append(keyString); stringBuilder.append(","); Value val = new Value(list[1]); stringBuilder.append(val.toString()); stringBuilder.append(" ]"); return stringBuilder.toString(); } stringBuilder.append(" ["); for (int i = 0; i < list.length; ++i) { Value val = new Value(list[i]); if (val.isString() || val.isEmpty()) { stringBuilder.append("'").append(val.toString()).append("'"); } else { stringBuilder.append(val.toString()); } if (i < list.length - 1) { stringBuilder.append(", "); } } stringBuilder.append("] "); return stringBuilder.toString(); } else if (isEmpty()) { return ""; } else if (isBytes()) { StringBuilder output = new StringBuilder(); if (isHashCode()) { output.append(ByteUtil.toHexString(asBytes())); } else if (isReadableString()) { output.append("'"); for (byte oneByte : asBytes()) { if (oneByte < 16) { output.append("\\x").append(ByteUtil.oneByteToHexString(oneByte)); } else { output.append(Character.valueOf((char) oneByte)); } } output.append("'"); return output.toString(); } return ByteUtil.toHexString(this.asBytes()); } else if (isString()) { return asString(); } return "Unexpected type"; } Value(); Value(Object obj); static Value fromRlpEncoded(byte[] data); void init(byte[] rlp); Object asObj(); List<Object> asList(); int asInt(); long asLong(); BigInteger asBigInt(); String asString(); byte[] asBytes(); String getHex(); byte[] getData(); int[] asSlice(); Value get(int index); byte[] encode(); byte[] hash(); boolean isList(); boolean isString(); boolean isInt(); boolean isLong(); boolean isBigInt(); boolean isBytes(); boolean isReadableString(); boolean isHexString(); boolean isHashCode(); boolean isNull(); boolean isEmpty(); int length(); String toString(); } | @Test public void toString_Empty() { Value val = new Value(null); String str = val.toString(); assertEquals("", str); }
@Test public void toString_SameString() { Value val = new Value("hello"); String str = val.toString(); assertEquals("hello", str); }
@Test public void toString_Array() { Value val = new Value(new String[] {"hello", "world", "!"}); String str = val.toString(); assertEquals(" ['hello', 'world', '!'] ", str); }
@Test public void toString_UnsupportedType() { Value val = new Value('a'); String str = val.toString(); assertEquals("Unexpected type", str); } |
BridgeSupport { @VisibleForTesting protected boolean isBlockMerkleRootValid(Sha256Hash merkleRoot, BtcBlock blockHeader) { boolean isValid = false; if (blockHeader.getMerkleRoot().equals(merkleRoot)) { logger.trace("block merkle root is valid"); isValid = true; } else { if (activations.isActive(ConsensusRule.RSKIP143)) { CoinbaseInformation coinbaseInformation = provider.getCoinbaseInformation(blockHeader.getHash()); if (coinbaseInformation == null) { logger.trace("coinbase information for block {} is not yet registered", blockHeader.getHash()); } isValid = coinbaseInformation != null && coinbaseInformation.getWitnessMerkleRoot().equals(merkleRoot); logger.trace("witness merkle root is {} valid", (isValid ? "":"NOT")); } else { logger.trace("RSKIP143 is not active, avoid checking witness merkle root"); } } return isValid; } BridgeSupport(
BridgeConstants bridgeConstants,
BridgeStorageProvider provider,
BridgeEventLogger eventLogger,
BtcLockSenderProvider btcLockSenderProvider,
Repository repository,
Block executionBlock,
Context btcContext,
FederationSupport federationSupport,
BtcBlockStoreWithCache.Factory btcBlockStoreFactory,
ActivationConfig.ForBlock activations); List<ProgramSubtrace> getSubtraces(); void save(); void receiveHeaders(BtcBlock[] headers); Wallet getActiveFederationWallet(); Wallet getRetiringFederationWallet(); Wallet getUTXOBasedWalletForLiveFederations(List<UTXO> utxos); Wallet getNoSpendWalletForLiveFederations(); void registerBtcTransaction(Transaction rskTx, byte[] btcTxSerialized, int height, byte[] pmtSerialized); void releaseBtc(Transaction rskTx); Coin getFeePerKb(); void updateCollections(Transaction rskTx); void addSignature(BtcECKey federatorPublicKey, List<byte[]> signatures, byte[] rskTxHash); byte[] getStateForBtcReleaseClient(); byte[] getStateForDebugging(); int getBtcBlockchainBestChainHeight(); int getBtcBlockchainInitialBlockHeight(); @Deprecated List<Sha256Hash> getBtcBlockchainBlockLocator(); Sha256Hash getBtcBlockchainBlockHashAtDepth(int depth); Long getBtcTransactionConfirmationsGetCost(Object[] args); Integer getBtcTransactionConfirmations(Sha256Hash btcTxHash, Sha256Hash btcBlockHash, MerkleBranch merkleBranch); Boolean isBtcTxHashAlreadyProcessed(Sha256Hash btcTxHash); Long getBtcTxHashProcessedHeight(Sha256Hash btcTxHash); boolean isAlreadyBtcTxHashProcessed(Sha256Hash btcTxHash); Federation getActiveFederation(); @Nullable Federation getRetiringFederation(); Address getFederationAddress(); Integer getFederationSize(); Integer getFederationThreshold(); byte[] getFederatorPublicKey(int index); byte[] getFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getFederationCreationTime(); long getFederationCreationBlockNumber(); Address getRetiringFederationAddress(); Integer getRetiringFederationSize(); Integer getRetiringFederationThreshold(); byte[] getRetiringFederatorPublicKey(int index); byte[] getRetiringFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getRetiringFederationCreationTime(); long getRetiringFederationCreationBlockNumber(); Integer voteFederationChange(Transaction tx, ABICallSpec callSpec); byte[] getPendingFederationHash(); Integer getPendingFederationSize(); byte[] getPendingFederatorPublicKey(int index); byte[] getPendingFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Integer getLockWhitelistSize(); LockWhitelistEntry getLockWhitelistEntryByIndex(int index); LockWhitelistEntry getLockWhitelistEntryByAddress(String addressBase58); Integer addOneOffLockWhitelistAddress(Transaction tx, String addressBase58, BigInteger maxTransferValue); Integer addUnlimitedLockWhitelistAddress(Transaction tx, String addressBase58); Integer removeLockWhitelistAddress(Transaction tx, String addressBase58); Coin getMinimumLockTxValue(); Integer voteFeePerKbChange(Transaction tx, Coin feePerKb); Integer setLockWhitelistDisableBlockDelay(Transaction tx, BigInteger disableBlockDelayBI); Coin getLockingCap(); boolean increaseLockingCap(Transaction tx, Coin newCap); void registerBtcCoinbaseTransaction(byte[] btcTxSerialized, Sha256Hash blockHash, byte[] pmtSerialized, Sha256Hash witnessMerkleRoot, byte[] witnessReservedValue); boolean hasBtcBlockCoinbaseTransactionInformation(Sha256Hash blockHash); static final RskAddress BURN_ADDRESS; static final int MAX_RELEASE_ITERATIONS; static final Integer FEDERATION_CHANGE_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_INVALID_ADDRESS_FORMAT_ERROR_CODE; static final Integer LOCK_WHITELIST_ALREADY_EXISTS_ERROR_CODE; static final Integer LOCK_WHITELIST_UNKNOWN_ERROR_CODE; static final Integer LOCK_WHITELIST_SUCCESS_CODE; static final Integer FEE_PER_KB_GENERIC_ERROR_CODE; static final Integer NEGATIVE_FEE_PER_KB_ERROR_CODE; static final Integer EXCESSIVE_FEE_PER_KB_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INEXISTENT_BLOCK_HASH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_NOT_IN_BEST_CHAIN_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INCONSISTENT_BLOCK_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_TOO_OLD_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INVALID_MERKLE_BRANCH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_MAX_DEPTH; } | @Test public void isBlockMerkleRootValid_equal_merkle_roots() { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(false); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, mock(BridgeStorageProvider.class), mock(Repository.class), mock(BtcLockSenderProvider.class), mock(Block.class), mock(BtcBlockStoreWithCache.Factory.class), activations ); Sha256Hash merkleRoot = PegTestUtils.createHash(1); BtcBlock btcBlock = mock(BtcBlock.class); when(btcBlock.getMerkleRoot()).thenReturn(merkleRoot); Assert.assertTrue(bridgeSupport.isBlockMerkleRootValid(merkleRoot, btcBlock)); }
@Test public void isBlockMerkleRootValid_unequal_merkle_roots_before_rskip_143() { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(false); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, mock(BridgeStorageProvider.class), mock(Repository.class), mock(BtcLockSenderProvider.class), mock(Block.class), mock(BtcBlockStoreWithCache.Factory.class), activations ); Sha256Hash merkleRoot = PegTestUtils.createHash(1); BtcBlock btcBlock = mock(BtcBlock.class); when(btcBlock.getMerkleRoot()).thenReturn(Sha256Hash.ZERO_HASH); Assert.assertFalse(bridgeSupport.isBlockMerkleRootValid(merkleRoot, btcBlock)); }
@Test public void isBlockMerkleRootValid_coinbase_information_null_after_rskip_143() { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); BridgeStorageProvider provider = mock(BridgeStorageProvider.class); when(provider.getCoinbaseInformation(Sha256Hash.ZERO_HASH)).thenReturn(null); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, mock(Repository.class), mock(BtcLockSenderProvider.class), mock(Block.class), mock(BtcBlockStoreWithCache.Factory.class), activations ); BtcBlock btcBlock = mock(BtcBlock.class); when(btcBlock.getMerkleRoot()).thenReturn(Sha256Hash.ZERO_HASH); when(btcBlock.getHash()).thenReturn(Sha256Hash.ZERO_HASH); Assert.assertFalse(bridgeSupport.isBlockMerkleRootValid(PegTestUtils.createHash(1), btcBlock)); }
@Test public void isBlockMerkleRootValid_coinbase_information_not_null_and_unequal_mroots_after_rskip_143() { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); CoinbaseInformation coinbaseInformation = new CoinbaseInformation(PegTestUtils.createHash(1)); BridgeStorageProvider provider = mock(BridgeStorageProvider.class); when(provider.getCoinbaseInformation(Sha256Hash.ZERO_HASH)).thenReturn(coinbaseInformation); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, mock(Repository.class), mock(BtcLockSenderProvider.class), mock(Block.class), mock(BtcBlockStoreWithCache.Factory.class), activations ); BtcBlock btcBlock = mock(BtcBlock.class); when(btcBlock.getMerkleRoot()).thenReturn(Sha256Hash.ZERO_HASH); when(btcBlock.getHash()).thenReturn(Sha256Hash.ZERO_HASH); Assert.assertFalse(bridgeSupport.isBlockMerkleRootValid(PegTestUtils.createHash(2), btcBlock)); }
@Test public void isBlockMerkleRootValid_coinbase_information_not_null_and_equal_mroots_after_rskip_143() { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); Sha256Hash merkleRoot = PegTestUtils.createHash(1); CoinbaseInformation coinbaseInformation = new CoinbaseInformation(merkleRoot); BridgeStorageProvider provider = mock(BridgeStorageProvider.class); when(provider.getCoinbaseInformation(Sha256Hash.ZERO_HASH)).thenReturn(coinbaseInformation); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, mock(Repository.class), mock(BtcLockSenderProvider.class), mock(Block.class), mock(BtcBlockStoreWithCache.Factory.class), activations ); BtcBlock btcBlock = mock(BtcBlock.class); when(btcBlock.getMerkleRoot()).thenReturn(Sha256Hash.ZERO_HASH); when(btcBlock.getHash()).thenReturn(Sha256Hash.ZERO_HASH); Assert.assertTrue(bridgeSupport.isBlockMerkleRootValid(merkleRoot, btcBlock)); } |
BridgeSupport { public Integer getBtcTransactionConfirmations(Sha256Hash btcTxHash, Sha256Hash btcBlockHash, MerkleBranch merkleBranch) throws BlockStoreException, IOException { Context.propagate(btcContext); this.ensureBtcBlockChain(); StoredBlock block = btcBlockStore.getFromCache(btcBlockHash); if (block == null) { return BTC_TRANSACTION_CONFIRMATION_INEXISTENT_BLOCK_HASH_ERROR_CODE; } final int bestChainHeight = getBtcBlockchainBestChainHeight(); final int blockDepth = Math.max(0, bestChainHeight - block.getHeight()); if (blockDepth > BTC_TRANSACTION_CONFIRMATION_MAX_DEPTH) { return BTC_TRANSACTION_CONFIRMATION_BLOCK_TOO_OLD_ERROR_CODE; } try { StoredBlock storedBlock = btcBlockStore.getStoredBlockAtMainChainHeight(block.getHeight()); if (storedBlock == null || !storedBlock.equals(block)){ return BTC_TRANSACTION_CONFIRMATION_BLOCK_NOT_IN_BEST_CHAIN_ERROR_CODE; } } catch (BlockStoreException e) { logger.warn(String.format( "Illegal state trying to get block with hash %s", btcBlockHash ), e); return BTC_TRANSACTION_CONFIRMATION_INCONSISTENT_BLOCK_ERROR_CODE; } Sha256Hash merkleRoot = merkleBranch.reduceFrom(btcTxHash); if (!isBlockMerkleRootValid(merkleRoot, block.getHeader())) { return BTC_TRANSACTION_CONFIRMATION_INVALID_MERKLE_BRANCH_ERROR_CODE; } return bestChainHeight - block.getHeight() + 1; } BridgeSupport(
BridgeConstants bridgeConstants,
BridgeStorageProvider provider,
BridgeEventLogger eventLogger,
BtcLockSenderProvider btcLockSenderProvider,
Repository repository,
Block executionBlock,
Context btcContext,
FederationSupport federationSupport,
BtcBlockStoreWithCache.Factory btcBlockStoreFactory,
ActivationConfig.ForBlock activations); List<ProgramSubtrace> getSubtraces(); void save(); void receiveHeaders(BtcBlock[] headers); Wallet getActiveFederationWallet(); Wallet getRetiringFederationWallet(); Wallet getUTXOBasedWalletForLiveFederations(List<UTXO> utxos); Wallet getNoSpendWalletForLiveFederations(); void registerBtcTransaction(Transaction rskTx, byte[] btcTxSerialized, int height, byte[] pmtSerialized); void releaseBtc(Transaction rskTx); Coin getFeePerKb(); void updateCollections(Transaction rskTx); void addSignature(BtcECKey federatorPublicKey, List<byte[]> signatures, byte[] rskTxHash); byte[] getStateForBtcReleaseClient(); byte[] getStateForDebugging(); int getBtcBlockchainBestChainHeight(); int getBtcBlockchainInitialBlockHeight(); @Deprecated List<Sha256Hash> getBtcBlockchainBlockLocator(); Sha256Hash getBtcBlockchainBlockHashAtDepth(int depth); Long getBtcTransactionConfirmationsGetCost(Object[] args); Integer getBtcTransactionConfirmations(Sha256Hash btcTxHash, Sha256Hash btcBlockHash, MerkleBranch merkleBranch); Boolean isBtcTxHashAlreadyProcessed(Sha256Hash btcTxHash); Long getBtcTxHashProcessedHeight(Sha256Hash btcTxHash); boolean isAlreadyBtcTxHashProcessed(Sha256Hash btcTxHash); Federation getActiveFederation(); @Nullable Federation getRetiringFederation(); Address getFederationAddress(); Integer getFederationSize(); Integer getFederationThreshold(); byte[] getFederatorPublicKey(int index); byte[] getFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getFederationCreationTime(); long getFederationCreationBlockNumber(); Address getRetiringFederationAddress(); Integer getRetiringFederationSize(); Integer getRetiringFederationThreshold(); byte[] getRetiringFederatorPublicKey(int index); byte[] getRetiringFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getRetiringFederationCreationTime(); long getRetiringFederationCreationBlockNumber(); Integer voteFederationChange(Transaction tx, ABICallSpec callSpec); byte[] getPendingFederationHash(); Integer getPendingFederationSize(); byte[] getPendingFederatorPublicKey(int index); byte[] getPendingFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Integer getLockWhitelistSize(); LockWhitelistEntry getLockWhitelistEntryByIndex(int index); LockWhitelistEntry getLockWhitelistEntryByAddress(String addressBase58); Integer addOneOffLockWhitelistAddress(Transaction tx, String addressBase58, BigInteger maxTransferValue); Integer addUnlimitedLockWhitelistAddress(Transaction tx, String addressBase58); Integer removeLockWhitelistAddress(Transaction tx, String addressBase58); Coin getMinimumLockTxValue(); Integer voteFeePerKbChange(Transaction tx, Coin feePerKb); Integer setLockWhitelistDisableBlockDelay(Transaction tx, BigInteger disableBlockDelayBI); Coin getLockingCap(); boolean increaseLockingCap(Transaction tx, Coin newCap); void registerBtcCoinbaseTransaction(byte[] btcTxSerialized, Sha256Hash blockHash, byte[] pmtSerialized, Sha256Hash witnessMerkleRoot, byte[] witnessReservedValue); boolean hasBtcBlockCoinbaseTransactionInformation(Sha256Hash blockHash); static final RskAddress BURN_ADDRESS; static final int MAX_RELEASE_ITERATIONS; static final Integer FEDERATION_CHANGE_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_INVALID_ADDRESS_FORMAT_ERROR_CODE; static final Integer LOCK_WHITELIST_ALREADY_EXISTS_ERROR_CODE; static final Integer LOCK_WHITELIST_UNKNOWN_ERROR_CODE; static final Integer LOCK_WHITELIST_SUCCESS_CODE; static final Integer FEE_PER_KB_GENERIC_ERROR_CODE; static final Integer NEGATIVE_FEE_PER_KB_ERROR_CODE; static final Integer EXCESSIVE_FEE_PER_KB_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INEXISTENT_BLOCK_HASH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_NOT_IN_BEST_CHAIN_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INCONSISTENT_BLOCK_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_TOO_OLD_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INVALID_MERKLE_BRANCH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_MAX_DEPTH; } | @Test public void getBtcTransactionConfirmations_rejects_tx_with_witness_before_rskip_143() throws Exception { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(false); BtcTransaction tx1 = new BtcTransaction(btcParams); tx1.addOutput(Coin.COIN.multiply(10), Address.fromBase58(BridgeRegTestConstants.getInstance().getBtcParams(), "mvbnrCX3bg1cDRUu8pkecrvP6vQkSLDSou")); tx1.addInput(PegTestUtils.createHash(1), 0, new Script(new byte[]{})); TransactionWitness txWit = new TransactionWitness(1); txWit.setPush(0, new byte[]{}); tx1.setWitness(0, txWit); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(tx1.getHash()); PartialMerkleTree pmt = new PartialMerkleTree(btcParams, bits, hashes, 1); List<Sha256Hash> hashlist = new ArrayList<>(); Sha256Hash blockMerkleRoot = pmt.getTxnHashAndMerkleRoot(hashlist); co.rsk.bitcoinj.core.BtcBlock registerHeader = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(1), blockMerkleRoot, 1, 1, 1, new ArrayList<>() ); int height = 50; StoredBlock block = new StoredBlock(registerHeader, new BigInteger("0"), height); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); when(btcBlockStore.getFromCache(registerHeader.getHash())).thenReturn(block); StoredBlock chainHead = new StoredBlock(registerHeader, new BigInteger("0"), 132); when(btcBlockStore.getChainHead()).thenReturn(chainHead); when(btcBlockStore.getStoredBlockAtMainChainHeight(block.getHeight())).thenReturn(block); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(any())).thenReturn(btcBlockStore); BridgeStorageProvider provider = mock(BridgeStorageProvider.class); BridgeSupport bridgeSupport = getBridgeSupport(provider, mock(Repository.class), mockFactory); MerkleBranch merkleBranch = mock(MerkleBranch.class); int confirmations = bridgeSupport.getBtcTransactionConfirmations(tx1.getHash(true), registerHeader.getHash(), merkleBranch); Assert.assertEquals(-5, confirmations); }
@Test public void getBtcTransactionConfirmations_accepts_tx_with_witness_after_rskip_143() throws Exception { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); Repository repository = createRepository(); BtcTransaction tx1 = new BtcTransaction(btcParams); tx1.addOutput(Coin.COIN.multiply(10), Address.fromBase58(BridgeRegTestConstants.getInstance().getBtcParams(), "mvbnrCX3bg1cDRUu8pkecrvP6vQkSLDSou")); tx1.addInput(PegTestUtils.createHash(1), 0, new Script(new byte[]{})); TransactionWitness txWit = new TransactionWitness(1); txWit.setPush(0, new byte[]{}); tx1.setWitness(0, txWit); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(tx1.getHash()); PartialMerkleTree pmt = new PartialMerkleTree(btcParams, bits, hashes, 1); List<Sha256Hash> hashlist = new ArrayList<>(); Sha256Hash blockMerkleRoot = pmt.getTxnHashAndMerkleRoot(hashlist); co.rsk.bitcoinj.core.BtcBlock registerHeader = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(1), blockMerkleRoot, 1, 1, 1, new ArrayList<>() ); List<Sha256Hash> hashes2 = new ArrayList<>(); hashes2.add(tx1.getHash(true)); PartialMerkleTree pmt2 = new PartialMerkleTree(btcParams, bits, hashes2, 1); List<Sha256Hash> hashlist2 = new ArrayList<>(); Sha256Hash witnessMerkleRoot = pmt2.getTxnHashAndMerkleRoot(hashlist2); int height = 50; StoredBlock block = new StoredBlock(registerHeader, new BigInteger("0"), height); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); when(btcBlockStore.getFromCache(registerHeader.getHash())).thenReturn(block); StoredBlock chainHead = new StoredBlock(registerHeader, new BigInteger("0"), 132); when(btcBlockStore.getChainHead()).thenReturn(chainHead); when(btcBlockStore.getStoredBlockAtMainChainHeight(block.getHeight())).thenReturn(block); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(any())).thenReturn(btcBlockStore); BridgeStorageProvider provider = spy(new BridgeStorageProvider(repository, PrecompiledContracts.BRIDGE_ADDR, bridgeConstants, activations)); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, mock(BtcLockSenderProvider.class), mock(Block.class), mockFactory, activations ); MerkleBranch merkleBranch = mock(MerkleBranch.class); when(merkleBranch.reduceFrom(tx1.getHash(true))).thenReturn(witnessMerkleRoot); CoinbaseInformation coinbaseInformation = new CoinbaseInformation(witnessMerkleRoot); provider.setCoinbaseInformation(registerHeader.getHash(), coinbaseInformation); int confirmations = bridgeSupport.getBtcTransactionConfirmations(tx1.getHash(true), registerHeader.getHash(), merkleBranch); Assert.assertEquals(chainHead.getHeight() - block.getHeight() + 1, confirmations); }
@Test public void getBtcTransactionConfirmations_unregistered_coinbase_after_rskip_143() throws Exception { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); Repository repository = createRepository(); BtcTransaction tx1 = new BtcTransaction(btcParams); tx1.addOutput(Coin.COIN.multiply(10), Address.fromBase58(BridgeRegTestConstants.getInstance().getBtcParams(), "mvbnrCX3bg1cDRUu8pkecrvP6vQkSLDSou")); tx1.addInput(PegTestUtils.createHash(1), 0, new Script(new byte[]{})); TransactionWitness txWit = new TransactionWitness(1); txWit.setPush(0, new byte[]{}); tx1.setWitness(0, txWit); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(tx1.getHash()); PartialMerkleTree pmt = new PartialMerkleTree(btcParams, bits, hashes, 1); List<Sha256Hash> hashlist = new ArrayList<>(); Sha256Hash blockMerkleRoot = pmt.getTxnHashAndMerkleRoot(hashlist); co.rsk.bitcoinj.core.BtcBlock registerHeader = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(1), blockMerkleRoot, 1, 1, 1, new ArrayList<>() ); List<Sha256Hash> hashes2 = new ArrayList<>(); hashes2.add(tx1.getHash(true)); PartialMerkleTree pmt2 = new PartialMerkleTree(btcParams, bits, hashes2, 1); List<Sha256Hash> hashlist2 = new ArrayList<>(); Sha256Hash witnessMerkleRoot = pmt2.getTxnHashAndMerkleRoot(hashlist2); int height = 50; StoredBlock block = new StoredBlock(registerHeader, new BigInteger("0"), height); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); when(btcBlockStore.getFromCache(registerHeader.getHash())).thenReturn(block); StoredBlock chainHead = new StoredBlock(registerHeader, new BigInteger("0"), 132); when(btcBlockStore.getChainHead()).thenReturn(chainHead); when(btcBlockStore.getStoredBlockAtMainChainHeight(block.getHeight())).thenReturn(block); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(any())).thenReturn(btcBlockStore); BridgeStorageProvider provider = spy(new BridgeStorageProvider(repository, PrecompiledContracts.BRIDGE_ADDR, bridgeConstants, activations)); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, mock(BtcLockSenderProvider.class), mock(Block.class), mockFactory, activations ); MerkleBranch merkleBranch = mock(MerkleBranch.class); when(merkleBranch.reduceFrom(tx1.getHash(true))).thenReturn(witnessMerkleRoot); int confirmations = bridgeSupport.getBtcTransactionConfirmations(tx1.getHash(true), registerHeader.getHash(), merkleBranch); Assert.assertEquals(-5, confirmations); }
@Test public void getBtcTransactionConfirmations_registered_coinbase_unequal_witnessroot_after_rskip_143() throws Exception { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); Repository repository = createRepository(); BtcTransaction tx1 = new BtcTransaction(btcParams); tx1.addOutput(Coin.COIN.multiply(10), Address.fromBase58(BridgeRegTestConstants.getInstance().getBtcParams(), "mvbnrCX3bg1cDRUu8pkecrvP6vQkSLDSou")); tx1.addInput(PegTestUtils.createHash(1), 0, new Script(new byte[]{})); TransactionWitness txWit = new TransactionWitness(1); txWit.setPush(0, new byte[]{}); tx1.setWitness(0, txWit); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(tx1.getHash()); PartialMerkleTree pmt = new PartialMerkleTree(btcParams, bits, hashes, 1); List<Sha256Hash> hashlist = new ArrayList<>(); Sha256Hash blockMerkleRoot = pmt.getTxnHashAndMerkleRoot(hashlist); co.rsk.bitcoinj.core.BtcBlock registerHeader = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(1), blockMerkleRoot, 1, 1, 1, new ArrayList<>() ); List<Sha256Hash> hashes2 = new ArrayList<>(); hashes2.add(tx1.getHash(true)); PartialMerkleTree pmt2 = new PartialMerkleTree(btcParams, bits, hashes2, 1); List<Sha256Hash> hashlist2 = new ArrayList<>(); Sha256Hash witnessMerkleRoot = pmt2.getTxnHashAndMerkleRoot(hashlist2); int height = 50; StoredBlock block = new StoredBlock(registerHeader, new BigInteger("0"), height); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); when(btcBlockStore.getFromCache(registerHeader.getHash())).thenReturn(block); StoredBlock chainHead = new StoredBlock(registerHeader, new BigInteger("0"), 132); when(btcBlockStore.getChainHead()).thenReturn(chainHead); when(btcBlockStore.getStoredBlockAtMainChainHeight(block.getHeight())).thenReturn(block); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(any())).thenReturn(btcBlockStore); BridgeStorageProvider provider = spy(new BridgeStorageProvider(repository, PrecompiledContracts.BRIDGE_ADDR, bridgeConstants, activations)); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, mock(BtcLockSenderProvider.class), mock(Block.class), mockFactory, activations ); MerkleBranch merkleBranch = mock(MerkleBranch.class); when(merkleBranch.reduceFrom(tx1.getHash(true))).thenReturn(witnessMerkleRoot); CoinbaseInformation coinbaseInformation = new CoinbaseInformation(Sha256Hash.ZERO_HASH); provider.setCoinbaseInformation(registerHeader.getHash(), coinbaseInformation); int confirmations = bridgeSupport.getBtcTransactionConfirmations(tx1.getHash(true), registerHeader.getHash(), merkleBranch); Assert.assertEquals(-5, confirmations); }
@Test public void getBtcTransactionConfirmations_tx_without_witness_unequal_roots_after_rskip_143() throws Exception { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); Repository repository = createRepository(); BtcTransaction tx1 = new BtcTransaction(btcParams); co.rsk.bitcoinj.core.BtcBlock registerHeader = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(1), Sha256Hash.ZERO_HASH, 1, 1, 1, new ArrayList<>() ); int height = 50; StoredBlock block = new StoredBlock(registerHeader, new BigInteger("0"), height); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); when(btcBlockStore.getFromCache(registerHeader.getHash())).thenReturn(block); StoredBlock chainHead = new StoredBlock(registerHeader, new BigInteger("0"), 132); when(btcBlockStore.getChainHead()).thenReturn(chainHead); when(btcBlockStore.getStoredBlockAtMainChainHeight(block.getHeight())).thenReturn(block); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(any())).thenReturn(btcBlockStore); BridgeStorageProvider provider = spy(new BridgeStorageProvider(repository, PrecompiledContracts.BRIDGE_ADDR, bridgeConstants, activations)); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, mock(BtcLockSenderProvider.class), mock(Block.class), mockFactory, activations ); MerkleBranch merkleBranch = mock(MerkleBranch.class); when(merkleBranch.reduceFrom(tx1.getHash())).thenReturn(PegTestUtils.createHash(5)); CoinbaseInformation coinbaseInformation = new CoinbaseInformation(Sha256Hash.ZERO_HASH); doReturn(coinbaseInformation).when(provider).getCoinbaseInformation(registerHeader.getHash()); int confirmations = bridgeSupport.getBtcTransactionConfirmations(tx1.getHash(), registerHeader.getHash(), merkleBranch); Assert.assertEquals(-5, confirmations); }
@Test public void getBtcTransactionConfirmations_accepts_tx_without_witness_after_rskip_143() throws Exception { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); Repository repository = createRepository(); BtcTransaction tx1 = new BtcTransaction(btcParams); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(tx1.getHash()); PartialMerkleTree pmt = new PartialMerkleTree(btcParams, bits, hashes, 1); List<Sha256Hash> hashlist = new ArrayList<>(); Sha256Hash blockMerkleRoot = pmt.getTxnHashAndMerkleRoot(hashlist); co.rsk.bitcoinj.core.BtcBlock registerHeader = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(1), blockMerkleRoot, 1, 1, 1, new ArrayList<>() ); int height = 50; StoredBlock block = new StoredBlock(registerHeader, new BigInteger("0"), height); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); when(btcBlockStore.getFromCache(registerHeader.getHash())).thenReturn(block); StoredBlock chainHead = new StoredBlock(registerHeader, new BigInteger("0"), 132); when(btcBlockStore.getChainHead()).thenReturn(chainHead); when(btcBlockStore.getStoredBlockAtMainChainHeight(block.getHeight())).thenReturn(block); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(any())).thenReturn(btcBlockStore); BridgeStorageProvider provider = spy(new BridgeStorageProvider(repository, PrecompiledContracts.BRIDGE_ADDR, bridgeConstants, activations)); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, mock(BtcLockSenderProvider.class), mock(Block.class), mockFactory, activations ); MerkleBranch merkleBranch = mock(MerkleBranch.class); when(merkleBranch.reduceFrom(tx1.getHash())).thenReturn(blockMerkleRoot); BtcBlock btcBlock = mock(BtcBlock.class); when(btcBlock.getMerkleRoot()).thenReturn(blockMerkleRoot); int confirmations = bridgeSupport.getBtcTransactionConfirmations(tx1.getHash(), registerHeader.getHash(), merkleBranch); Assert.assertEquals(chainHead.getHeight() - block.getHeight() + 1, confirmations); } |
BridgeSupport { public void registerBtcCoinbaseTransaction(byte[] btcTxSerialized, Sha256Hash blockHash, byte[] pmtSerialized, Sha256Hash witnessMerkleRoot, byte[] witnessReservedValue) throws IOException, BlockStoreException { Context.propagate(btcContext); this.ensureBtcBlockStore(); Sha256Hash btcTxHash = BtcTransactionFormatUtils.calculateBtcTxHash(btcTxSerialized); if (witnessReservedValue.length != 32) { logger.warn("[btcTx:{}] WitnessResevedValue length can't be different than 32 bytes", btcTxHash); throw new BridgeIllegalArgumentException("WitnessResevedValue length can't be different than 32 bytes"); } if (!PartialMerkleTreeFormatUtils.hasExpectedSize(pmtSerialized)) { logger.warn("[btcTx:{}] PartialMerkleTree doesn't have expected size", btcTxHash); throw new BridgeIllegalArgumentException("PartialMerkleTree doesn't have expected size"); } Sha256Hash merkleRoot; try { PartialMerkleTree pmt = new PartialMerkleTree(bridgeConstants.getBtcParams(), pmtSerialized, 0); List<Sha256Hash> hashesInPmt = new ArrayList<>(); merkleRoot = pmt.getTxnHashAndMerkleRoot(hashesInPmt); if (!hashesInPmt.contains(btcTxHash)) { logger.warn("Supplied Btc Tx {} is not in the supplied partial merkle tree", btcTxHash); return; } } catch (VerificationException e) { logger.warn("[btcTx:{}] PartialMerkleTree could not be parsed", btcTxHash); throw new BridgeIllegalArgumentException(String.format("PartialMerkleTree could not be parsed %s", ByteUtil.toHexString(pmtSerialized)), e); } StoredBlock storedBlock = btcBlockStore.getFromCache(blockHash); if (storedBlock == null) { logger.warn("[btcTx:{}] Block not registered", btcTxHash); throw new BridgeIllegalArgumentException(String.format("Block not registered %s", blockHash.toString())); } BtcBlock blockHeader = storedBlock.getHeader(); if (!blockHeader.getMerkleRoot().equals(merkleRoot)) { String panicMessage = String.format( "Btc Tx %s Supplied merkle root %s does not match block's merkle root %s", btcTxHash.toString(), merkleRoot, blockHeader.getMerkleRoot() ); logger.warn(panicMessage); panicProcessor.panic("btclock", panicMessage); return; } BtcTransaction btcTx = new BtcTransaction(bridgeConstants.getBtcParams(), btcTxSerialized); btcTx.verify(); Sha256Hash witnessCommitment = Sha256Hash.twiceOf(witnessMerkleRoot.getReversedBytes(), witnessReservedValue); if(!witnessCommitment.equals(btcTx.findWitnessCommitment())){ logger.warn("[btcTx:{}] WitnessCommitment does not match", btcTxHash); throw new BridgeIllegalArgumentException("WitnessCommitment does not match"); } CoinbaseInformation coinbaseInformation = new CoinbaseInformation(witnessMerkleRoot); provider.setCoinbaseInformation(blockHeader.getHash(), coinbaseInformation); logger.warn("[btcTx:{}] Registered coinbase information", btcTxHash); } BridgeSupport(
BridgeConstants bridgeConstants,
BridgeStorageProvider provider,
BridgeEventLogger eventLogger,
BtcLockSenderProvider btcLockSenderProvider,
Repository repository,
Block executionBlock,
Context btcContext,
FederationSupport federationSupport,
BtcBlockStoreWithCache.Factory btcBlockStoreFactory,
ActivationConfig.ForBlock activations); List<ProgramSubtrace> getSubtraces(); void save(); void receiveHeaders(BtcBlock[] headers); Wallet getActiveFederationWallet(); Wallet getRetiringFederationWallet(); Wallet getUTXOBasedWalletForLiveFederations(List<UTXO> utxos); Wallet getNoSpendWalletForLiveFederations(); void registerBtcTransaction(Transaction rskTx, byte[] btcTxSerialized, int height, byte[] pmtSerialized); void releaseBtc(Transaction rskTx); Coin getFeePerKb(); void updateCollections(Transaction rskTx); void addSignature(BtcECKey federatorPublicKey, List<byte[]> signatures, byte[] rskTxHash); byte[] getStateForBtcReleaseClient(); byte[] getStateForDebugging(); int getBtcBlockchainBestChainHeight(); int getBtcBlockchainInitialBlockHeight(); @Deprecated List<Sha256Hash> getBtcBlockchainBlockLocator(); Sha256Hash getBtcBlockchainBlockHashAtDepth(int depth); Long getBtcTransactionConfirmationsGetCost(Object[] args); Integer getBtcTransactionConfirmations(Sha256Hash btcTxHash, Sha256Hash btcBlockHash, MerkleBranch merkleBranch); Boolean isBtcTxHashAlreadyProcessed(Sha256Hash btcTxHash); Long getBtcTxHashProcessedHeight(Sha256Hash btcTxHash); boolean isAlreadyBtcTxHashProcessed(Sha256Hash btcTxHash); Federation getActiveFederation(); @Nullable Federation getRetiringFederation(); Address getFederationAddress(); Integer getFederationSize(); Integer getFederationThreshold(); byte[] getFederatorPublicKey(int index); byte[] getFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getFederationCreationTime(); long getFederationCreationBlockNumber(); Address getRetiringFederationAddress(); Integer getRetiringFederationSize(); Integer getRetiringFederationThreshold(); byte[] getRetiringFederatorPublicKey(int index); byte[] getRetiringFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getRetiringFederationCreationTime(); long getRetiringFederationCreationBlockNumber(); Integer voteFederationChange(Transaction tx, ABICallSpec callSpec); byte[] getPendingFederationHash(); Integer getPendingFederationSize(); byte[] getPendingFederatorPublicKey(int index); byte[] getPendingFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Integer getLockWhitelistSize(); LockWhitelistEntry getLockWhitelistEntryByIndex(int index); LockWhitelistEntry getLockWhitelistEntryByAddress(String addressBase58); Integer addOneOffLockWhitelistAddress(Transaction tx, String addressBase58, BigInteger maxTransferValue); Integer addUnlimitedLockWhitelistAddress(Transaction tx, String addressBase58); Integer removeLockWhitelistAddress(Transaction tx, String addressBase58); Coin getMinimumLockTxValue(); Integer voteFeePerKbChange(Transaction tx, Coin feePerKb); Integer setLockWhitelistDisableBlockDelay(Transaction tx, BigInteger disableBlockDelayBI); Coin getLockingCap(); boolean increaseLockingCap(Transaction tx, Coin newCap); void registerBtcCoinbaseTransaction(byte[] btcTxSerialized, Sha256Hash blockHash, byte[] pmtSerialized, Sha256Hash witnessMerkleRoot, byte[] witnessReservedValue); boolean hasBtcBlockCoinbaseTransactionInformation(Sha256Hash blockHash); static final RskAddress BURN_ADDRESS; static final int MAX_RELEASE_ITERATIONS; static final Integer FEDERATION_CHANGE_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_INVALID_ADDRESS_FORMAT_ERROR_CODE; static final Integer LOCK_WHITELIST_ALREADY_EXISTS_ERROR_CODE; static final Integer LOCK_WHITELIST_UNKNOWN_ERROR_CODE; static final Integer LOCK_WHITELIST_SUCCESS_CODE; static final Integer FEE_PER_KB_GENERIC_ERROR_CODE; static final Integer NEGATIVE_FEE_PER_KB_ERROR_CODE; static final Integer EXCESSIVE_FEE_PER_KB_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INEXISTENT_BLOCK_HASH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_NOT_IN_BEST_CHAIN_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INCONSISTENT_BLOCK_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_TOO_OLD_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INVALID_MERKLE_BRANCH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_MAX_DEPTH; } | @Test(expected = BridgeIllegalArgumentException.class) public void when_RegisterBtcCoinbaseTransaction_wrong_witnessReservedValue_noSent() throws BlockStoreException, AddressFormatException, IOException { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); Repository repository = createRepository(); byte[] rawTx = Hex.decode("020000000001010000000000000000000000000000000000000000000000000000000000000000fff" + "fffff0502cc000101ffffffff029c070395000000002321036d6b5bc8c0e902f296b5bdf3dfd4b6f095d8d0987818a557e1766e" + "a25c664524ac0000000000000000266a24aa21a9edfeb3b9170ae765cc6586edd67229eaa8bc19f9674d64cb10ee8a205f4ccf0" + "bc60120000000000000000000000000000000000000000000000000000000000000000000000000"); BtcTransaction txWithoutWitness = new BtcTransaction(btcParams, rawTx); byte[] witnessReservedValue = new byte[10]; BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(repository)).thenReturn(btcBlockStore); BridgeStorageProvider provider = mock(BridgeStorageProvider.class); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, mock(BtcLockSenderProvider.class), mock(Block.class), mockFactory, activations ); byte[] bits = new byte[1]; bits[0] = 0x01; List<Sha256Hash> hashes = new ArrayList<>(); PartialMerkleTree pmt = new PartialMerkleTree(btcParams, bits, hashes, 1); int height = 5; mockChainOfStoredBlocks(btcBlockStore, mock(BtcBlock.class), 5, height); when(btcBlockStore.getFromCache(mock(Sha256Hash.class))).thenReturn(new StoredBlock(mock(BtcBlock.class), BigInteger.ZERO, 0)); bridgeSupport.registerBtcCoinbaseTransaction(txWithoutWitness.bitcoinSerialize(), mock(Sha256Hash.class), pmt.bitcoinSerialize(), mock(Sha256Hash.class), witnessReservedValue); verify(mock(BridgeStorageProvider.class), never()).setCoinbaseInformation(any(Sha256Hash.class), any(CoinbaseInformation.class)); }
@Test(expected = BridgeIllegalArgumentException.class) public void when_RegisterBtcCoinbaseTransaction_MerkleTreeWrongFormat_noSent() throws BlockStoreException, AddressFormatException, IOException { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); Repository repository = createRepository(); byte[] rawTx = Hex.decode("020000000001010000000000000000000000000000000000000000000000000000000000000000fff" + "fffff0502cc000101ffffffff029c070395000000002321036d6b5bc8c0e902f296b5bdf3dfd4b6f095d8d0987818a557e1766e" + "a25c664524ac0000000000000000266a24aa21a9edfeb3b9170ae765cc6586edd67229eaa8bc19f9674d64cb10ee8a205f4ccf0" + "bc60120000000000000000000000000000000000000000000000000000000000000000000000000"); BtcTransaction tx1 = new BtcTransaction(btcParams, rawTx); BtcTransaction txWithoutWitness = new BtcTransaction(btcParams, rawTx); byte[] witnessReservedValue = tx1.getWitness(0).getPush(0); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(repository)).thenReturn(btcBlockStore); BridgeStorageProvider provider = mock(BridgeStorageProvider.class); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, mock(BtcLockSenderProvider.class), mock(Block.class), mockFactory, activations ); int height = 5; mockChainOfStoredBlocks(btcBlockStore, mock(BtcBlock.class), 5, height); when(btcBlockStore.getFromCache(mock(Sha256Hash.class))).thenReturn(new StoredBlock(mock(BtcBlock.class), BigInteger.ZERO, 0)); bridgeSupport.registerBtcCoinbaseTransaction(txWithoutWitness.bitcoinSerialize(), mock(Sha256Hash.class), new byte[]{6,6,6}, mock(Sha256Hash.class), witnessReservedValue); verify(mock(BridgeStorageProvider.class), never()).setCoinbaseInformation(any(Sha256Hash.class), any(CoinbaseInformation.class)); }
@Test public void when_RegisterBtcCoinbaseTransaction_HashNotInPmt_noSent() throws BlockStoreException, AddressFormatException, IOException { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); Repository repository = createRepository(); byte[] rawTx = Hex.decode("020000000001010000000000000000000000000000000000000000000000000000000000000000fff" + "fffff0502cc000101ffffffff029c070395000000002321036d6b5bc8c0e902f296b5bdf3dfd4b6f095d8d0987818a557e1766e" + "a25c664524ac0000000000000000266a24aa21a9edfeb3b9170ae765cc6586edd67229eaa8bc19f9674d64cb10ee8a205f4ccf0" + "bc60120000000000000000000000000000000000000000000000000000000000000000000000000"); BtcTransaction tx1 = new BtcTransaction(btcParams, rawTx); BtcTransaction txWithoutWitness = new BtcTransaction(btcParams, rawTx); Sha256Hash secondHashTx = Sha256Hash.wrap(Hex.decode("e3d0840a0825fb7d880e5cb8306745352920a8c7e8a30fac882b275e26c6bb65")); byte[] witnessReservedValue = tx1.getWitness(0).getPush(0); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(repository)).thenReturn(btcBlockStore); BridgeStorageProvider provider = mock(BridgeStorageProvider.class); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, mock(BtcLockSenderProvider.class), mock(Block.class), mockFactory, activations ); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(secondHashTx); PartialMerkleTree pmt = new PartialMerkleTree(btcParams, bits, hashes, 1); List<Sha256Hash> hashlist = new ArrayList<>(); Sha256Hash merkleRoot = pmt.getTxnHashAndMerkleRoot(hashlist); co.rsk.bitcoinj.core.BtcBlock registerHeader = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(1), merkleRoot, 1, 1, 1, new ArrayList<>() ); int height = 5; mockChainOfStoredBlocks(btcBlockStore, registerHeader, 5, height); when(btcBlockStore.getFromCache(registerHeader.getHash())).thenReturn(new StoredBlock(registerHeader, BigInteger.ZERO, 0)); bridgeSupport.registerBtcCoinbaseTransaction(txWithoutWitness.bitcoinSerialize(), mock(Sha256Hash.class), pmt.bitcoinSerialize(), mock(Sha256Hash.class), witnessReservedValue); verify(mock(BridgeStorageProvider.class), never()).setCoinbaseInformation(any(Sha256Hash.class), any(CoinbaseInformation.class)); }
@Test(expected = VerificationException.class) public void when_RegisterBtcCoinbaseTransaction_notVerify_noSent() throws BlockStoreException, AddressFormatException, IOException { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); Repository repository = createRepository(); BtcTransaction tx = new BtcTransaction(btcParams); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(repository)).thenReturn(btcBlockStore); BridgeStorageProvider provider = mock(BridgeStorageProvider.class); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, mock(BtcLockSenderProvider.class), mock(Block.class), mockFactory, activations ); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(tx.getHash()); PartialMerkleTree pmt = new PartialMerkleTree(btcParams, bits, hashes, 1); List<Sha256Hash> hashlist = new ArrayList<>(); Sha256Hash merkleRoot = pmt.getTxnHashAndMerkleRoot(hashlist); co.rsk.bitcoinj.core.BtcBlock registerHeader = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(1), merkleRoot, 1, 1, 1, new ArrayList<>() ); int height = 5; mockChainOfStoredBlocks(btcBlockStore, registerHeader, 5, height); when(btcBlockStore.getFromCache(registerHeader.getHash())).thenReturn(new StoredBlock(registerHeader, BigInteger.ZERO, 0)); bridgeSupport.registerBtcCoinbaseTransaction(tx.bitcoinSerialize(), registerHeader.getHash(), pmt.bitcoinSerialize(), mock(Sha256Hash.class), Sha256Hash.ZERO_HASH.getBytes()); verify(mock(BridgeStorageProvider.class), never()).setCoinbaseInformation(any(Sha256Hash.class), any(CoinbaseInformation.class)); }
@Test public void when_RegisterBtcCoinbaseTransaction_not_equal_merkle_root_noSent() throws BlockStoreException, AddressFormatException, IOException { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); Repository repository = createRepository(); byte[] rawTx = Hex.decode("020000000001010000000000000000000000000000000000000000000000000000000000000000fff" + "fffff0502cc000101ffffffff029c070395000000002321036d6b5bc8c0e902f296b5bdf3dfd4b6f095d8d0987818a557e1766e" + "a25c664524ac0000000000000000266a24aa21a9edfeb3b9170ae765cc6586edd67229eaa8bc19f9674d64cb10ee8a205f4ccf0" + "bc60120000000000000000000000000000000000000000000000000000000000000000000000000"); BtcTransaction tx1 = new BtcTransaction(btcParams, rawTx); BtcTransaction txWithoutWitness = new BtcTransaction(btcParams, rawTx); txWithoutWitness.setWitness(0, null); byte[] witnessReservedValue = tx1.getWitness(0).getPush(0); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(repository)).thenReturn(btcBlockStore); BridgeStorageProvider provider = mock(BridgeStorageProvider.class); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, mock(BtcLockSenderProvider.class), mock(Block.class), mockFactory, activations ); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(txWithoutWitness.getHash()); PartialMerkleTree pmt = new PartialMerkleTree(btcParams, bits, hashes, 1); co.rsk.bitcoinj.core.BtcBlock registerHeader = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(1), Sha256Hash.ZERO_HASH, 1, 1, 1, new ArrayList<>() ); int height = 5; mockChainOfStoredBlocks(btcBlockStore, registerHeader, 5, height); BtcBlock btcBlock = mock(BtcBlock.class); StoredBlock storedBlock = mock(StoredBlock.class); when(btcBlock.getMerkleRoot()).thenReturn(Sha256Hash.ZERO_HASH); when(storedBlock.getHeader()).thenReturn(btcBlock); when(btcBlockStore.getFromCache(registerHeader.getHash())).thenReturn(storedBlock); bridgeSupport.registerBtcCoinbaseTransaction(txWithoutWitness.bitcoinSerialize(), registerHeader.getHash(), pmt.bitcoinSerialize(), mock(Sha256Hash.class), witnessReservedValue); verify(mock(BridgeStorageProvider.class), never()).setCoinbaseInformation(any(Sha256Hash.class), any(CoinbaseInformation.class)); }
@Test(expected = BridgeIllegalArgumentException.class) public void when_RegisterBtcCoinbaseTransaction_null_stored_block_noSent() throws BlockStoreException, AddressFormatException, IOException { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); Repository repository = createRepository(); byte[] rawTx = Hex.decode("020000000001010000000000000000000000000000000000000000000000000000000000000000fff" + "fffff0502cc000101ffffffff029c070395000000002321036d6b5bc8c0e902f296b5bdf3dfd4b6f095d8d0987818a557e1766e" + "a25c664524ac0000000000000000266a24aa21a9edfeb3b9170ae765cc6586edd67229eaa8bc19f9674d64cb10ee8a205f4ccf0" + "bc60120000000000000000000000000000000000000000000000000000000000000000000000000"); BtcTransaction tx1 = new BtcTransaction(btcParams, rawTx); BtcTransaction txWithoutWitness = new BtcTransaction(btcParams, rawTx); Sha256Hash secondHashTx = Sha256Hash.wrap(Hex.decode("e3d0840a0825fb7d880e5cb8306745352920a8c7e8a30fac882b275e26c6bb65")); txWithoutWitness.setWitness(0, null); byte[] witnessReservedValue = tx1.getWitness(0).getPush(0); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(repository)).thenReturn(btcBlockStore); BridgeStorageProvider provider = mock(BridgeStorageProvider.class); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, mock(BtcLockSenderProvider.class), mock(Block.class), mockFactory, activations ); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(tx1.getHash()); hashes.add(secondHashTx); PartialMerkleTree pmt = new PartialMerkleTree(btcParams, bits, hashes, 2); List<Sha256Hash> hashlist = new ArrayList<>(); Sha256Hash merkleRoot = pmt.getTxnHashAndMerkleRoot(hashlist); co.rsk.bitcoinj.core.BtcBlock registerHeader = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(1), merkleRoot, 1, 1, 1, new ArrayList<>() ); int height = 5; mockChainOfStoredBlocks(btcBlockStore, registerHeader, 5, height); when(btcBlockStore.getFromCache(registerHeader.getHash())).thenReturn(null); bridgeSupport.registerBtcCoinbaseTransaction(txWithoutWitness.bitcoinSerialize(), mock(Sha256Hash.class), pmt.bitcoinSerialize(), mock(Sha256Hash.class), witnessReservedValue); verify(mock(BridgeStorageProvider.class), never()).setCoinbaseInformation(any(Sha256Hash.class), any(CoinbaseInformation.class)); }
@Test public void registerBtcCoinbaseTransaction() throws BlockStoreException, AddressFormatException, IOException { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); Repository repository = createRepository(); byte[] rawTx = Hex.decode("020000000001010000000000000000000000000000000000000000000000000000000000000000fff" + "fffff0502cc000101ffffffff029c070395000000002321036d6b5bc8c0e902f296b5bdf3dfd4b6f095d8d0987818a557e1766e" + "a25c664524ac0000000000000000266a24aa21a9edfeb3b9170ae765cc6586edd67229eaa8bc19f9674d64cb10ee8a205f4ccf0" + "bc60120000000000000000000000000000000000000000000000000000000000000000000000000"); BtcTransaction tx1 = new BtcTransaction(btcParams, rawTx); BtcTransaction txWithoutWitness = new BtcTransaction(btcParams, rawTx); Sha256Hash secondHashTx = Sha256Hash.wrap(Hex.decode("e3d0840a0825fb7d880e5cb8306745352920a8c7e8a30fac882b275e26c6bb65")); Sha256Hash mRoot = MerkleTreeUtils.combineLeftRight(tx1.getHash(), secondHashTx); txWithoutWitness.setWitness(0, null); byte[] witnessReservedValue = tx1.getWitness(0).getPush(0); Sha256Hash witnessRoot = MerkleTreeUtils.combineLeftRight(Sha256Hash.ZERO_HASH, secondHashTx); byte[] witnessRootBytes = witnessRoot.getReversedBytes(); byte[] wc = tx1.getOutputs().stream().filter(t -> t.getValue().getValue() == 0).collect(Collectors.toList()).get(0).getScriptPubKey().getChunks().get(1).data; wc = Arrays.copyOfRange(wc,4, 36); Sha256Hash witCom = Sha256Hash.wrap(wc); Assert.assertEquals(Sha256Hash.twiceOf(witnessRootBytes, witnessReservedValue), witCom); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(repository)).thenReturn(btcBlockStore); BridgeStorageProvider provider = mock(BridgeStorageProvider.class); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, mock(BtcLockSenderProvider.class), mock(Block.class), mockFactory, activations ); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(tx1.getHash()); hashes.add(secondHashTx); PartialMerkleTree pmt = new PartialMerkleTree(btcParams, bits, hashes, 2); List<Sha256Hash> hashlist = new ArrayList<>(); Sha256Hash merkleRoot = pmt.getTxnHashAndMerkleRoot(hashlist); Assert.assertEquals(merkleRoot, mRoot); co.rsk.bitcoinj.core.BtcBlock registerHeader = new co.rsk.bitcoinj.core.BtcBlock( btcParams, 1, PegTestUtils.createHash(1), merkleRoot, 1, 1, 1, new ArrayList<>() ); int height = 5; mockChainOfStoredBlocks(btcBlockStore, registerHeader, 5, height); when(btcBlockStore.getFromCache(registerHeader.getHash())).thenReturn(new StoredBlock(registerHeader, BigInteger.ZERO, 0)); bridgeSupport.registerBtcCoinbaseTransaction(txWithoutWitness.bitcoinSerialize(), registerHeader.getHash(), pmt.bitcoinSerialize(), witnessRoot, witnessReservedValue); ArgumentCaptor<CoinbaseInformation> argumentCaptor = ArgumentCaptor.forClass(CoinbaseInformation.class); verify(provider).setCoinbaseInformation(eq(registerHeader.getHash()), argumentCaptor.capture()); assertEquals(witnessRoot, argumentCaptor.getValue().getWitnessMerkleRoot()); } |
BridgeSupport { public boolean hasBtcBlockCoinbaseTransactionInformation(Sha256Hash blockHash) { CoinbaseInformation coinbaseInformation = provider.getCoinbaseInformation(blockHash); return coinbaseInformation != null; } BridgeSupport(
BridgeConstants bridgeConstants,
BridgeStorageProvider provider,
BridgeEventLogger eventLogger,
BtcLockSenderProvider btcLockSenderProvider,
Repository repository,
Block executionBlock,
Context btcContext,
FederationSupport federationSupport,
BtcBlockStoreWithCache.Factory btcBlockStoreFactory,
ActivationConfig.ForBlock activations); List<ProgramSubtrace> getSubtraces(); void save(); void receiveHeaders(BtcBlock[] headers); Wallet getActiveFederationWallet(); Wallet getRetiringFederationWallet(); Wallet getUTXOBasedWalletForLiveFederations(List<UTXO> utxos); Wallet getNoSpendWalletForLiveFederations(); void registerBtcTransaction(Transaction rskTx, byte[] btcTxSerialized, int height, byte[] pmtSerialized); void releaseBtc(Transaction rskTx); Coin getFeePerKb(); void updateCollections(Transaction rskTx); void addSignature(BtcECKey federatorPublicKey, List<byte[]> signatures, byte[] rskTxHash); byte[] getStateForBtcReleaseClient(); byte[] getStateForDebugging(); int getBtcBlockchainBestChainHeight(); int getBtcBlockchainInitialBlockHeight(); @Deprecated List<Sha256Hash> getBtcBlockchainBlockLocator(); Sha256Hash getBtcBlockchainBlockHashAtDepth(int depth); Long getBtcTransactionConfirmationsGetCost(Object[] args); Integer getBtcTransactionConfirmations(Sha256Hash btcTxHash, Sha256Hash btcBlockHash, MerkleBranch merkleBranch); Boolean isBtcTxHashAlreadyProcessed(Sha256Hash btcTxHash); Long getBtcTxHashProcessedHeight(Sha256Hash btcTxHash); boolean isAlreadyBtcTxHashProcessed(Sha256Hash btcTxHash); Federation getActiveFederation(); @Nullable Federation getRetiringFederation(); Address getFederationAddress(); Integer getFederationSize(); Integer getFederationThreshold(); byte[] getFederatorPublicKey(int index); byte[] getFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getFederationCreationTime(); long getFederationCreationBlockNumber(); Address getRetiringFederationAddress(); Integer getRetiringFederationSize(); Integer getRetiringFederationThreshold(); byte[] getRetiringFederatorPublicKey(int index); byte[] getRetiringFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getRetiringFederationCreationTime(); long getRetiringFederationCreationBlockNumber(); Integer voteFederationChange(Transaction tx, ABICallSpec callSpec); byte[] getPendingFederationHash(); Integer getPendingFederationSize(); byte[] getPendingFederatorPublicKey(int index); byte[] getPendingFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Integer getLockWhitelistSize(); LockWhitelistEntry getLockWhitelistEntryByIndex(int index); LockWhitelistEntry getLockWhitelistEntryByAddress(String addressBase58); Integer addOneOffLockWhitelistAddress(Transaction tx, String addressBase58, BigInteger maxTransferValue); Integer addUnlimitedLockWhitelistAddress(Transaction tx, String addressBase58); Integer removeLockWhitelistAddress(Transaction tx, String addressBase58); Coin getMinimumLockTxValue(); Integer voteFeePerKbChange(Transaction tx, Coin feePerKb); Integer setLockWhitelistDisableBlockDelay(Transaction tx, BigInteger disableBlockDelayBI); Coin getLockingCap(); boolean increaseLockingCap(Transaction tx, Coin newCap); void registerBtcCoinbaseTransaction(byte[] btcTxSerialized, Sha256Hash blockHash, byte[] pmtSerialized, Sha256Hash witnessMerkleRoot, byte[] witnessReservedValue); boolean hasBtcBlockCoinbaseTransactionInformation(Sha256Hash blockHash); static final RskAddress BURN_ADDRESS; static final int MAX_RELEASE_ITERATIONS; static final Integer FEDERATION_CHANGE_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_INVALID_ADDRESS_FORMAT_ERROR_CODE; static final Integer LOCK_WHITELIST_ALREADY_EXISTS_ERROR_CODE; static final Integer LOCK_WHITELIST_UNKNOWN_ERROR_CODE; static final Integer LOCK_WHITELIST_SUCCESS_CODE; static final Integer FEE_PER_KB_GENERIC_ERROR_CODE; static final Integer NEGATIVE_FEE_PER_KB_ERROR_CODE; static final Integer EXCESSIVE_FEE_PER_KB_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INEXISTENT_BLOCK_HASH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_NOT_IN_BEST_CHAIN_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INCONSISTENT_BLOCK_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_TOO_OLD_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INVALID_MERKLE_BRANCH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_MAX_DEPTH; } | @Test public void hasBtcCoinbaseTransaction_before_rskip_143_activation() throws AddressFormatException { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(false); Repository repository = createRepository(); BridgeStorageProvider provider = new BridgeStorageProvider(repository, PrecompiledContracts.BRIDGE_ADDR, bridgeConstants, activations); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, mock(BtcLockSenderProvider.class), mock(Block.class), mock(BtcBlockStoreWithCache.Factory.class), activations ); CoinbaseInformation coinbaseInformation = new CoinbaseInformation(Sha256Hash.ZERO_HASH); provider.setCoinbaseInformation(Sha256Hash.ZERO_HASH, coinbaseInformation); Assert.assertFalse(bridgeSupport.hasBtcBlockCoinbaseTransactionInformation(Sha256Hash.ZERO_HASH)); }
@Test public void hasBtcCoinbaseTransaction_after_rskip_143_activation() throws AddressFormatException { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); Repository repository = createRepository(); BridgeStorageProvider provider = new BridgeStorageProvider(repository, PrecompiledContracts.BRIDGE_ADDR, bridgeConstants, activations); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, mock(BtcLockSenderProvider.class), mock(Block.class), mock(BtcBlockStoreWithCache.Factory.class), activations ); CoinbaseInformation coinbaseInformation = new CoinbaseInformation(Sha256Hash.ZERO_HASH); provider.setCoinbaseInformation(Sha256Hash.ZERO_HASH, coinbaseInformation); Assert.assertTrue(bridgeSupport.hasBtcBlockCoinbaseTransactionInformation(Sha256Hash.ZERO_HASH)); }
@Test public void hasBtcCoinbaseTransaction_fails_with_null_coinbase_information_after_rskip_143_activation() throws AddressFormatException { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); Repository repository = createRepository(); BridgeStorageProvider provider = mock(BridgeStorageProvider.class); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, repository, mock(BtcLockSenderProvider.class), mock(Block.class), mock(BtcBlockStoreWithCache.Factory.class), activations ); Assert.assertFalse(bridgeSupport.hasBtcBlockCoinbaseTransactionInformation(Sha256Hash.ZERO_HASH)); } |
BridgeSupport { public boolean isAlreadyBtcTxHashProcessed(Sha256Hash btcTxHash) throws IOException { if (getBtcTxHashProcessedHeight(btcTxHash) > -1L) { logger.warn("Supplied Btc Tx {} was already processed", btcTxHash); return true; } return false; } BridgeSupport(
BridgeConstants bridgeConstants,
BridgeStorageProvider provider,
BridgeEventLogger eventLogger,
BtcLockSenderProvider btcLockSenderProvider,
Repository repository,
Block executionBlock,
Context btcContext,
FederationSupport federationSupport,
BtcBlockStoreWithCache.Factory btcBlockStoreFactory,
ActivationConfig.ForBlock activations); List<ProgramSubtrace> getSubtraces(); void save(); void receiveHeaders(BtcBlock[] headers); Wallet getActiveFederationWallet(); Wallet getRetiringFederationWallet(); Wallet getUTXOBasedWalletForLiveFederations(List<UTXO> utxos); Wallet getNoSpendWalletForLiveFederations(); void registerBtcTransaction(Transaction rskTx, byte[] btcTxSerialized, int height, byte[] pmtSerialized); void releaseBtc(Transaction rskTx); Coin getFeePerKb(); void updateCollections(Transaction rskTx); void addSignature(BtcECKey federatorPublicKey, List<byte[]> signatures, byte[] rskTxHash); byte[] getStateForBtcReleaseClient(); byte[] getStateForDebugging(); int getBtcBlockchainBestChainHeight(); int getBtcBlockchainInitialBlockHeight(); @Deprecated List<Sha256Hash> getBtcBlockchainBlockLocator(); Sha256Hash getBtcBlockchainBlockHashAtDepth(int depth); Long getBtcTransactionConfirmationsGetCost(Object[] args); Integer getBtcTransactionConfirmations(Sha256Hash btcTxHash, Sha256Hash btcBlockHash, MerkleBranch merkleBranch); Boolean isBtcTxHashAlreadyProcessed(Sha256Hash btcTxHash); Long getBtcTxHashProcessedHeight(Sha256Hash btcTxHash); boolean isAlreadyBtcTxHashProcessed(Sha256Hash btcTxHash); Federation getActiveFederation(); @Nullable Federation getRetiringFederation(); Address getFederationAddress(); Integer getFederationSize(); Integer getFederationThreshold(); byte[] getFederatorPublicKey(int index); byte[] getFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getFederationCreationTime(); long getFederationCreationBlockNumber(); Address getRetiringFederationAddress(); Integer getRetiringFederationSize(); Integer getRetiringFederationThreshold(); byte[] getRetiringFederatorPublicKey(int index); byte[] getRetiringFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getRetiringFederationCreationTime(); long getRetiringFederationCreationBlockNumber(); Integer voteFederationChange(Transaction tx, ABICallSpec callSpec); byte[] getPendingFederationHash(); Integer getPendingFederationSize(); byte[] getPendingFederatorPublicKey(int index); byte[] getPendingFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Integer getLockWhitelistSize(); LockWhitelistEntry getLockWhitelistEntryByIndex(int index); LockWhitelistEntry getLockWhitelistEntryByAddress(String addressBase58); Integer addOneOffLockWhitelistAddress(Transaction tx, String addressBase58, BigInteger maxTransferValue); Integer addUnlimitedLockWhitelistAddress(Transaction tx, String addressBase58); Integer removeLockWhitelistAddress(Transaction tx, String addressBase58); Coin getMinimumLockTxValue(); Integer voteFeePerKbChange(Transaction tx, Coin feePerKb); Integer setLockWhitelistDisableBlockDelay(Transaction tx, BigInteger disableBlockDelayBI); Coin getLockingCap(); boolean increaseLockingCap(Transaction tx, Coin newCap); void registerBtcCoinbaseTransaction(byte[] btcTxSerialized, Sha256Hash blockHash, byte[] pmtSerialized, Sha256Hash witnessMerkleRoot, byte[] witnessReservedValue); boolean hasBtcBlockCoinbaseTransactionInformation(Sha256Hash blockHash); static final RskAddress BURN_ADDRESS; static final int MAX_RELEASE_ITERATIONS; static final Integer FEDERATION_CHANGE_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_INVALID_ADDRESS_FORMAT_ERROR_CODE; static final Integer LOCK_WHITELIST_ALREADY_EXISTS_ERROR_CODE; static final Integer LOCK_WHITELIST_UNKNOWN_ERROR_CODE; static final Integer LOCK_WHITELIST_SUCCESS_CODE; static final Integer FEE_PER_KB_GENERIC_ERROR_CODE; static final Integer NEGATIVE_FEE_PER_KB_ERROR_CODE; static final Integer EXCESSIVE_FEE_PER_KB_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INEXISTENT_BLOCK_HASH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_NOT_IN_BEST_CHAIN_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INCONSISTENT_BLOCK_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_TOO_OLD_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INVALID_MERKLE_BRANCH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_MAX_DEPTH; } | @Test public void isAlreadyBtcTxHashProcessedHeight_true() throws IOException { Repository repository = createRepository(); BtcTransaction btcTransaction = new BtcTransaction(btcParams); BridgeStorageProvider provider = new BridgeStorageProvider(repository, PrecompiledContracts.BRIDGE_ADDR, bridgeConstants, activationsBeforeForks); provider.setHeightBtcTxhashAlreadyProcessed(btcTransaction.getHash(), 1L); BridgeSupport bridgeSupport = getBridgeSupport(bridgeConstants, provider); Assert.assertTrue(bridgeSupport.isAlreadyBtcTxHashProcessed(btcTransaction.getHash())); }
@Test public void isAlreadyBtcTxHashProcessedHeight_false() throws IOException { BtcTransaction btcTransaction = new BtcTransaction(btcParams); BridgeSupport bridgeSupport = getBridgeSupport(bridgeConstants, mock(BridgeStorageProvider.class)); Assert.assertFalse(bridgeSupport.isAlreadyBtcTxHashProcessed(btcTransaction.getHash())); } |
BridgeSupport { @VisibleForTesting protected boolean validationsForRegisterBtcTransaction(Sha256Hash btcTxHash, int height, byte[] pmtSerialized, byte[] btcTxSerialized) throws BlockStoreException, VerificationException.EmptyInputsOrOutputs, BridgeIllegalArgumentException { try { int acceptableConfirmationsAmount = bridgeConstants.getBtc2RskMinimumAcceptableConfirmations(); if (!BridgeUtils.validateHeightAndConfirmations(height, getBtcBlockchainBestChainHeight(), acceptableConfirmationsAmount, btcTxHash)) { return false; } } catch (Exception e) { String panicMessage = String.format("Btc Tx %s Supplied Height is %d but should be greater than 0", btcTxHash, height); logger.warn(panicMessage); panicProcessor.panic("btclock", panicMessage); return false; } if (!PartialMerkleTreeFormatUtils.hasExpectedSize(pmtSerialized)) { throw new BridgeIllegalArgumentException("PartialMerkleTree doesn't have expected size"); } Sha256Hash merkleRoot; try { NetworkParameters networkParameters = bridgeConstants.getBtcParams(); merkleRoot = BridgeUtils.calculateMerkleRoot(networkParameters, pmtSerialized, btcTxHash); if (merkleRoot == null) { return false; } } catch (VerificationException e) { throw new BridgeIllegalArgumentException(e.getMessage(), e); } logger.info("Going to validate inputs for btc tx {}", btcTxHash); BridgeUtils.validateInputsCount(btcTxSerialized, activations.isActive(ConsensusRule.RSKIP143)); BtcBlock blockHeader = btcBlockStore.getStoredBlockAtMainChainHeight(height).getHeader(); if (!isBlockMerkleRootValid(merkleRoot, blockHeader)){ String panicMessage = String.format( "Btc Tx %s Supplied merkle root %s does not match block's merkle root %s", btcTxHash.toString(), merkleRoot, blockHeader.getMerkleRoot() ); logger.warn(panicMessage); panicProcessor.panic("btclock", panicMessage); return false; } return true; } BridgeSupport(
BridgeConstants bridgeConstants,
BridgeStorageProvider provider,
BridgeEventLogger eventLogger,
BtcLockSenderProvider btcLockSenderProvider,
Repository repository,
Block executionBlock,
Context btcContext,
FederationSupport federationSupport,
BtcBlockStoreWithCache.Factory btcBlockStoreFactory,
ActivationConfig.ForBlock activations); List<ProgramSubtrace> getSubtraces(); void save(); void receiveHeaders(BtcBlock[] headers); Wallet getActiveFederationWallet(); Wallet getRetiringFederationWallet(); Wallet getUTXOBasedWalletForLiveFederations(List<UTXO> utxos); Wallet getNoSpendWalletForLiveFederations(); void registerBtcTransaction(Transaction rskTx, byte[] btcTxSerialized, int height, byte[] pmtSerialized); void releaseBtc(Transaction rskTx); Coin getFeePerKb(); void updateCollections(Transaction rskTx); void addSignature(BtcECKey federatorPublicKey, List<byte[]> signatures, byte[] rskTxHash); byte[] getStateForBtcReleaseClient(); byte[] getStateForDebugging(); int getBtcBlockchainBestChainHeight(); int getBtcBlockchainInitialBlockHeight(); @Deprecated List<Sha256Hash> getBtcBlockchainBlockLocator(); Sha256Hash getBtcBlockchainBlockHashAtDepth(int depth); Long getBtcTransactionConfirmationsGetCost(Object[] args); Integer getBtcTransactionConfirmations(Sha256Hash btcTxHash, Sha256Hash btcBlockHash, MerkleBranch merkleBranch); Boolean isBtcTxHashAlreadyProcessed(Sha256Hash btcTxHash); Long getBtcTxHashProcessedHeight(Sha256Hash btcTxHash); boolean isAlreadyBtcTxHashProcessed(Sha256Hash btcTxHash); Federation getActiveFederation(); @Nullable Federation getRetiringFederation(); Address getFederationAddress(); Integer getFederationSize(); Integer getFederationThreshold(); byte[] getFederatorPublicKey(int index); byte[] getFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getFederationCreationTime(); long getFederationCreationBlockNumber(); Address getRetiringFederationAddress(); Integer getRetiringFederationSize(); Integer getRetiringFederationThreshold(); byte[] getRetiringFederatorPublicKey(int index); byte[] getRetiringFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getRetiringFederationCreationTime(); long getRetiringFederationCreationBlockNumber(); Integer voteFederationChange(Transaction tx, ABICallSpec callSpec); byte[] getPendingFederationHash(); Integer getPendingFederationSize(); byte[] getPendingFederatorPublicKey(int index); byte[] getPendingFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Integer getLockWhitelistSize(); LockWhitelistEntry getLockWhitelistEntryByIndex(int index); LockWhitelistEntry getLockWhitelistEntryByAddress(String addressBase58); Integer addOneOffLockWhitelistAddress(Transaction tx, String addressBase58, BigInteger maxTransferValue); Integer addUnlimitedLockWhitelistAddress(Transaction tx, String addressBase58); Integer removeLockWhitelistAddress(Transaction tx, String addressBase58); Coin getMinimumLockTxValue(); Integer voteFeePerKbChange(Transaction tx, Coin feePerKb); Integer setLockWhitelistDisableBlockDelay(Transaction tx, BigInteger disableBlockDelayBI); Coin getLockingCap(); boolean increaseLockingCap(Transaction tx, Coin newCap); void registerBtcCoinbaseTransaction(byte[] btcTxSerialized, Sha256Hash blockHash, byte[] pmtSerialized, Sha256Hash witnessMerkleRoot, byte[] witnessReservedValue); boolean hasBtcBlockCoinbaseTransactionInformation(Sha256Hash blockHash); static final RskAddress BURN_ADDRESS; static final int MAX_RELEASE_ITERATIONS; static final Integer FEDERATION_CHANGE_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_INVALID_ADDRESS_FORMAT_ERROR_CODE; static final Integer LOCK_WHITELIST_ALREADY_EXISTS_ERROR_CODE; static final Integer LOCK_WHITELIST_UNKNOWN_ERROR_CODE; static final Integer LOCK_WHITELIST_SUCCESS_CODE; static final Integer FEE_PER_KB_GENERIC_ERROR_CODE; static final Integer NEGATIVE_FEE_PER_KB_ERROR_CODE; static final Integer EXCESSIVE_FEE_PER_KB_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INEXISTENT_BLOCK_HASH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_NOT_IN_BEST_CHAIN_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INCONSISTENT_BLOCK_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_TOO_OLD_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INVALID_MERKLE_BRANCH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_MAX_DEPTH; } | @Test public void validationsForRegisterBtcTransaction_negative_height() throws BlockStoreException { BtcTransaction tx = new BtcTransaction(btcParams); Repository repository = createRepository(); BridgeStorageProvider provider = new BridgeStorageProvider(repository, PrecompiledContracts.BRIDGE_ADDR, bridgeConstants, activationsBeforeForks); BridgeSupport bridgeSupport = getBridgeSupport(bridgeConstants, provider); byte[] data = Hex.decode("ab"); Assert.assertFalse(bridgeSupport.validationsForRegisterBtcTransaction(tx.getHash(), -1, data, data)); }
@Test public void validationsForRegisterBtcTransaction_insufficient_confirmations() throws IOException, BlockStoreException { BtcTransaction tx = new BtcTransaction(btcParams); BtcBlockStoreWithCache.Factory btcBlockStoreFactory = new RepositoryBtcBlockStoreWithCache.Factory(bridgeConstants.getBtcParams()); Repository repository = createRepository(); BridgeStorageProvider provider = new BridgeStorageProvider(repository, PrecompiledContracts.BRIDGE_ADDR, bridgeConstants, activationsBeforeForks); BridgeSupport bridgeSupport = getBridgeSupport(bridgeConstants, provider, repository, mock(BtcLockSenderProvider.class), mock(Block.class), btcBlockStoreFactory); byte[] data = Hex.decode("ab"); Assert.assertFalse(bridgeSupport.validationsForRegisterBtcTransaction(tx.getHash(), 100, data, data)); }
@Test(expected = BridgeIllegalArgumentException.class) public void validationsForRegisterBtcTransaction_invalid_pmt() throws IOException, BlockStoreException { BtcTransaction btcTx = new BtcTransaction(btcParams); BridgeConstants bridgeConstants = mock(BridgeConstants.class); String pmtSerializedEncoded = "030000000279e7c0da739df8a00f12c0bff55e5438f530aa5859ff9874258cd7bad3fe709746aff89" + "7e6a851faa80120d6ae99db30883699ac0428fc7192d6c3fec0ca64010d"; byte[] pmtSerialized = Hex.decode(pmtSerializedEncoded); int btcTxHeight = 2; doReturn(btcParams).when(bridgeConstants).getBtcParams(); doReturn(0).when(bridgeConstants).getBtc2RskMinimumAcceptableConfirmations(); StoredBlock storedBlock = mock(StoredBlock.class); doReturn(btcTxHeight - 1).when(storedBlock).getHeight(); BtcBlock btcBlock = mock(BtcBlock.class); doReturn(Sha256Hash.of(Hex.decode("aa"))).when(btcBlock).getHash(); doReturn(btcBlock).when(storedBlock).getHeader(); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); doReturn(storedBlock).when(btcBlockStore).getChainHead(); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(any())).thenReturn(btcBlockStore); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, mock(BridgeStorageProvider.class), mock(Repository.class), mock(BridgeEventLogger.class), null, mockFactory ); bridgeSupport.validationsForRegisterBtcTransaction(btcTx.getHash(), btcTxHeight, pmtSerialized, btcTx.bitcoinSerialize()); }
@Test public void validationsForRegisterBtcTransaction_hash_not_in_pmt() throws BlockStoreException, AddressFormatException, IOException { BtcTransaction btcTx = new BtcTransaction(btcParams); BridgeConstants bridgeConstants = mock(BridgeConstants.class); byte[] bits = new byte[1]; bits[0] = 0x01; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(PegTestUtils.createHash(0)); PartialMerkleTree pmt = new PartialMerkleTree(btcParams, bits, hashes, 1); int btcTxHeight = 2; doReturn(btcParams).when(bridgeConstants).getBtcParams(); doReturn(0).when(bridgeConstants).getBtc2RskMinimumAcceptableConfirmations(); StoredBlock storedBlock = mock(StoredBlock.class); doReturn(btcTxHeight - 1).when(storedBlock).getHeight(); BtcBlock btcBlock = mock(BtcBlock.class); doReturn(Sha256Hash.of(Hex.decode("aa"))).when(btcBlock).getHash(); doReturn(btcBlock).when(storedBlock).getHeader(); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); doReturn(storedBlock).when(btcBlockStore).getChainHead(); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(any())).thenReturn(btcBlockStore); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, mock(BridgeStorageProvider.class), mock(Repository.class), mock(BridgeEventLogger.class), null, mockFactory ); Assert.assertFalse(bridgeSupport.validationsForRegisterBtcTransaction(btcTx.getHash(), 0, pmt.bitcoinSerialize(), btcTx.bitcoinSerialize())); }
@Test(expected = VerificationException.class) public void validationsForRegisterBtcTransaction_tx_without_inputs_before_rskip_143() throws BlockStoreException { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(false); BtcTransaction btcTx = new BtcTransaction(btcParams); BridgeConstants bridgeConstants = mock(BridgeConstants.class); byte[] bits = new byte[1]; bits[0] = 0x01; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(btcTx.getHash()); PartialMerkleTree pmt = new PartialMerkleTree(btcParams, bits, hashes, 1); int btcTxHeight = 2; doReturn(btcParams).when(bridgeConstants).getBtcParams(); doReturn(0).when(bridgeConstants).getBtc2RskMinimumAcceptableConfirmations(); StoredBlock storedBlock = mock(StoredBlock.class); doReturn(btcTxHeight - 1).when(storedBlock).getHeight(); BtcBlock btcBlock = mock(BtcBlock.class); doReturn(Sha256Hash.of(Hex.decode("aa"))).when(btcBlock).getHash(); doReturn(btcBlock).when(storedBlock).getHeader(); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); doReturn(storedBlock).when(btcBlockStore).getChainHead(); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(any())).thenReturn(btcBlockStore); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, mock(BridgeStorageProvider.class), mock(Repository.class), mock(BridgeEventLogger.class), null, mockFactory, activations ); bridgeSupport.validationsForRegisterBtcTransaction(btcTx.getHash(), btcTxHeight, pmt.bitcoinSerialize(), btcTx.bitcoinSerialize()); }
@Test(expected = VerificationException.class) public void validationsForRegisterBtcTransaction_tx_without_inputs_after_rskip_143() throws BlockStoreException { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(true); BtcTransaction btcTx = new BtcTransaction(btcParams); BridgeConstants bridgeConstants = mock(BridgeConstants.class); byte[] bits = new byte[1]; bits[0] = 0x01; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(btcTx.getHash()); PartialMerkleTree pmt = new PartialMerkleTree(btcParams, bits, hashes, 1); int btcTxHeight = 2; doReturn(btcParams).when(bridgeConstants).getBtcParams(); doReturn(0).when(bridgeConstants).getBtc2RskMinimumAcceptableConfirmations(); StoredBlock storedBlock = mock(StoredBlock.class); doReturn(btcTxHeight - 1).when(storedBlock).getHeight(); BtcBlock btcBlock = mock(BtcBlock.class); doReturn(Sha256Hash.of(Hex.decode("aa"))).when(btcBlock).getHash(); doReturn(btcBlock).when(storedBlock).getHeader(); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); doReturn(storedBlock).when(btcBlockStore).getChainHead(); BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(any())).thenReturn(btcBlockStore); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, mock(BridgeStorageProvider.class), mock(Repository.class), mock(BridgeEventLogger.class), null, mockFactory, activations ); bridgeSupport.validationsForRegisterBtcTransaction(btcTx.getHash(), 0, pmt.bitcoinSerialize(), Hex.decode("00000000000100")); }
@Test public void validationsForRegisterBtcTransaction_invalid_block_merkle_root() throws IOException, BlockStoreException { BridgeStorageProvider mockBridgeStorageProvider = mock(BridgeStorageProvider.class); when(mockBridgeStorageProvider.getHeightIfBtcTxhashIsAlreadyProcessed(any(Sha256Hash.class))).thenReturn(Optional.empty()); BtcBlockStoreWithCache.Factory btcBlockStoreFactory = mock(BtcBlockStoreWithCache.Factory.class); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); when(btcBlockStoreFactory.newInstance(any(Repository.class))).thenReturn(btcBlockStore); BtcTransaction tx = new BtcTransaction(bridgeConstants.getBtcParams()); BtcECKey srcKey = new BtcECKey(); tx.addInput(PegTestUtils.createHash(1), 0, ScriptBuilder.createInputScript(null, srcKey)); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(tx.getHash()); PartialMerkleTree pmt = new PartialMerkleTree(bridgeConstants.getBtcParams(), bits, hashes, 1); co.rsk.bitcoinj.core.BtcBlock btcBlock = new co.rsk.bitcoinj.core.BtcBlock(bridgeConstants.getBtcParams(), 1, PegTestUtils.createHash(), Sha256Hash.ZERO_HASH, 1, 1, 1, new ArrayList<>()); int height = 1; mockChainOfStoredBlocks(btcBlockStore, btcBlock, height + bridgeConstants.getBtc2RskMinimumAcceptableConfirmations(), height); BridgeSupport bridgeSupport = new BridgeSupport( bridgeConstants, mockBridgeStorageProvider, mock(BridgeEventLogger.class), new BtcLockSenderProvider(), mock(Repository.class), mock(Block.class), mock(Context.class), mock(FederationSupport.class), btcBlockStoreFactory, mock(ActivationConfig.ForBlock.class) ); Assert.assertFalse(bridgeSupport.validationsForRegisterBtcTransaction(tx.getHash(), height, pmt.bitcoinSerialize(), tx.bitcoinSerialize())); }
@Test public void validationsForRegisterBtcTransaction_successful() throws IOException, BlockStoreException { BridgeStorageProvider mockBridgeStorageProvider = mock(BridgeStorageProvider.class); when(mockBridgeStorageProvider.getHeightIfBtcTxhashIsAlreadyProcessed(any(Sha256Hash.class))).thenReturn(Optional.empty()); when(mockBridgeStorageProvider.getNewFederation()).thenReturn(bridgeConstants.getGenesisFederation()); BtcBlockStoreWithCache.Factory btcBlockStoreFactory = mock(BtcBlockStoreWithCache.Factory.class); BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class); when(btcBlockStoreFactory.newInstance(any(Repository.class))).thenReturn(btcBlockStore); Coin lockValue = Coin.COIN; BtcTransaction tx = new BtcTransaction(bridgeConstants.getBtcParams()); tx.addOutput(lockValue, mockBridgeStorageProvider.getNewFederation().getAddress()); BtcECKey srcKey = new BtcECKey(); tx.addInput(PegTestUtils.createHash(1), 0, ScriptBuilder.createInputScript(null, srcKey)); byte[] bits = new byte[1]; bits[0] = 0x3f; List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(tx.getHash()); PartialMerkleTree pmt = new PartialMerkleTree(bridgeConstants.getBtcParams(), bits, hashes, 1); Sha256Hash merkleRoot = pmt.getTxnHashAndMerkleRoot(new ArrayList<>()); co.rsk.bitcoinj.core.BtcBlock btcBlock = new co.rsk.bitcoinj.core.BtcBlock(bridgeConstants.getBtcParams(), 1, PegTestUtils.createHash(), merkleRoot, 1, 1, 1, new ArrayList<>()); int height = 1; mockChainOfStoredBlocks(btcBlockStore, btcBlock, height + bridgeConstants.getBtc2RskMinimumAcceptableConfirmations(), height); BridgeSupport bridgeSupport = new BridgeSupport( bridgeConstants, mockBridgeStorageProvider, mock(BridgeEventLogger.class), new BtcLockSenderProvider(), mock(Repository.class), mock(Block.class), mock(Context.class), mock(FederationSupport.class), btcBlockStoreFactory, mock(ActivationConfig.ForBlock.class) ); Assert.assertTrue(bridgeSupport.validationsForRegisterBtcTransaction(tx.getHash(), height, pmt.bitcoinSerialize(), tx.bitcoinSerialize())); } |
BridgeSupport { public void addSignature(BtcECKey federatorPublicKey, List<byte[]> signatures, byte[] rskTxHash) throws Exception { Context.propagate(btcContext); Federation retiringFederation = getRetiringFederation(); Federation activeFederation = getActiveFederation(); Federation federation = activeFederation.hasBtcPublicKey(federatorPublicKey) ? activeFederation : (retiringFederation != null && retiringFederation.hasBtcPublicKey(federatorPublicKey) ? retiringFederation: null); if (federation == null) { logger.warn("Supplied federator public key {} does not belong to any of the federators.", federatorPublicKey); return; } BtcTransaction btcTx = provider.getRskTxsWaitingForSignatures().get(new Keccak256(rskTxHash)); if (btcTx == null) { logger.warn("No tx waiting for signature for hash {}. Probably fully signed already.", new Keccak256(rskTxHash)); return; } if (btcTx.getInputs().size() != signatures.size()) { logger.warn("Expected {} signatures but received {}.", btcTx.getInputs().size(), signatures.size()); return; } eventLogger.logAddSignature(federatorPublicKey, btcTx, rskTxHash); processSigning(federatorPublicKey, signatures, rskTxHash, btcTx, federation); } BridgeSupport(
BridgeConstants bridgeConstants,
BridgeStorageProvider provider,
BridgeEventLogger eventLogger,
BtcLockSenderProvider btcLockSenderProvider,
Repository repository,
Block executionBlock,
Context btcContext,
FederationSupport federationSupport,
BtcBlockStoreWithCache.Factory btcBlockStoreFactory,
ActivationConfig.ForBlock activations); List<ProgramSubtrace> getSubtraces(); void save(); void receiveHeaders(BtcBlock[] headers); Wallet getActiveFederationWallet(); Wallet getRetiringFederationWallet(); Wallet getUTXOBasedWalletForLiveFederations(List<UTXO> utxos); Wallet getNoSpendWalletForLiveFederations(); void registerBtcTransaction(Transaction rskTx, byte[] btcTxSerialized, int height, byte[] pmtSerialized); void releaseBtc(Transaction rskTx); Coin getFeePerKb(); void updateCollections(Transaction rskTx); void addSignature(BtcECKey federatorPublicKey, List<byte[]> signatures, byte[] rskTxHash); byte[] getStateForBtcReleaseClient(); byte[] getStateForDebugging(); int getBtcBlockchainBestChainHeight(); int getBtcBlockchainInitialBlockHeight(); @Deprecated List<Sha256Hash> getBtcBlockchainBlockLocator(); Sha256Hash getBtcBlockchainBlockHashAtDepth(int depth); Long getBtcTransactionConfirmationsGetCost(Object[] args); Integer getBtcTransactionConfirmations(Sha256Hash btcTxHash, Sha256Hash btcBlockHash, MerkleBranch merkleBranch); Boolean isBtcTxHashAlreadyProcessed(Sha256Hash btcTxHash); Long getBtcTxHashProcessedHeight(Sha256Hash btcTxHash); boolean isAlreadyBtcTxHashProcessed(Sha256Hash btcTxHash); Federation getActiveFederation(); @Nullable Federation getRetiringFederation(); Address getFederationAddress(); Integer getFederationSize(); Integer getFederationThreshold(); byte[] getFederatorPublicKey(int index); byte[] getFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getFederationCreationTime(); long getFederationCreationBlockNumber(); Address getRetiringFederationAddress(); Integer getRetiringFederationSize(); Integer getRetiringFederationThreshold(); byte[] getRetiringFederatorPublicKey(int index); byte[] getRetiringFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getRetiringFederationCreationTime(); long getRetiringFederationCreationBlockNumber(); Integer voteFederationChange(Transaction tx, ABICallSpec callSpec); byte[] getPendingFederationHash(); Integer getPendingFederationSize(); byte[] getPendingFederatorPublicKey(int index); byte[] getPendingFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Integer getLockWhitelistSize(); LockWhitelistEntry getLockWhitelistEntryByIndex(int index); LockWhitelistEntry getLockWhitelistEntryByAddress(String addressBase58); Integer addOneOffLockWhitelistAddress(Transaction tx, String addressBase58, BigInteger maxTransferValue); Integer addUnlimitedLockWhitelistAddress(Transaction tx, String addressBase58); Integer removeLockWhitelistAddress(Transaction tx, String addressBase58); Coin getMinimumLockTxValue(); Integer voteFeePerKbChange(Transaction tx, Coin feePerKb); Integer setLockWhitelistDisableBlockDelay(Transaction tx, BigInteger disableBlockDelayBI); Coin getLockingCap(); boolean increaseLockingCap(Transaction tx, Coin newCap); void registerBtcCoinbaseTransaction(byte[] btcTxSerialized, Sha256Hash blockHash, byte[] pmtSerialized, Sha256Hash witnessMerkleRoot, byte[] witnessReservedValue); boolean hasBtcBlockCoinbaseTransactionInformation(Sha256Hash blockHash); static final RskAddress BURN_ADDRESS; static final int MAX_RELEASE_ITERATIONS; static final Integer FEDERATION_CHANGE_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_INVALID_ADDRESS_FORMAT_ERROR_CODE; static final Integer LOCK_WHITELIST_ALREADY_EXISTS_ERROR_CODE; static final Integer LOCK_WHITELIST_UNKNOWN_ERROR_CODE; static final Integer LOCK_WHITELIST_SUCCESS_CODE; static final Integer FEE_PER_KB_GENERIC_ERROR_CODE; static final Integer NEGATIVE_FEE_PER_KB_ERROR_CODE; static final Integer EXCESSIVE_FEE_PER_KB_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INEXISTENT_BLOCK_HASH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_NOT_IN_BEST_CHAIN_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INCONSISTENT_BLOCK_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_TOO_OLD_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INVALID_MERKLE_BRANCH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_MAX_DEPTH; } | @Test public void addSignature_fedPubKey_no_belong_to_active_federation_no_existing_retiring_fed() throws Exception { BridgeStorageProvider provider = mock(BridgeStorageProvider.class); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, mock(Repository.class), mock(BridgeEventLogger.class), mock(Block.class), null ); bridgeSupport.addSignature(BtcECKey.fromPrivate(Hex.decode("fa03")), null, PegTestUtils.createHash3(1).getBytes()); verify(provider, times(0)).getRskTxsWaitingForSignatures(); } |
BridgeSupport { protected TxType getTransactionType(BtcTransaction btcTx) { if (BridgeUtils.isLockTx(btcTx, getLiveFederations(), btcContext, bridgeConstants)) { return TxType.PEGIN; } if (BridgeUtils.isMigrationTx(btcTx, getActiveFederation(), getRetiringFederation(), btcContext, bridgeConstants)) { return TxType.MIGRATION; } if (BridgeUtils.isReleaseTx(btcTx, getLiveFederations())) { return TxType.PEGOUT; } return TxType.UNKNOWN; } BridgeSupport(
BridgeConstants bridgeConstants,
BridgeStorageProvider provider,
BridgeEventLogger eventLogger,
BtcLockSenderProvider btcLockSenderProvider,
Repository repository,
Block executionBlock,
Context btcContext,
FederationSupport federationSupport,
BtcBlockStoreWithCache.Factory btcBlockStoreFactory,
ActivationConfig.ForBlock activations); List<ProgramSubtrace> getSubtraces(); void save(); void receiveHeaders(BtcBlock[] headers); Wallet getActiveFederationWallet(); Wallet getRetiringFederationWallet(); Wallet getUTXOBasedWalletForLiveFederations(List<UTXO> utxos); Wallet getNoSpendWalletForLiveFederations(); void registerBtcTransaction(Transaction rskTx, byte[] btcTxSerialized, int height, byte[] pmtSerialized); void releaseBtc(Transaction rskTx); Coin getFeePerKb(); void updateCollections(Transaction rskTx); void addSignature(BtcECKey federatorPublicKey, List<byte[]> signatures, byte[] rskTxHash); byte[] getStateForBtcReleaseClient(); byte[] getStateForDebugging(); int getBtcBlockchainBestChainHeight(); int getBtcBlockchainInitialBlockHeight(); @Deprecated List<Sha256Hash> getBtcBlockchainBlockLocator(); Sha256Hash getBtcBlockchainBlockHashAtDepth(int depth); Long getBtcTransactionConfirmationsGetCost(Object[] args); Integer getBtcTransactionConfirmations(Sha256Hash btcTxHash, Sha256Hash btcBlockHash, MerkleBranch merkleBranch); Boolean isBtcTxHashAlreadyProcessed(Sha256Hash btcTxHash); Long getBtcTxHashProcessedHeight(Sha256Hash btcTxHash); boolean isAlreadyBtcTxHashProcessed(Sha256Hash btcTxHash); Federation getActiveFederation(); @Nullable Federation getRetiringFederation(); Address getFederationAddress(); Integer getFederationSize(); Integer getFederationThreshold(); byte[] getFederatorPublicKey(int index); byte[] getFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getFederationCreationTime(); long getFederationCreationBlockNumber(); Address getRetiringFederationAddress(); Integer getRetiringFederationSize(); Integer getRetiringFederationThreshold(); byte[] getRetiringFederatorPublicKey(int index); byte[] getRetiringFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Instant getRetiringFederationCreationTime(); long getRetiringFederationCreationBlockNumber(); Integer voteFederationChange(Transaction tx, ABICallSpec callSpec); byte[] getPendingFederationHash(); Integer getPendingFederationSize(); byte[] getPendingFederatorPublicKey(int index); byte[] getPendingFederatorPublicKeyOfType(int index, FederationMember.KeyType keyType); Integer getLockWhitelistSize(); LockWhitelistEntry getLockWhitelistEntryByIndex(int index); LockWhitelistEntry getLockWhitelistEntryByAddress(String addressBase58); Integer addOneOffLockWhitelistAddress(Transaction tx, String addressBase58, BigInteger maxTransferValue); Integer addUnlimitedLockWhitelistAddress(Transaction tx, String addressBase58); Integer removeLockWhitelistAddress(Transaction tx, String addressBase58); Coin getMinimumLockTxValue(); Integer voteFeePerKbChange(Transaction tx, Coin feePerKb); Integer setLockWhitelistDisableBlockDelay(Transaction tx, BigInteger disableBlockDelayBI); Coin getLockingCap(); boolean increaseLockingCap(Transaction tx, Coin newCap); void registerBtcCoinbaseTransaction(byte[] btcTxSerialized, Sha256Hash blockHash, byte[] pmtSerialized, Sha256Hash witnessMerkleRoot, byte[] witnessReservedValue); boolean hasBtcBlockCoinbaseTransactionInformation(Sha256Hash blockHash); static final RskAddress BURN_ADDRESS; static final int MAX_RELEASE_ITERATIONS; static final Integer FEDERATION_CHANGE_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_GENERIC_ERROR_CODE; static final Integer LOCK_WHITELIST_INVALID_ADDRESS_FORMAT_ERROR_CODE; static final Integer LOCK_WHITELIST_ALREADY_EXISTS_ERROR_CODE; static final Integer LOCK_WHITELIST_UNKNOWN_ERROR_CODE; static final Integer LOCK_WHITELIST_SUCCESS_CODE; static final Integer FEE_PER_KB_GENERIC_ERROR_CODE; static final Integer NEGATIVE_FEE_PER_KB_ERROR_CODE; static final Integer EXCESSIVE_FEE_PER_KB_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INEXISTENT_BLOCK_HASH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_NOT_IN_BEST_CHAIN_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INCONSISTENT_BLOCK_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_BLOCK_TOO_OLD_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_INVALID_MERKLE_BRANCH_ERROR_CODE; static final Integer BTC_TRANSACTION_CONFIRMATION_MAX_DEPTH; } | @Test public void getTransactionType_lock_tx() { BridgeSupport bridgeSupport = getBridgeSupport(bridgeConstants, mock(BridgeStorageProvider.class)); BtcTransaction btcTx = new BtcTransaction(btcParams); btcTx.addOutput(Coin.COIN.multiply(10), bridgeConstants.getGenesisFederation().getAddress()); btcTx.addInput(PegTestUtils.createHash(1), 0, new Script(new byte[]{})); Assert.assertEquals(BridgeSupport.TxType.PEGIN, bridgeSupport.getTransactionType(btcTx)); }
@Test public void getTransactionType_release_tx() { BridgeSupport bridgeSupport = getBridgeSupport(bridgeConstants, mock(BridgeStorageProvider.class)); Federation federation = bridgeConstants.getGenesisFederation(); List<BtcECKey> federationPrivateKeys = BridgeRegTestConstants.REGTEST_FEDERATION_PRIVATE_KEYS; co.rsk.bitcoinj.core.Address randomAddress = new co.rsk.bitcoinj.core.Address( btcParams, org.bouncycastle.util.encoders.Hex.decode("4a22c3c4cbb31e4d03b15550636762bda0baf85a")); BtcTransaction releaseTx1 = new BtcTransaction(btcParams); releaseTx1.addOutput(co.rsk.bitcoinj.core.Coin.COIN, randomAddress); co.rsk.bitcoinj.core.TransactionInput releaseInput1 = new co.rsk.bitcoinj.core.TransactionInput(btcParams, releaseTx1, new byte[]{}, new co.rsk.bitcoinj.core.TransactionOutPoint( btcParams, 0, co.rsk.bitcoinj.core.Sha256Hash.ZERO_HASH) ); releaseTx1.addInput(releaseInput1); co.rsk.bitcoinj.script.Script redeemScript = createBaseRedeemScriptThatSpendsFromTheFederation(federation); co.rsk.bitcoinj.script.Script inputScript = createBaseInputScriptThatSpendsFromTheFederation(federation); releaseInput1.setScriptSig(inputScript); co.rsk.bitcoinj.core.Sha256Hash sighash = releaseTx1.hashForSignature( 0, redeemScript, BtcTransaction.SigHash.ALL, false); for (int i = 0; i < federation.getNumberOfSignaturesRequired(); i++) { BtcECKey federatorPrivKey = federationPrivateKeys.get(i); BtcECKey federatorPublicKey = federation.getBtcPublicKeys().get(i); BtcECKey.ECDSASignature sig = federatorPrivKey.sign(sighash); TransactionSignature txSig = new TransactionSignature(sig, BtcTransaction.SigHash.ALL, false); int sigIndex = inputScript.getSigInsertionIndex(sighash, federatorPublicKey); inputScript = ScriptBuilder.updateScriptWithSignature(inputScript, txSig.encodeToBitcoin(), sigIndex, 1, 1); } releaseInput1.setScriptSig(inputScript); Assert.assertEquals(BridgeSupport.TxType.PEGOUT, bridgeSupport.getTransactionType(releaseTx1)); }
@Test public void getTransactionType_unknown_tx() { BridgeSupport bridgeSupport = getBridgeSupport(bridgeConstants, mock(BridgeStorageProvider.class)); BtcTransaction btcTx = new BtcTransaction(btcParams); Assert.assertEquals(BridgeSupport.TxType.UNKNOWN, bridgeSupport.getTransactionType(btcTx)); } |
AddressBasedAuthorizer { public boolean isAuthorized(RskAddress sender) { return authorizedAddresses.stream() .anyMatch(address -> Arrays.equals(address, sender.getBytes())); } AddressBasedAuthorizer(List<ECKey> authorizedKeys, MinimumRequiredCalculation requiredCalculation); boolean isAuthorized(RskAddress sender); boolean isAuthorized(Transaction tx); int getNumberOfAuthorizedKeys(); int getRequiredAuthorizedKeys(); } | @Test public void isAuthorized() { AddressBasedAuthorizer auth = new AddressBasedAuthorizer(Arrays.asList( ECKey.fromPrivate(BigInteger.valueOf(100L)), ECKey.fromPrivate(BigInteger.valueOf(101L)), ECKey.fromPrivate(BigInteger.valueOf(102L)) ), AddressBasedAuthorizer.MinimumRequiredCalculation.MAJORITY); for (long n = 100L; n <= 102L; n++) { Transaction mockedTx = mock(Transaction.class); when(mockedTx.getSender()).thenReturn(new RskAddress(ECKey.fromPrivate(BigInteger.valueOf(n)).getAddress())); Assert.assertTrue(auth.isAuthorized(new RskAddress(ECKey.fromPrivate(BigInteger.valueOf(n)).getAddress()))); Assert.assertTrue(auth.isAuthorized(mockedTx)); } Assert.assertFalse(auth.isAuthorized(new RskAddress(ECKey.fromPrivate(BigInteger.valueOf(50L)).getAddress()))); Transaction mockedTx = mock(Transaction.class); when(mockedTx.getSender()).thenReturn(new RskAddress(ECKey.fromPrivate(BigInteger.valueOf(50L)).getAddress())); Assert.assertFalse(auth.isAuthorized(mockedTx)); } |
BridgeSerializationUtils { public static byte[] serializeMapOfHashesToLong(Map<Sha256Hash, Long> map) { byte[][] bytes = new byte[map.size() * 2][]; int n = 0; List<Sha256Hash> sortedHashes = new ArrayList<>(map.keySet()); Collections.sort(sortedHashes); for (Sha256Hash hash : sortedHashes) { Long value = map.get(hash); bytes[n++] = RLP.encodeElement(hash.getBytes()); bytes[n++] = RLP.encodeBigInteger(BigInteger.valueOf(value)); } return RLP.encodeList(bytes); } private BridgeSerializationUtils(); static byte[] serializeMap(SortedMap<Keccak256, BtcTransaction> map); static SortedMap<Keccak256, BtcTransaction> deserializeMap(byte[] data, NetworkParameters networkParameters, boolean noInputsTxs); static byte[] serializeUTXOList(List<UTXO> list); static List<UTXO> deserializeUTXOList(byte[] data); static byte[] serializeSet(SortedSet<Sha256Hash> set); static SortedSet<Sha256Hash> deserializeSet(byte[] data); static byte[] serializeMapOfHashesToLong(Map<Sha256Hash, Long> map); static Map<Sha256Hash, Long> deserializeMapOfHashesToLong(byte[] data); static byte[] serializeFederationOnlyBtcKeys(Federation federation); static Federation deserializeFederationOnlyBtcKeys(byte[] data, NetworkParameters networkParameters); static byte[] serializeFederation(Federation federation); static Federation deserializeFederation(byte[] data, NetworkParameters networkParameters); static byte[] serializeFederationMember(FederationMember federationMember); static byte[] serializePendingFederationOnlyBtcKeys(PendingFederation pendingFederation); static PendingFederation deserializePendingFederationOnlyBtcKeys(byte[] data); static byte[] serializePendingFederation(PendingFederation pendingFederation); static PendingFederation deserializePendingFederation(byte[] data); static byte[] serializeElection(ABICallElection election); static ABICallElection deserializeElection(byte[] data, AddressBasedAuthorizer authorizer); static byte[] serializeOneOffLockWhitelist(Pair<List<OneOffWhiteListEntry>, Integer> data); static byte[] serializeUnlimitedLockWhitelist(List<UnlimitedWhiteListEntry> entries); static Pair<HashMap<Address, OneOffWhiteListEntry>, Integer> deserializeOneOffLockWhitelistAndDisableBlockHeight(byte[] data, NetworkParameters parameters); static Map<Address, UnlimitedWhiteListEntry> deserializeUnlimitedLockWhitelistEntries(byte[] data, NetworkParameters parameters); static byte[] serializeCoin(Coin coin); @Nullable static Coin deserializeCoin(byte[] data); static byte[] serializeReleaseRequestQueue(ReleaseRequestQueue queue); static byte[] serializeReleaseRequestQueueWithTxHash(ReleaseRequestQueue queue); static List<ReleaseRequestQueue.Entry> deserializeReleaseRequestQueue(byte[] data, NetworkParameters networkParameters); static List<ReleaseRequestQueue.Entry> deserializeReleaseRequestQueue(byte[] data, NetworkParameters networkParameters, boolean hasTxHash); static byte[] serializeReleaseTransactionSet(ReleaseTransactionSet set); static byte[] serializeReleaseTransactionSetWithTxHash(ReleaseTransactionSet set); static ReleaseTransactionSet deserializeReleaseTransactionSet(byte[] data, NetworkParameters networkParameters); static ReleaseTransactionSet deserializeReleaseTransactionSet(byte[] data, NetworkParameters networkParameters, boolean hasTxHash); static byte[] serializeInteger(Integer value); static Integer deserializeInteger(byte[] data); static byte[] serializeLong(long value); static Optional<Long> deserializeOptionalLong(byte[] data); static CoinbaseInformation deserializeCoinbaseInformation(byte[] data); static byte[] serializeCoinbaseInformation(CoinbaseInformation coinbaseInformation); } | @Test public void serializeMapOfHashesToLong() throws Exception { Map<Sha256Hash, Long> sample = new HashMap<>(); sample.put(Sha256Hash.wrap(charNTimes('b', 64)), 1L); sample.put(Sha256Hash.wrap(charNTimes('d', 64)), 2L); sample.put(Sha256Hash.wrap(charNTimes('a', 64)), 3L); sample.put(Sha256Hash.wrap(charNTimes('c', 64)), 4L); byte[] result = BridgeSerializationUtils.serializeMapOfHashesToLong(sample); String hexResult = ByteUtil.toHexString(result); StringBuilder expectedBuilder = new StringBuilder(); expectedBuilder.append("f888"); char[] sorted = new char[]{'a','b','c','d'}; for (char c : sorted) { String key = charNTimes(c, 64); expectedBuilder.append("a0"); expectedBuilder.append(key); expectedBuilder.append("0" + String.valueOf(sample.get(Sha256Hash.wrap(key)).longValue())); } assertEquals(expectedBuilder.toString(), hexResult); } |
BridgeSerializationUtils { public static Map<Sha256Hash, Long> deserializeMapOfHashesToLong(byte[] data) { Map<Sha256Hash, Long> map = new HashMap<>(); if (data == null || data.length == 0) { return map; } RLPList rlpList = (RLPList) RLP.decode2(data).get(0); if (rlpList.size() % 2 != 0) { throw new RuntimeException("deserializeMapOfHashesToLong: expected an even number of entries, but odd given"); } int numEntries = rlpList.size() / 2; for (int k = 0; k < numEntries; k++) { Sha256Hash hash = Sha256Hash.wrap(rlpList.get(k * 2).getRLPData()); long number = BigIntegers.fromUnsignedByteArray(rlpList.get(k * 2 + 1).getRLPData()).longValue(); map.put(hash, number); } return map; } private BridgeSerializationUtils(); static byte[] serializeMap(SortedMap<Keccak256, BtcTransaction> map); static SortedMap<Keccak256, BtcTransaction> deserializeMap(byte[] data, NetworkParameters networkParameters, boolean noInputsTxs); static byte[] serializeUTXOList(List<UTXO> list); static List<UTXO> deserializeUTXOList(byte[] data); static byte[] serializeSet(SortedSet<Sha256Hash> set); static SortedSet<Sha256Hash> deserializeSet(byte[] data); static byte[] serializeMapOfHashesToLong(Map<Sha256Hash, Long> map); static Map<Sha256Hash, Long> deserializeMapOfHashesToLong(byte[] data); static byte[] serializeFederationOnlyBtcKeys(Federation federation); static Federation deserializeFederationOnlyBtcKeys(byte[] data, NetworkParameters networkParameters); static byte[] serializeFederation(Federation federation); static Federation deserializeFederation(byte[] data, NetworkParameters networkParameters); static byte[] serializeFederationMember(FederationMember federationMember); static byte[] serializePendingFederationOnlyBtcKeys(PendingFederation pendingFederation); static PendingFederation deserializePendingFederationOnlyBtcKeys(byte[] data); static byte[] serializePendingFederation(PendingFederation pendingFederation); static PendingFederation deserializePendingFederation(byte[] data); static byte[] serializeElection(ABICallElection election); static ABICallElection deserializeElection(byte[] data, AddressBasedAuthorizer authorizer); static byte[] serializeOneOffLockWhitelist(Pair<List<OneOffWhiteListEntry>, Integer> data); static byte[] serializeUnlimitedLockWhitelist(List<UnlimitedWhiteListEntry> entries); static Pair<HashMap<Address, OneOffWhiteListEntry>, Integer> deserializeOneOffLockWhitelistAndDisableBlockHeight(byte[] data, NetworkParameters parameters); static Map<Address, UnlimitedWhiteListEntry> deserializeUnlimitedLockWhitelistEntries(byte[] data, NetworkParameters parameters); static byte[] serializeCoin(Coin coin); @Nullable static Coin deserializeCoin(byte[] data); static byte[] serializeReleaseRequestQueue(ReleaseRequestQueue queue); static byte[] serializeReleaseRequestQueueWithTxHash(ReleaseRequestQueue queue); static List<ReleaseRequestQueue.Entry> deserializeReleaseRequestQueue(byte[] data, NetworkParameters networkParameters); static List<ReleaseRequestQueue.Entry> deserializeReleaseRequestQueue(byte[] data, NetworkParameters networkParameters, boolean hasTxHash); static byte[] serializeReleaseTransactionSet(ReleaseTransactionSet set); static byte[] serializeReleaseTransactionSetWithTxHash(ReleaseTransactionSet set); static ReleaseTransactionSet deserializeReleaseTransactionSet(byte[] data, NetworkParameters networkParameters); static ReleaseTransactionSet deserializeReleaseTransactionSet(byte[] data, NetworkParameters networkParameters, boolean hasTxHash); static byte[] serializeInteger(Integer value); static Integer deserializeInteger(byte[] data); static byte[] serializeLong(long value); static Optional<Long> deserializeOptionalLong(byte[] data); static CoinbaseInformation deserializeCoinbaseInformation(byte[] data); static byte[] serializeCoinbaseInformation(CoinbaseInformation coinbaseInformation); } | @Test public void deserializeMapOfHashesToLong_emptyOrNull() throws Exception { assertEquals(BridgeSerializationUtils.deserializeMapOfHashesToLong(null), new HashMap<>()); assertEquals(BridgeSerializationUtils.deserializeMapOfHashesToLong(new byte[]{}), new HashMap<>()); }
@Test public void deserializeMapOfHashesToLong_nonEmpty() throws Exception { byte[] rlpFirstKey = RLP.encodeElement(Hex.decode(charNTimes('b', 64))); byte[] rlpSecondKey = RLP.encodeElement(Hex.decode(charNTimes('d', 64))); byte[] rlpThirdKey = RLP.encodeElement(Hex.decode(charNTimes('a', 64))); byte[] rlpFirstValue = RLP.encodeBigInteger(BigInteger.valueOf(7)); byte[] rlpSecondValue = RLP.encodeBigInteger(BigInteger.valueOf(76)); byte[] rlpThirdValue = RLP.encodeBigInteger(BigInteger.valueOf(123)); byte[] data = RLP.encodeList(rlpFirstKey, rlpFirstValue, rlpSecondKey, rlpSecondValue, rlpThirdKey, rlpThirdValue); Map<Sha256Hash, Long> result = BridgeSerializationUtils.deserializeMapOfHashesToLong(data); assertEquals(3, result.size()); assertEquals(7L, result.get(Sha256Hash.wrap(charNTimes('b', 64))).longValue()); assertEquals(76L, result.get(Sha256Hash.wrap(charNTimes('d', 64))).longValue()); assertEquals(123L, result.get(Sha256Hash.wrap(charNTimes('a', 64))).longValue()); }
@Test public void deserializeMapOfHashesToLong_nonEmptyOddSize() throws Exception { byte[] rlpFirstKey = RLP.encodeElement(Hex.decode(charNTimes('b', 64))); byte[] rlpSecondKey = RLP.encodeElement(Hex.decode(charNTimes('d', 64))); byte[] rlpThirdKey = RLP.encodeElement(Hex.decode(charNTimes('a', 64))); byte[] rlpFourthKey = RLP.encodeElement(Hex.decode(charNTimes('e', 64))); byte[] rlpFirstValue = RLP.encodeBigInteger(BigInteger.valueOf(7)); byte[] rlpSecondValue = RLP.encodeBigInteger(BigInteger.valueOf(76)); byte[] rlpThirdValue = RLP.encodeBigInteger(BigInteger.valueOf(123)); byte[] data = RLP.encodeList(rlpFirstKey, rlpFirstValue, rlpSecondKey, rlpSecondValue, rlpThirdKey, rlpThirdValue, rlpFourthKey); boolean thrown = false; try { BridgeSerializationUtils.deserializeMapOfHashesToLong(data); } catch (RuntimeException e) { thrown = true; } Assert.assertTrue(thrown); } |
BridgeSerializationUtils { public static byte[] serializeFederationOnlyBtcKeys(Federation federation) { return serializeFederationWithSerializer(federation, federationMember -> federationMember.getBtcPublicKey().getPubKeyPoint().getEncoded(true)); } private BridgeSerializationUtils(); static byte[] serializeMap(SortedMap<Keccak256, BtcTransaction> map); static SortedMap<Keccak256, BtcTransaction> deserializeMap(byte[] data, NetworkParameters networkParameters, boolean noInputsTxs); static byte[] serializeUTXOList(List<UTXO> list); static List<UTXO> deserializeUTXOList(byte[] data); static byte[] serializeSet(SortedSet<Sha256Hash> set); static SortedSet<Sha256Hash> deserializeSet(byte[] data); static byte[] serializeMapOfHashesToLong(Map<Sha256Hash, Long> map); static Map<Sha256Hash, Long> deserializeMapOfHashesToLong(byte[] data); static byte[] serializeFederationOnlyBtcKeys(Federation federation); static Federation deserializeFederationOnlyBtcKeys(byte[] data, NetworkParameters networkParameters); static byte[] serializeFederation(Federation federation); static Federation deserializeFederation(byte[] data, NetworkParameters networkParameters); static byte[] serializeFederationMember(FederationMember federationMember); static byte[] serializePendingFederationOnlyBtcKeys(PendingFederation pendingFederation); static PendingFederation deserializePendingFederationOnlyBtcKeys(byte[] data); static byte[] serializePendingFederation(PendingFederation pendingFederation); static PendingFederation deserializePendingFederation(byte[] data); static byte[] serializeElection(ABICallElection election); static ABICallElection deserializeElection(byte[] data, AddressBasedAuthorizer authorizer); static byte[] serializeOneOffLockWhitelist(Pair<List<OneOffWhiteListEntry>, Integer> data); static byte[] serializeUnlimitedLockWhitelist(List<UnlimitedWhiteListEntry> entries); static Pair<HashMap<Address, OneOffWhiteListEntry>, Integer> deserializeOneOffLockWhitelistAndDisableBlockHeight(byte[] data, NetworkParameters parameters); static Map<Address, UnlimitedWhiteListEntry> deserializeUnlimitedLockWhitelistEntries(byte[] data, NetworkParameters parameters); static byte[] serializeCoin(Coin coin); @Nullable static Coin deserializeCoin(byte[] data); static byte[] serializeReleaseRequestQueue(ReleaseRequestQueue queue); static byte[] serializeReleaseRequestQueueWithTxHash(ReleaseRequestQueue queue); static List<ReleaseRequestQueue.Entry> deserializeReleaseRequestQueue(byte[] data, NetworkParameters networkParameters); static List<ReleaseRequestQueue.Entry> deserializeReleaseRequestQueue(byte[] data, NetworkParameters networkParameters, boolean hasTxHash); static byte[] serializeReleaseTransactionSet(ReleaseTransactionSet set); static byte[] serializeReleaseTransactionSetWithTxHash(ReleaseTransactionSet set); static ReleaseTransactionSet deserializeReleaseTransactionSet(byte[] data, NetworkParameters networkParameters); static ReleaseTransactionSet deserializeReleaseTransactionSet(byte[] data, NetworkParameters networkParameters, boolean hasTxHash); static byte[] serializeInteger(Integer value); static Integer deserializeInteger(byte[] data); static byte[] serializeLong(long value); static Optional<Long> deserializeOptionalLong(byte[] data); static CoinbaseInformation deserializeCoinbaseInformation(byte[] data); static byte[] serializeCoinbaseInformation(CoinbaseInformation coinbaseInformation); } | @Test public void serializeFederationOnlyBtcKeys() throws Exception { byte[][] publicKeyBytes = new byte[][]{ BtcECKey.fromPrivate(BigInteger.valueOf(100)).getPubKey(), BtcECKey.fromPrivate(BigInteger.valueOf(200)).getPubKey(), BtcECKey.fromPrivate(BigInteger.valueOf(300)).getPubKey(), BtcECKey.fromPrivate(BigInteger.valueOf(400)).getPubKey(), BtcECKey.fromPrivate(BigInteger.valueOf(500)).getPubKey(), BtcECKey.fromPrivate(BigInteger.valueOf(600)).getPubKey(), }; Federation federation = new Federation( FederationTestUtils.getFederationMembersWithBtcKeys(Arrays.asList(new BtcECKey[]{ BtcECKey.fromPublicOnly(publicKeyBytes[0]), BtcECKey.fromPublicOnly(publicKeyBytes[1]), BtcECKey.fromPublicOnly(publicKeyBytes[2]), BtcECKey.fromPublicOnly(publicKeyBytes[3]), BtcECKey.fromPublicOnly(publicKeyBytes[4]), BtcECKey.fromPublicOnly(publicKeyBytes[5]), })), Instant.ofEpochMilli(0xabcdef), 42L, NetworkParameters.fromID(NetworkParameters.ID_REGTEST) ); byte[] result = BridgeSerializationUtils.serializeFederationOnlyBtcKeys(federation); StringBuilder expectedBuilder = new StringBuilder(); expectedBuilder.append("f8d3"); expectedBuilder.append("83abcdef"); expectedBuilder.append("2a"); expectedBuilder.append("f8cc"); federation.getBtcPublicKeys().stream().sorted(BtcECKey.PUBKEY_COMPARATOR).forEach(key -> { expectedBuilder.append("a1"); expectedBuilder.append(ByteUtil.toHexString(key.getPubKey())); }); String expected = expectedBuilder.toString(); Assert.assertEquals(expected, ByteUtil.toHexString(result)); } |
BridgeSerializationUtils { public static Federation deserializeFederationOnlyBtcKeys(byte[] data, NetworkParameters networkParameters) { return deserializeFederationWithDesserializer(data, networkParameters, (pubKeyBytes -> FederationMember.getFederationMemberFromKey(BtcECKey.fromPublicOnly(pubKeyBytes)))); } private BridgeSerializationUtils(); static byte[] serializeMap(SortedMap<Keccak256, BtcTransaction> map); static SortedMap<Keccak256, BtcTransaction> deserializeMap(byte[] data, NetworkParameters networkParameters, boolean noInputsTxs); static byte[] serializeUTXOList(List<UTXO> list); static List<UTXO> deserializeUTXOList(byte[] data); static byte[] serializeSet(SortedSet<Sha256Hash> set); static SortedSet<Sha256Hash> deserializeSet(byte[] data); static byte[] serializeMapOfHashesToLong(Map<Sha256Hash, Long> map); static Map<Sha256Hash, Long> deserializeMapOfHashesToLong(byte[] data); static byte[] serializeFederationOnlyBtcKeys(Federation federation); static Federation deserializeFederationOnlyBtcKeys(byte[] data, NetworkParameters networkParameters); static byte[] serializeFederation(Federation federation); static Federation deserializeFederation(byte[] data, NetworkParameters networkParameters); static byte[] serializeFederationMember(FederationMember federationMember); static byte[] serializePendingFederationOnlyBtcKeys(PendingFederation pendingFederation); static PendingFederation deserializePendingFederationOnlyBtcKeys(byte[] data); static byte[] serializePendingFederation(PendingFederation pendingFederation); static PendingFederation deserializePendingFederation(byte[] data); static byte[] serializeElection(ABICallElection election); static ABICallElection deserializeElection(byte[] data, AddressBasedAuthorizer authorizer); static byte[] serializeOneOffLockWhitelist(Pair<List<OneOffWhiteListEntry>, Integer> data); static byte[] serializeUnlimitedLockWhitelist(List<UnlimitedWhiteListEntry> entries); static Pair<HashMap<Address, OneOffWhiteListEntry>, Integer> deserializeOneOffLockWhitelistAndDisableBlockHeight(byte[] data, NetworkParameters parameters); static Map<Address, UnlimitedWhiteListEntry> deserializeUnlimitedLockWhitelistEntries(byte[] data, NetworkParameters parameters); static byte[] serializeCoin(Coin coin); @Nullable static Coin deserializeCoin(byte[] data); static byte[] serializeReleaseRequestQueue(ReleaseRequestQueue queue); static byte[] serializeReleaseRequestQueueWithTxHash(ReleaseRequestQueue queue); static List<ReleaseRequestQueue.Entry> deserializeReleaseRequestQueue(byte[] data, NetworkParameters networkParameters); static List<ReleaseRequestQueue.Entry> deserializeReleaseRequestQueue(byte[] data, NetworkParameters networkParameters, boolean hasTxHash); static byte[] serializeReleaseTransactionSet(ReleaseTransactionSet set); static byte[] serializeReleaseTransactionSetWithTxHash(ReleaseTransactionSet set); static ReleaseTransactionSet deserializeReleaseTransactionSet(byte[] data, NetworkParameters networkParameters); static ReleaseTransactionSet deserializeReleaseTransactionSet(byte[] data, NetworkParameters networkParameters, boolean hasTxHash); static byte[] serializeInteger(Integer value); static Integer deserializeInteger(byte[] data); static byte[] serializeLong(long value); static Optional<Long> deserializeOptionalLong(byte[] data); static CoinbaseInformation deserializeCoinbaseInformation(byte[] data); static byte[] serializeCoinbaseInformation(CoinbaseInformation coinbaseInformation); } | @Test public void deserializeFederationOnlyBtcKeys_ok() throws Exception { byte[][] publicKeyBytes = Arrays.asList(100, 200, 300, 400, 500, 600).stream() .map(k -> BtcECKey.fromPrivate(BigInteger.valueOf(k))) .sorted(BtcECKey.PUBKEY_COMPARATOR) .map(k -> k.getPubKey()) .toArray(byte[][]::new); byte[][] rlpKeys = new byte[publicKeyBytes.length][]; for (int k = 0; k < publicKeyBytes.length; k++) { rlpKeys[k] = RLP.encodeElement(publicKeyBytes[k]); } byte[] rlpFirstElement = RLP.encodeElement(Hex.decode("1388")); byte[] rlpSecondElement = RLP.encodeElement(Hex.decode("002a")); byte[] rlpKeyList = RLP.encodeList(rlpKeys); byte[] data = RLP.encodeList(rlpFirstElement, rlpSecondElement, rlpKeyList); Federation deserializedFederation = BridgeSerializationUtils.deserializeFederationOnlyBtcKeys(data, NetworkParameters.fromID(NetworkParameters.ID_REGTEST)); Assert.assertEquals(5000, deserializedFederation.getCreationTime().toEpochMilli()); Assert.assertEquals(4, deserializedFederation.getNumberOfSignaturesRequired()); Assert.assertEquals(6, deserializedFederation.getBtcPublicKeys().size()); Assert.assertThat(deserializedFederation.getCreationBlockNumber(), is(42L)); for (int i = 0; i < 6; i++) { Assert.assertTrue(Arrays.equals(publicKeyBytes[i], deserializedFederation.getBtcPublicKeys().get(i).getPubKey())); } Assert.assertEquals(NetworkParameters.fromID(NetworkParameters.ID_REGTEST), deserializedFederation.getBtcParams()); }
@Test public void deserializeFederationOnlyBtcKeys_wrongListSize() throws Exception { byte[] rlpFirstElement = RLP.encodeElement(Hex.decode("1388")); byte[] rlpSecondElement = RLP.encodeElement(Hex.decode("03")); byte[] rlpThirdElement = RLP.encodeElement(Hex.decode("03")); byte[] rlpFourthElement = RLP.encodeElement(Hex.decode("aabbccdd")); byte[] data = RLP.encodeList(rlpFirstElement, rlpSecondElement, rlpThirdElement, rlpFourthElement); boolean thrown = false; try { BridgeSerializationUtils.deserializeFederationOnlyBtcKeys(data, NetworkParameters.fromID(NetworkParameters.ID_REGTEST)); } catch (Exception e) { Assert.assertTrue(e.getMessage().contains("Expected 3 elements")); thrown = true; } Assert.assertTrue(thrown); } |
BridgeSerializationUtils { public static byte[] serializeFederation(Federation federation) { return serializeFederationWithSerializer(federation, BridgeSerializationUtils::serializeFederationMember); } private BridgeSerializationUtils(); static byte[] serializeMap(SortedMap<Keccak256, BtcTransaction> map); static SortedMap<Keccak256, BtcTransaction> deserializeMap(byte[] data, NetworkParameters networkParameters, boolean noInputsTxs); static byte[] serializeUTXOList(List<UTXO> list); static List<UTXO> deserializeUTXOList(byte[] data); static byte[] serializeSet(SortedSet<Sha256Hash> set); static SortedSet<Sha256Hash> deserializeSet(byte[] data); static byte[] serializeMapOfHashesToLong(Map<Sha256Hash, Long> map); static Map<Sha256Hash, Long> deserializeMapOfHashesToLong(byte[] data); static byte[] serializeFederationOnlyBtcKeys(Federation federation); static Federation deserializeFederationOnlyBtcKeys(byte[] data, NetworkParameters networkParameters); static byte[] serializeFederation(Federation federation); static Federation deserializeFederation(byte[] data, NetworkParameters networkParameters); static byte[] serializeFederationMember(FederationMember federationMember); static byte[] serializePendingFederationOnlyBtcKeys(PendingFederation pendingFederation); static PendingFederation deserializePendingFederationOnlyBtcKeys(byte[] data); static byte[] serializePendingFederation(PendingFederation pendingFederation); static PendingFederation deserializePendingFederation(byte[] data); static byte[] serializeElection(ABICallElection election); static ABICallElection deserializeElection(byte[] data, AddressBasedAuthorizer authorizer); static byte[] serializeOneOffLockWhitelist(Pair<List<OneOffWhiteListEntry>, Integer> data); static byte[] serializeUnlimitedLockWhitelist(List<UnlimitedWhiteListEntry> entries); static Pair<HashMap<Address, OneOffWhiteListEntry>, Integer> deserializeOneOffLockWhitelistAndDisableBlockHeight(byte[] data, NetworkParameters parameters); static Map<Address, UnlimitedWhiteListEntry> deserializeUnlimitedLockWhitelistEntries(byte[] data, NetworkParameters parameters); static byte[] serializeCoin(Coin coin); @Nullable static Coin deserializeCoin(byte[] data); static byte[] serializeReleaseRequestQueue(ReleaseRequestQueue queue); static byte[] serializeReleaseRequestQueueWithTxHash(ReleaseRequestQueue queue); static List<ReleaseRequestQueue.Entry> deserializeReleaseRequestQueue(byte[] data, NetworkParameters networkParameters); static List<ReleaseRequestQueue.Entry> deserializeReleaseRequestQueue(byte[] data, NetworkParameters networkParameters, boolean hasTxHash); static byte[] serializeReleaseTransactionSet(ReleaseTransactionSet set); static byte[] serializeReleaseTransactionSetWithTxHash(ReleaseTransactionSet set); static ReleaseTransactionSet deserializeReleaseTransactionSet(byte[] data, NetworkParameters networkParameters); static ReleaseTransactionSet deserializeReleaseTransactionSet(byte[] data, NetworkParameters networkParameters, boolean hasTxHash); static byte[] serializeInteger(Integer value); static Integer deserializeInteger(byte[] data); static byte[] serializeLong(long value); static Optional<Long> deserializeOptionalLong(byte[] data); static CoinbaseInformation deserializeCoinbaseInformation(byte[] data); static byte[] serializeCoinbaseInformation(CoinbaseInformation coinbaseInformation); } | @Test public void serializeFederation_serializedKeysAreCompressedAndThree() { final int NUM_MEMBERS = 10; final int EXPECTED_NUM_KEYS = 3; final int EXPECTED_PUBLICKEY_SIZE = 33; List<FederationMember> members = new ArrayList<>(); for (int j = 0; j < NUM_MEMBERS; j++) { members.add(new FederationMember(new BtcECKey(), new ECKey(), new ECKey())); } Federation testFederation = new Federation( members, Instant.now(), 123, NetworkParameters.fromID(NetworkParameters.ID_REGTEST) ); byte[] serializedFederation = BridgeSerializationUtils.serializeFederation(testFederation); RLPList serializedList = (RLPList) RLP.decode2(serializedFederation).get(0); Assert.assertEquals(3, serializedList.size()); RLPList memberList = (RLPList) serializedList.get(2); Assert.assertEquals(NUM_MEMBERS, memberList.size()); for (int i = 0; i < NUM_MEMBERS; i++) { RLPList memberKeys = (RLPList) RLP.decode2(memberList.get(i).getRLPData()).get(0); Assert.assertEquals(EXPECTED_NUM_KEYS, memberKeys.size()); for (int j = 0; j < EXPECTED_NUM_KEYS; j++) { Assert.assertEquals(EXPECTED_PUBLICKEY_SIZE, memberKeys.get(j).getRLPData().length); } } } |
BridgeSerializationUtils { public static Federation deserializeFederation(byte[] data, NetworkParameters networkParameters) { return deserializeFederationWithDesserializer(data, networkParameters, BridgeSerializationUtils::deserializeFederationMember); } private BridgeSerializationUtils(); static byte[] serializeMap(SortedMap<Keccak256, BtcTransaction> map); static SortedMap<Keccak256, BtcTransaction> deserializeMap(byte[] data, NetworkParameters networkParameters, boolean noInputsTxs); static byte[] serializeUTXOList(List<UTXO> list); static List<UTXO> deserializeUTXOList(byte[] data); static byte[] serializeSet(SortedSet<Sha256Hash> set); static SortedSet<Sha256Hash> deserializeSet(byte[] data); static byte[] serializeMapOfHashesToLong(Map<Sha256Hash, Long> map); static Map<Sha256Hash, Long> deserializeMapOfHashesToLong(byte[] data); static byte[] serializeFederationOnlyBtcKeys(Federation federation); static Federation deserializeFederationOnlyBtcKeys(byte[] data, NetworkParameters networkParameters); static byte[] serializeFederation(Federation federation); static Federation deserializeFederation(byte[] data, NetworkParameters networkParameters); static byte[] serializeFederationMember(FederationMember federationMember); static byte[] serializePendingFederationOnlyBtcKeys(PendingFederation pendingFederation); static PendingFederation deserializePendingFederationOnlyBtcKeys(byte[] data); static byte[] serializePendingFederation(PendingFederation pendingFederation); static PendingFederation deserializePendingFederation(byte[] data); static byte[] serializeElection(ABICallElection election); static ABICallElection deserializeElection(byte[] data, AddressBasedAuthorizer authorizer); static byte[] serializeOneOffLockWhitelist(Pair<List<OneOffWhiteListEntry>, Integer> data); static byte[] serializeUnlimitedLockWhitelist(List<UnlimitedWhiteListEntry> entries); static Pair<HashMap<Address, OneOffWhiteListEntry>, Integer> deserializeOneOffLockWhitelistAndDisableBlockHeight(byte[] data, NetworkParameters parameters); static Map<Address, UnlimitedWhiteListEntry> deserializeUnlimitedLockWhitelistEntries(byte[] data, NetworkParameters parameters); static byte[] serializeCoin(Coin coin); @Nullable static Coin deserializeCoin(byte[] data); static byte[] serializeReleaseRequestQueue(ReleaseRequestQueue queue); static byte[] serializeReleaseRequestQueueWithTxHash(ReleaseRequestQueue queue); static List<ReleaseRequestQueue.Entry> deserializeReleaseRequestQueue(byte[] data, NetworkParameters networkParameters); static List<ReleaseRequestQueue.Entry> deserializeReleaseRequestQueue(byte[] data, NetworkParameters networkParameters, boolean hasTxHash); static byte[] serializeReleaseTransactionSet(ReleaseTransactionSet set); static byte[] serializeReleaseTransactionSetWithTxHash(ReleaseTransactionSet set); static ReleaseTransactionSet deserializeReleaseTransactionSet(byte[] data, NetworkParameters networkParameters); static ReleaseTransactionSet deserializeReleaseTransactionSet(byte[] data, NetworkParameters networkParameters, boolean hasTxHash); static byte[] serializeInteger(Integer value); static Integer deserializeInteger(byte[] data); static byte[] serializeLong(long value); static Optional<Long> deserializeOptionalLong(byte[] data); static CoinbaseInformation deserializeCoinbaseInformation(byte[] data); static byte[] serializeCoinbaseInformation(CoinbaseInformation coinbaseInformation); } | @Test public void deserializeFederation_wrongListSize() { byte[] serialized = RLP.encodeList(RLP.encodeElement(new byte[0]), RLP.encodeElement(new byte[0])); try { BridgeSerializationUtils.deserializeFederation(serialized, NetworkParameters.fromID(NetworkParameters.ID_REGTEST)); Assert.fail(); } catch (RuntimeException e) { Assert.assertTrue(e.getMessage().contains("Invalid serialized Federation")); } }
@Test public void deserializeFederation_invalidFederationMember() { byte[] serialized = RLP.encodeList( RLP.encodeElement(BigInteger.valueOf(1).toByteArray()), RLP.encodeElement(BigInteger.valueOf(1).toByteArray()), RLP.encodeList(RLP.encodeList(RLP.encodeElement(new byte[0]), RLP.encodeElement(new byte[0]))) ); try { BridgeSerializationUtils.deserializeFederation(serialized, NetworkParameters.fromID(NetworkParameters.ID_REGTEST)); Assert.fail(); } catch (RuntimeException e) { Assert.assertTrue(e.getMessage().contains("Invalid serialized FederationMember")); } } |
BridgeSerializationUtils { public static byte[] serializePendingFederation(PendingFederation pendingFederation) { List<byte[]> encodedMembers = pendingFederation.getMembers().stream() .sorted(FederationMember.BTC_RSK_MST_PUBKEYS_COMPARATOR) .map(BridgeSerializationUtils::serializeFederationMember) .collect(Collectors.toList()); return RLP.encodeList(encodedMembers.toArray(new byte[0][])); } private BridgeSerializationUtils(); static byte[] serializeMap(SortedMap<Keccak256, BtcTransaction> map); static SortedMap<Keccak256, BtcTransaction> deserializeMap(byte[] data, NetworkParameters networkParameters, boolean noInputsTxs); static byte[] serializeUTXOList(List<UTXO> list); static List<UTXO> deserializeUTXOList(byte[] data); static byte[] serializeSet(SortedSet<Sha256Hash> set); static SortedSet<Sha256Hash> deserializeSet(byte[] data); static byte[] serializeMapOfHashesToLong(Map<Sha256Hash, Long> map); static Map<Sha256Hash, Long> deserializeMapOfHashesToLong(byte[] data); static byte[] serializeFederationOnlyBtcKeys(Federation federation); static Federation deserializeFederationOnlyBtcKeys(byte[] data, NetworkParameters networkParameters); static byte[] serializeFederation(Federation federation); static Federation deserializeFederation(byte[] data, NetworkParameters networkParameters); static byte[] serializeFederationMember(FederationMember federationMember); static byte[] serializePendingFederationOnlyBtcKeys(PendingFederation pendingFederation); static PendingFederation deserializePendingFederationOnlyBtcKeys(byte[] data); static byte[] serializePendingFederation(PendingFederation pendingFederation); static PendingFederation deserializePendingFederation(byte[] data); static byte[] serializeElection(ABICallElection election); static ABICallElection deserializeElection(byte[] data, AddressBasedAuthorizer authorizer); static byte[] serializeOneOffLockWhitelist(Pair<List<OneOffWhiteListEntry>, Integer> data); static byte[] serializeUnlimitedLockWhitelist(List<UnlimitedWhiteListEntry> entries); static Pair<HashMap<Address, OneOffWhiteListEntry>, Integer> deserializeOneOffLockWhitelistAndDisableBlockHeight(byte[] data, NetworkParameters parameters); static Map<Address, UnlimitedWhiteListEntry> deserializeUnlimitedLockWhitelistEntries(byte[] data, NetworkParameters parameters); static byte[] serializeCoin(Coin coin); @Nullable static Coin deserializeCoin(byte[] data); static byte[] serializeReleaseRequestQueue(ReleaseRequestQueue queue); static byte[] serializeReleaseRequestQueueWithTxHash(ReleaseRequestQueue queue); static List<ReleaseRequestQueue.Entry> deserializeReleaseRequestQueue(byte[] data, NetworkParameters networkParameters); static List<ReleaseRequestQueue.Entry> deserializeReleaseRequestQueue(byte[] data, NetworkParameters networkParameters, boolean hasTxHash); static byte[] serializeReleaseTransactionSet(ReleaseTransactionSet set); static byte[] serializeReleaseTransactionSetWithTxHash(ReleaseTransactionSet set); static ReleaseTransactionSet deserializeReleaseTransactionSet(byte[] data, NetworkParameters networkParameters); static ReleaseTransactionSet deserializeReleaseTransactionSet(byte[] data, NetworkParameters networkParameters, boolean hasTxHash); static byte[] serializeInteger(Integer value); static Integer deserializeInteger(byte[] data); static byte[] serializeLong(long value); static Optional<Long> deserializeOptionalLong(byte[] data); static CoinbaseInformation deserializeCoinbaseInformation(byte[] data); static byte[] serializeCoinbaseInformation(CoinbaseInformation coinbaseInformation); } | @Test public void serializePendingFederation_serializedKeysAreCompressedAndThree() { final int NUM_MEMBERS = 10; final int EXPECTED_NUM_KEYS = 3; final int EXPECTED_PUBLICKEY_SIZE = 33; List<FederationMember> members = new ArrayList<>(); for (int j = 0; j < NUM_MEMBERS; j++) { members.add(new FederationMember(new BtcECKey(), new ECKey(), new ECKey())); } PendingFederation testPendingFederation = new PendingFederation(members); byte[] serializedPendingFederation = BridgeSerializationUtils.serializePendingFederation(testPendingFederation); RLPList memberList = (RLPList) RLP.decode2(serializedPendingFederation).get(0); Assert.assertEquals(NUM_MEMBERS, memberList.size()); for (int i = 0; i < NUM_MEMBERS; i++) { RLPList memberKeys = (RLPList) RLP.decode2(memberList.get(i).getRLPData()).get(0); Assert.assertEquals(EXPECTED_NUM_KEYS, memberKeys.size()); for (int j = 0; j < EXPECTED_NUM_KEYS; j++) { Assert.assertEquals(EXPECTED_PUBLICKEY_SIZE, memberKeys.get(j).getRLPData().length); } } } |
BridgeSerializationUtils { public static PendingFederation deserializePendingFederation(byte[] data) { RLPList rlpList = (RLPList)RLP.decode2(data).get(0); List<FederationMember> members = new ArrayList<>(); for (int k = 0; k < rlpList.size(); k++) { RLPElement element = rlpList.get(k); FederationMember member = deserializeFederationMember(element.getRLPData()); members.add(member); } return new PendingFederation(members); } private BridgeSerializationUtils(); static byte[] serializeMap(SortedMap<Keccak256, BtcTransaction> map); static SortedMap<Keccak256, BtcTransaction> deserializeMap(byte[] data, NetworkParameters networkParameters, boolean noInputsTxs); static byte[] serializeUTXOList(List<UTXO> list); static List<UTXO> deserializeUTXOList(byte[] data); static byte[] serializeSet(SortedSet<Sha256Hash> set); static SortedSet<Sha256Hash> deserializeSet(byte[] data); static byte[] serializeMapOfHashesToLong(Map<Sha256Hash, Long> map); static Map<Sha256Hash, Long> deserializeMapOfHashesToLong(byte[] data); static byte[] serializeFederationOnlyBtcKeys(Federation federation); static Federation deserializeFederationOnlyBtcKeys(byte[] data, NetworkParameters networkParameters); static byte[] serializeFederation(Federation federation); static Federation deserializeFederation(byte[] data, NetworkParameters networkParameters); static byte[] serializeFederationMember(FederationMember federationMember); static byte[] serializePendingFederationOnlyBtcKeys(PendingFederation pendingFederation); static PendingFederation deserializePendingFederationOnlyBtcKeys(byte[] data); static byte[] serializePendingFederation(PendingFederation pendingFederation); static PendingFederation deserializePendingFederation(byte[] data); static byte[] serializeElection(ABICallElection election); static ABICallElection deserializeElection(byte[] data, AddressBasedAuthorizer authorizer); static byte[] serializeOneOffLockWhitelist(Pair<List<OneOffWhiteListEntry>, Integer> data); static byte[] serializeUnlimitedLockWhitelist(List<UnlimitedWhiteListEntry> entries); static Pair<HashMap<Address, OneOffWhiteListEntry>, Integer> deserializeOneOffLockWhitelistAndDisableBlockHeight(byte[] data, NetworkParameters parameters); static Map<Address, UnlimitedWhiteListEntry> deserializeUnlimitedLockWhitelistEntries(byte[] data, NetworkParameters parameters); static byte[] serializeCoin(Coin coin); @Nullable static Coin deserializeCoin(byte[] data); static byte[] serializeReleaseRequestQueue(ReleaseRequestQueue queue); static byte[] serializeReleaseRequestQueueWithTxHash(ReleaseRequestQueue queue); static List<ReleaseRequestQueue.Entry> deserializeReleaseRequestQueue(byte[] data, NetworkParameters networkParameters); static List<ReleaseRequestQueue.Entry> deserializeReleaseRequestQueue(byte[] data, NetworkParameters networkParameters, boolean hasTxHash); static byte[] serializeReleaseTransactionSet(ReleaseTransactionSet set); static byte[] serializeReleaseTransactionSetWithTxHash(ReleaseTransactionSet set); static ReleaseTransactionSet deserializeReleaseTransactionSet(byte[] data, NetworkParameters networkParameters); static ReleaseTransactionSet deserializeReleaseTransactionSet(byte[] data, NetworkParameters networkParameters, boolean hasTxHash); static byte[] serializeInteger(Integer value); static Integer deserializeInteger(byte[] data); static byte[] serializeLong(long value); static Optional<Long> deserializeOptionalLong(byte[] data); static CoinbaseInformation deserializeCoinbaseInformation(byte[] data); static byte[] serializeCoinbaseInformation(CoinbaseInformation coinbaseInformation); } | @Test public void deserializePendingFederation_invalidFederationMember() { byte[] serialized = RLP.encodeList( RLP.encodeList(RLP.encodeElement(new byte[0]), RLP.encodeElement(new byte[0])) ); try { BridgeSerializationUtils.deserializePendingFederation(serialized); Assert.fail(); } catch (RuntimeException e) { Assert.assertTrue(e.getMessage().contains("Invalid serialized FederationMember")); } } |
BridgeSerializationUtils { public static byte[] serializePendingFederationOnlyBtcKeys(PendingFederation pendingFederation) { return serializeBtcPublicKeys(pendingFederation.getBtcPublicKeys()); } private BridgeSerializationUtils(); static byte[] serializeMap(SortedMap<Keccak256, BtcTransaction> map); static SortedMap<Keccak256, BtcTransaction> deserializeMap(byte[] data, NetworkParameters networkParameters, boolean noInputsTxs); static byte[] serializeUTXOList(List<UTXO> list); static List<UTXO> deserializeUTXOList(byte[] data); static byte[] serializeSet(SortedSet<Sha256Hash> set); static SortedSet<Sha256Hash> deserializeSet(byte[] data); static byte[] serializeMapOfHashesToLong(Map<Sha256Hash, Long> map); static Map<Sha256Hash, Long> deserializeMapOfHashesToLong(byte[] data); static byte[] serializeFederationOnlyBtcKeys(Federation federation); static Federation deserializeFederationOnlyBtcKeys(byte[] data, NetworkParameters networkParameters); static byte[] serializeFederation(Federation federation); static Federation deserializeFederation(byte[] data, NetworkParameters networkParameters); static byte[] serializeFederationMember(FederationMember federationMember); static byte[] serializePendingFederationOnlyBtcKeys(PendingFederation pendingFederation); static PendingFederation deserializePendingFederationOnlyBtcKeys(byte[] data); static byte[] serializePendingFederation(PendingFederation pendingFederation); static PendingFederation deserializePendingFederation(byte[] data); static byte[] serializeElection(ABICallElection election); static ABICallElection deserializeElection(byte[] data, AddressBasedAuthorizer authorizer); static byte[] serializeOneOffLockWhitelist(Pair<List<OneOffWhiteListEntry>, Integer> data); static byte[] serializeUnlimitedLockWhitelist(List<UnlimitedWhiteListEntry> entries); static Pair<HashMap<Address, OneOffWhiteListEntry>, Integer> deserializeOneOffLockWhitelistAndDisableBlockHeight(byte[] data, NetworkParameters parameters); static Map<Address, UnlimitedWhiteListEntry> deserializeUnlimitedLockWhitelistEntries(byte[] data, NetworkParameters parameters); static byte[] serializeCoin(Coin coin); @Nullable static Coin deserializeCoin(byte[] data); static byte[] serializeReleaseRequestQueue(ReleaseRequestQueue queue); static byte[] serializeReleaseRequestQueueWithTxHash(ReleaseRequestQueue queue); static List<ReleaseRequestQueue.Entry> deserializeReleaseRequestQueue(byte[] data, NetworkParameters networkParameters); static List<ReleaseRequestQueue.Entry> deserializeReleaseRequestQueue(byte[] data, NetworkParameters networkParameters, boolean hasTxHash); static byte[] serializeReleaseTransactionSet(ReleaseTransactionSet set); static byte[] serializeReleaseTransactionSetWithTxHash(ReleaseTransactionSet set); static ReleaseTransactionSet deserializeReleaseTransactionSet(byte[] data, NetworkParameters networkParameters); static ReleaseTransactionSet deserializeReleaseTransactionSet(byte[] data, NetworkParameters networkParameters, boolean hasTxHash); static byte[] serializeInteger(Integer value); static Integer deserializeInteger(byte[] data); static byte[] serializeLong(long value); static Optional<Long> deserializeOptionalLong(byte[] data); static CoinbaseInformation deserializeCoinbaseInformation(byte[] data); static byte[] serializeCoinbaseInformation(CoinbaseInformation coinbaseInformation); } | @Test public void serializePendingFederationOnlyBtcKeys() throws Exception { byte[][] publicKeyBytes = new byte[][]{ BtcECKey.fromPrivate(BigInteger.valueOf(100)).getPubKey(), BtcECKey.fromPrivate(BigInteger.valueOf(200)).getPubKey(), BtcECKey.fromPrivate(BigInteger.valueOf(300)).getPubKey(), BtcECKey.fromPrivate(BigInteger.valueOf(400)).getPubKey(), BtcECKey.fromPrivate(BigInteger.valueOf(500)).getPubKey(), BtcECKey.fromPrivate(BigInteger.valueOf(600)).getPubKey(), }; PendingFederation pendingFederation = new PendingFederation( FederationTestUtils.getFederationMembersWithBtcKeys(Arrays.asList(new BtcECKey[]{ BtcECKey.fromPublicOnly(publicKeyBytes[0]), BtcECKey.fromPublicOnly(publicKeyBytes[1]), BtcECKey.fromPublicOnly(publicKeyBytes[2]), BtcECKey.fromPublicOnly(publicKeyBytes[3]), BtcECKey.fromPublicOnly(publicKeyBytes[4]), BtcECKey.fromPublicOnly(publicKeyBytes[5]), })) ); byte[] result = BridgeSerializationUtils.serializePendingFederationOnlyBtcKeys(pendingFederation); StringBuilder expectedBuilder = new StringBuilder(); expectedBuilder.append("f8cc"); pendingFederation.getBtcPublicKeys().stream().sorted(BtcECKey.PUBKEY_COMPARATOR).forEach(key -> { expectedBuilder.append("a1"); expectedBuilder.append(ByteUtil.toHexString(key.getPubKey())); }); String expected = expectedBuilder.toString(); Assert.assertEquals(expected, ByteUtil.toHexString(result)); } |
BridgeSerializationUtils { public static PendingFederation deserializePendingFederationOnlyBtcKeys(byte[] data) { List<FederationMember> members = deserializeBtcPublicKeys(data).stream().map(pk -> FederationMember.getFederationMemberFromKey(pk) ).collect(Collectors.toList()); return new PendingFederation(members); } private BridgeSerializationUtils(); static byte[] serializeMap(SortedMap<Keccak256, BtcTransaction> map); static SortedMap<Keccak256, BtcTransaction> deserializeMap(byte[] data, NetworkParameters networkParameters, boolean noInputsTxs); static byte[] serializeUTXOList(List<UTXO> list); static List<UTXO> deserializeUTXOList(byte[] data); static byte[] serializeSet(SortedSet<Sha256Hash> set); static SortedSet<Sha256Hash> deserializeSet(byte[] data); static byte[] serializeMapOfHashesToLong(Map<Sha256Hash, Long> map); static Map<Sha256Hash, Long> deserializeMapOfHashesToLong(byte[] data); static byte[] serializeFederationOnlyBtcKeys(Federation federation); static Federation deserializeFederationOnlyBtcKeys(byte[] data, NetworkParameters networkParameters); static byte[] serializeFederation(Federation federation); static Federation deserializeFederation(byte[] data, NetworkParameters networkParameters); static byte[] serializeFederationMember(FederationMember federationMember); static byte[] serializePendingFederationOnlyBtcKeys(PendingFederation pendingFederation); static PendingFederation deserializePendingFederationOnlyBtcKeys(byte[] data); static byte[] serializePendingFederation(PendingFederation pendingFederation); static PendingFederation deserializePendingFederation(byte[] data); static byte[] serializeElection(ABICallElection election); static ABICallElection deserializeElection(byte[] data, AddressBasedAuthorizer authorizer); static byte[] serializeOneOffLockWhitelist(Pair<List<OneOffWhiteListEntry>, Integer> data); static byte[] serializeUnlimitedLockWhitelist(List<UnlimitedWhiteListEntry> entries); static Pair<HashMap<Address, OneOffWhiteListEntry>, Integer> deserializeOneOffLockWhitelistAndDisableBlockHeight(byte[] data, NetworkParameters parameters); static Map<Address, UnlimitedWhiteListEntry> deserializeUnlimitedLockWhitelistEntries(byte[] data, NetworkParameters parameters); static byte[] serializeCoin(Coin coin); @Nullable static Coin deserializeCoin(byte[] data); static byte[] serializeReleaseRequestQueue(ReleaseRequestQueue queue); static byte[] serializeReleaseRequestQueueWithTxHash(ReleaseRequestQueue queue); static List<ReleaseRequestQueue.Entry> deserializeReleaseRequestQueue(byte[] data, NetworkParameters networkParameters); static List<ReleaseRequestQueue.Entry> deserializeReleaseRequestQueue(byte[] data, NetworkParameters networkParameters, boolean hasTxHash); static byte[] serializeReleaseTransactionSet(ReleaseTransactionSet set); static byte[] serializeReleaseTransactionSetWithTxHash(ReleaseTransactionSet set); static ReleaseTransactionSet deserializeReleaseTransactionSet(byte[] data, NetworkParameters networkParameters); static ReleaseTransactionSet deserializeReleaseTransactionSet(byte[] data, NetworkParameters networkParameters, boolean hasTxHash); static byte[] serializeInteger(Integer value); static Integer deserializeInteger(byte[] data); static byte[] serializeLong(long value); static Optional<Long> deserializeOptionalLong(byte[] data); static CoinbaseInformation deserializeCoinbaseInformation(byte[] data); static byte[] serializeCoinbaseInformation(CoinbaseInformation coinbaseInformation); } | @Test public void deserializePendingFederationOnlyBtcKeys() throws Exception { byte[][] publicKeyBytes = Arrays.asList(100, 200, 300, 400, 500, 600).stream() .map(k -> BtcECKey.fromPrivate(BigInteger.valueOf(k))) .sorted(BtcECKey.PUBKEY_COMPARATOR) .map(k -> k.getPubKey()) .toArray(byte[][]::new); byte[][] rlpBytes = new byte[publicKeyBytes.length][]; for (int k = 0; k < publicKeyBytes.length; k++) { rlpBytes[k] = RLP.encodeElement(publicKeyBytes[k]); } byte[] data = RLP.encodeList(rlpBytes); PendingFederation deserializedPendingFederation = BridgeSerializationUtils.deserializePendingFederationOnlyBtcKeys(data); Assert.assertEquals(6, deserializedPendingFederation.getBtcPublicKeys().size()); for (int i = 0; i < 6; i++) { Assert.assertTrue(Arrays.equals(publicKeyBytes[i], deserializedPendingFederation.getBtcPublicKeys().get(i).getPubKey())); } } |
BridgeSerializationUtils { public static byte[] serializeElection(ABICallElection election) { byte[][] bytes = new byte[election.getVotes().size() * 2][]; int n = 0; Map<ABICallSpec, List<RskAddress>> votes = election.getVotes(); ABICallSpec[] specs = votes.keySet().toArray(new ABICallSpec[0]); Arrays.sort(specs, ABICallSpec.byBytesComparator); for (ABICallSpec spec : specs) { bytes[n++] = serializeABICallSpec(spec); bytes[n++] = serializeVoters(votes.get(spec)); } return RLP.encodeList(bytes); } private BridgeSerializationUtils(); static byte[] serializeMap(SortedMap<Keccak256, BtcTransaction> map); static SortedMap<Keccak256, BtcTransaction> deserializeMap(byte[] data, NetworkParameters networkParameters, boolean noInputsTxs); static byte[] serializeUTXOList(List<UTXO> list); static List<UTXO> deserializeUTXOList(byte[] data); static byte[] serializeSet(SortedSet<Sha256Hash> set); static SortedSet<Sha256Hash> deserializeSet(byte[] data); static byte[] serializeMapOfHashesToLong(Map<Sha256Hash, Long> map); static Map<Sha256Hash, Long> deserializeMapOfHashesToLong(byte[] data); static byte[] serializeFederationOnlyBtcKeys(Federation federation); static Federation deserializeFederationOnlyBtcKeys(byte[] data, NetworkParameters networkParameters); static byte[] serializeFederation(Federation federation); static Federation deserializeFederation(byte[] data, NetworkParameters networkParameters); static byte[] serializeFederationMember(FederationMember federationMember); static byte[] serializePendingFederationOnlyBtcKeys(PendingFederation pendingFederation); static PendingFederation deserializePendingFederationOnlyBtcKeys(byte[] data); static byte[] serializePendingFederation(PendingFederation pendingFederation); static PendingFederation deserializePendingFederation(byte[] data); static byte[] serializeElection(ABICallElection election); static ABICallElection deserializeElection(byte[] data, AddressBasedAuthorizer authorizer); static byte[] serializeOneOffLockWhitelist(Pair<List<OneOffWhiteListEntry>, Integer> data); static byte[] serializeUnlimitedLockWhitelist(List<UnlimitedWhiteListEntry> entries); static Pair<HashMap<Address, OneOffWhiteListEntry>, Integer> deserializeOneOffLockWhitelistAndDisableBlockHeight(byte[] data, NetworkParameters parameters); static Map<Address, UnlimitedWhiteListEntry> deserializeUnlimitedLockWhitelistEntries(byte[] data, NetworkParameters parameters); static byte[] serializeCoin(Coin coin); @Nullable static Coin deserializeCoin(byte[] data); static byte[] serializeReleaseRequestQueue(ReleaseRequestQueue queue); static byte[] serializeReleaseRequestQueueWithTxHash(ReleaseRequestQueue queue); static List<ReleaseRequestQueue.Entry> deserializeReleaseRequestQueue(byte[] data, NetworkParameters networkParameters); static List<ReleaseRequestQueue.Entry> deserializeReleaseRequestQueue(byte[] data, NetworkParameters networkParameters, boolean hasTxHash); static byte[] serializeReleaseTransactionSet(ReleaseTransactionSet set); static byte[] serializeReleaseTransactionSetWithTxHash(ReleaseTransactionSet set); static ReleaseTransactionSet deserializeReleaseTransactionSet(byte[] data, NetworkParameters networkParameters); static ReleaseTransactionSet deserializeReleaseTransactionSet(byte[] data, NetworkParameters networkParameters, boolean hasTxHash); static byte[] serializeInteger(Integer value); static Integer deserializeInteger(byte[] data); static byte[] serializeLong(long value); static Optional<Long> deserializeOptionalLong(byte[] data); static CoinbaseInformation deserializeCoinbaseInformation(byte[] data); static byte[] serializeCoinbaseInformation(CoinbaseInformation coinbaseInformation); } | @Test public void serializeElection() throws Exception { AddressBasedAuthorizer authorizer = getTestingAddressBasedAuthorizer(); Map<ABICallSpec, List<RskAddress>> sampleVotes = new HashMap<>(); sampleVotes.put( new ABICallSpec("one-function", new byte[][]{}), Arrays.asList(createAddress("8899"), createAddress("aabb")) ); sampleVotes.put( new ABICallSpec("another-function", new byte[][]{ Hex.decode("01"), Hex.decode("0203") }), Arrays.asList(createAddress("ccdd"), createAddress("eeff"), createAddress("0011")) ); sampleVotes.put( new ABICallSpec("yet-another-function", new byte[][]{ Hex.decode("0405") }), Arrays.asList(createAddress("fa"), createAddress("ca")) ); ABICallElection sample = new ABICallElection(authorizer, sampleVotes); byte[] result = BridgeSerializationUtils.serializeElection(sample); String hexResult = ByteUtil.toHexString(result); StringBuilder expectedBuilder = new StringBuilder(); expectedBuilder.append("f8d7d6"); expectedBuilder.append("90"); expectedBuilder.append(ByteUtil.toHexString("another-function".getBytes(StandardCharsets.UTF_8))); expectedBuilder.append("c4"); expectedBuilder.append("01"); expectedBuilder.append("820203"); expectedBuilder.append("f83f"); expectedBuilder.append("94" + createAddress("0011").toString()); expectedBuilder.append("94" + createAddress("ccdd").toString()); expectedBuilder.append("94" + createAddress("eeff").toString()); expectedBuilder.append("ce"); expectedBuilder.append("8c"); expectedBuilder.append(ByteUtil.toHexString("one-function".getBytes(StandardCharsets.UTF_8))); expectedBuilder.append("c0"); expectedBuilder.append("ea"); expectedBuilder.append("94" + createAddress("8899").toString()); expectedBuilder.append("94" + createAddress("aabb").toString()); expectedBuilder.append("d9"); expectedBuilder.append("94"); expectedBuilder.append(ByteUtil.toHexString("yet-another-function".getBytes(StandardCharsets.UTF_8))); expectedBuilder.append("c3"); expectedBuilder.append("820405"); expectedBuilder.append("ea"); expectedBuilder.append("94" + createAddress("ca").toString() + "94" + createAddress("fa").toString()); Assert.assertEquals(expectedBuilder.toString(), hexResult); } |
BridgeSerializationUtils { public static ABICallElection deserializeElection(byte[] data, AddressBasedAuthorizer authorizer) { if (data == null || data.length == 0) { return new ABICallElection(authorizer); } RLPList rlpList = (RLPList) RLP.decode2(data).get(0); if (rlpList.size() % 2 != 0) { throw new RuntimeException("deserializeElection: expected an even number of entries, but odd given"); } int numEntries = rlpList.size() / 2; Map<ABICallSpec, List<RskAddress>> votes = new HashMap<>(); for (int k = 0; k < numEntries; k++) { ABICallSpec spec = deserializeABICallSpec(rlpList.get(k * 2).getRLPData()); List<RskAddress> specVotes = deserializeVoters(rlpList.get(k * 2 + 1).getRLPData()); votes.put(spec, specVotes); } return new ABICallElection(authorizer, votes); } private BridgeSerializationUtils(); static byte[] serializeMap(SortedMap<Keccak256, BtcTransaction> map); static SortedMap<Keccak256, BtcTransaction> deserializeMap(byte[] data, NetworkParameters networkParameters, boolean noInputsTxs); static byte[] serializeUTXOList(List<UTXO> list); static List<UTXO> deserializeUTXOList(byte[] data); static byte[] serializeSet(SortedSet<Sha256Hash> set); static SortedSet<Sha256Hash> deserializeSet(byte[] data); static byte[] serializeMapOfHashesToLong(Map<Sha256Hash, Long> map); static Map<Sha256Hash, Long> deserializeMapOfHashesToLong(byte[] data); static byte[] serializeFederationOnlyBtcKeys(Federation federation); static Federation deserializeFederationOnlyBtcKeys(byte[] data, NetworkParameters networkParameters); static byte[] serializeFederation(Federation federation); static Federation deserializeFederation(byte[] data, NetworkParameters networkParameters); static byte[] serializeFederationMember(FederationMember federationMember); static byte[] serializePendingFederationOnlyBtcKeys(PendingFederation pendingFederation); static PendingFederation deserializePendingFederationOnlyBtcKeys(byte[] data); static byte[] serializePendingFederation(PendingFederation pendingFederation); static PendingFederation deserializePendingFederation(byte[] data); static byte[] serializeElection(ABICallElection election); static ABICallElection deserializeElection(byte[] data, AddressBasedAuthorizer authorizer); static byte[] serializeOneOffLockWhitelist(Pair<List<OneOffWhiteListEntry>, Integer> data); static byte[] serializeUnlimitedLockWhitelist(List<UnlimitedWhiteListEntry> entries); static Pair<HashMap<Address, OneOffWhiteListEntry>, Integer> deserializeOneOffLockWhitelistAndDisableBlockHeight(byte[] data, NetworkParameters parameters); static Map<Address, UnlimitedWhiteListEntry> deserializeUnlimitedLockWhitelistEntries(byte[] data, NetworkParameters parameters); static byte[] serializeCoin(Coin coin); @Nullable static Coin deserializeCoin(byte[] data); static byte[] serializeReleaseRequestQueue(ReleaseRequestQueue queue); static byte[] serializeReleaseRequestQueueWithTxHash(ReleaseRequestQueue queue); static List<ReleaseRequestQueue.Entry> deserializeReleaseRequestQueue(byte[] data, NetworkParameters networkParameters); static List<ReleaseRequestQueue.Entry> deserializeReleaseRequestQueue(byte[] data, NetworkParameters networkParameters, boolean hasTxHash); static byte[] serializeReleaseTransactionSet(ReleaseTransactionSet set); static byte[] serializeReleaseTransactionSetWithTxHash(ReleaseTransactionSet set); static ReleaseTransactionSet deserializeReleaseTransactionSet(byte[] data, NetworkParameters networkParameters); static ReleaseTransactionSet deserializeReleaseTransactionSet(byte[] data, NetworkParameters networkParameters, boolean hasTxHash); static byte[] serializeInteger(Integer value); static Integer deserializeInteger(byte[] data); static byte[] serializeLong(long value); static Optional<Long> deserializeOptionalLong(byte[] data); static CoinbaseInformation deserializeCoinbaseInformation(byte[] data); static byte[] serializeCoinbaseInformation(CoinbaseInformation coinbaseInformation); } | @Test public void deserializeElection_emptyOrNull() throws Exception { AddressBasedAuthorizer authorizer = getTestingAddressBasedAuthorizer(); ABICallElection election; election = BridgeSerializationUtils.deserializeElection(null, authorizer); Assert.assertEquals(0, election.getVotes().size()); election = BridgeSerializationUtils.deserializeElection(new byte[]{}, authorizer); Assert.assertEquals(0, election.getVotes().size()); }
@Test public void deserializeElection_unevenOuterList() throws Exception { AddressBasedAuthorizer mockedAuthorizer = mock(AddressBasedAuthorizer.class); byte[] rlpFirstElement = RLP.encodeElement(Hex.decode("010203")); byte[] data = RLP.encodeList(rlpFirstElement); try { BridgeSerializationUtils.deserializeElection(data, mockedAuthorizer); } catch (RuntimeException e) { Assert.assertTrue(e.getMessage().contains("expected an even number of entries, but odd given")); return; } Assert.fail(); }
@Test public void deserializeElection_invalidCallSpec() throws Exception { AddressBasedAuthorizer authorizer = getTestingAddressBasedAuthorizer(); byte[] rlpFirstSpec = RLP.encodeList(RLP.encode(Hex.decode("010203"))); byte[] rlpFirstVoters = RLP.encodeList(RLP.encodeElement(Hex.decode("03"))); byte[] data = RLP.encodeList(rlpFirstSpec, rlpFirstVoters); try { BridgeSerializationUtils.deserializeElection(data, authorizer); } catch (RuntimeException e) { Assert.assertTrue(e.getMessage().contains("Invalid serialized ABICallSpec")); return; } Assert.fail(); } |
Web3Impl implements Web3 { @Override public String web3_clientVersion() { String clientVersion = baseClientVersion + "/" + config.projectVersion() + "/" + System.getProperty("os.name") + "/Java1.8/" + config.projectVersionModifier() + "-" + buildInfo.getBuildHash(); if (logger.isDebugEnabled()) { logger.debug("web3_clientVersion(): {}", clientVersion); } return clientVersion; } protected Web3Impl(
Ethereum eth,
Blockchain blockchain,
BlockStore blockStore,
ReceiptStore receiptStore,
RskSystemProperties config,
MinerClient minerClient,
MinerServer minerServer,
PersonalModule personalModule,
EthModule ethModule,
EvmModule evmModule,
TxPoolModule txPoolModule,
MnrModule mnrModule,
DebugModule debugModule,
TraceModule traceModule,
RskModule rskModule,
ChannelManager channelManager,
PeerScoringManager peerScoringManager,
PeerServer peerServer,
BlockProcessor nodeBlockProcessor,
HashRateCalculator hashRateCalculator,
ConfigCapabilities configCapabilities,
BuildInfo buildInfo,
BlocksBloomStore blocksBloomStore,
Web3InformationRetriever web3InformationRetriever); @Override void start(); @Override void stop(); @Override String web3_clientVersion(); @Override String web3_sha3(String data); @Override String net_version(); @Override String net_peerCount(); @Override boolean net_listening(); @Override String rsk_protocolVersion(); @Override String eth_protocolVersion(); @Override Object eth_syncing(); @Override String eth_coinbase(); @Override boolean eth_mining(); @Override BigInteger eth_hashrate(); @Override BigInteger eth_netHashrate(); @Override String[] net_peerList(); @Override String eth_gasPrice(); @Override String eth_blockNumber(); @Override String eth_getBalance(String address, String block); @Override String eth_getBalance(String address); @Override String eth_getStorageAt(String address, String storageIdx, String blockId); @Override String eth_getTransactionCount(String address, String blockId); Block getBlockByJSonHash(String blockHash); @Override String eth_getBlockTransactionCountByHash(String blockHash); static Block getBlockByNumberOrStr(String bnOrId, Blockchain blockchain); @Override String eth_getBlockTransactionCountByNumber(String bnOrId); @Override String eth_getUncleCountByBlockHash(String blockHash); @Override String eth_getUncleCountByBlockNumber(String bnOrId); BlockInformationResult getBlockInformationResult(BlockInformation blockInformation); BlockResultDTO getBlockResult(Block b, boolean fullTx); BlockInformationResult[] eth_getBlocksByNumber(String number); @Override BlockResultDTO eth_getBlockByHash(String blockHash, Boolean fullTransactionObjects); @Override BlockResultDTO eth_getBlockByNumber(String bnOrId, Boolean fullTransactionObjects); @Override TransactionResultDTO eth_getTransactionByHash(String transactionHash); @Override TransactionResultDTO eth_getTransactionByBlockHashAndIndex(String blockHash, String index); @Override TransactionResultDTO eth_getTransactionByBlockNumberAndIndex(String bnOrId, String index); @Override TransactionReceiptDTO eth_getTransactionReceipt(String transactionHash); @Override BlockResultDTO eth_getUncleByBlockHashAndIndex(String blockHash, String uncleIdx); @Override BlockResultDTO eth_getUncleByBlockNumberAndIndex(String blockId, String uncleIdx); @Override String[] eth_getCompilers(); @Override Map<String, CompilationResultDTO> eth_compileLLL(String contract); @Override Map<String, CompilationResultDTO> eth_compileSerpent(String contract); @Override Map<String, CompilationResultDTO> eth_compileSolidity(String contract); @Override String eth_newFilter(FilterRequest fr); @Override String eth_newBlockFilter(); @Override String eth_newPendingTransactionFilter(); @Override boolean eth_uninstallFilter(String id); @Override Object[] eth_getFilterChanges(String id); @Override Object[] eth_getFilterLogs(String id); @Override Object[] eth_getLogs(FilterRequest fr); @Override Map<String, String> rpc_modules(); @Override void db_putString(); @Override void db_getString(); @Override boolean eth_submitWork(String nonce, String header, String mince); @Override boolean eth_submitHashrate(String hashrate, String id); @Override void db_putHex(); @Override void db_getHex(); @Override String personal_newAccountWithSeed(String seed); @Override String personal_newAccount(String passphrase); @Override String personal_importRawKey(String key, String passphrase); @Override String personal_dumpRawKey(String address); @Override String[] personal_listAccounts(); @Override String personal_sendTransaction(CallArguments args, String passphrase); @Override boolean personal_unlockAccount(String address, String passphrase, String duration); @Override boolean personal_lockAccount(String address); @Override EthModule getEthModule(); @Override EvmModule getEvmModule(); @Override TxPoolModule getTxPoolModule(); @Override MnrModule getMnrModule(); @Override DebugModule getDebugModule(); @Override TraceModule getTraceModule(); @Override RskModule getRskModule(); @Override void sco_banAddress(String address); @Override void sco_unbanAddress(String address); @Override PeerScoringInformation[] sco_peerList(); @Override String[] sco_bannedAddresses(); public Ethereum eth; } | @Test public void web3_clientVersion() throws Exception { Web3 web3 = createWeb3(); String clientVersion = web3.web3_clientVersion(); assertTrue("client version is not including rsk!", clientVersion.toLowerCase().contains("rsk")); } |
TransportAsync implements Transport { public synchronized void handleConnected() { if (!this.state) { this.state = true; fireEvent(true, this.listener); } } TransportAsync(final Executor executor); synchronized void handleConnected(); synchronized void handleDisconnected(); @Override void state(final Consumer<Boolean> listener); } | @Test public void test1() throws InterruptedException { final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); try { final TransportAsync transport = new TransportAsync(executor); final Instant start = Instant.now(); executor.schedule(() -> { transport.handleConnected(); }, 100, TimeUnit.MILLISECONDS); Transport.waitForConnection(transport); Duration duration = Duration.between(start, Instant.now()); System.out.println(duration); Assert.assertTrue(duration.compareTo(Duration.ofMillis(100)) > 0); } finally { executor.shutdown(); } } |
Topic { public Stream<String> stream() { return segments.stream(); } private Topic(final List<String> segments); List<String> getSegments(); Stream<String> stream(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static Topic split(String path); static Topic of(final List<String> segments); static Topic of(final String first, final String... strings); static String ensureNotSpecial(final String segment); } | @Test public void testStream() { final String result = Topic.split("foo/bar").stream().collect(Collectors.joining()); assertEquals("foobar", result); } |
Payload { public static Payload of(final String key, final Object value) { Objects.requireNonNull(key); return new Payload(now(), singletonMap(key, value), false); } private Payload(final Instant timestamp, final Map<String, ?> values, final boolean cloneValues); Instant getTimestamp(); Map<String, ?> getValues(); @Override String toString(); static Payload of(final String key, final Object value); static Payload of(final Map<String, ?> values); static Payload of(final Instant timestamp, final String key, final Object value); static Payload of(final Instant timestamp, final Map<String, ?> values); } | @Test(expected = NullPointerException.class) public void testNull1() { Payload.of((String) null, null); }
@Test(expected = NullPointerException.class) public void testNull2() { Payload.of(null); }
@Test(expected = NullPointerException.class) public void testNull3() { Payload.of(null, null, null); }
@Test(expected = NullPointerException.class) public void testNull4() { Payload.of((Instant) null, null); } |
Errors { public static ErrorHandler<RuntimeException> ignore() { return IGNORE; } private Errors(); static ErrorHandler<RuntimeException> ignore(); static ErrorHandler<RuntimeException> handle(final BiConsumer<Throwable, Optional<Payload>> handler); static void ignore(final Throwable e, final Optional<Payload> payload); } | @Test public void test1() { Errors.ignore().handleError(new Exception(), Optional.empty()); } |
Errors { public static ErrorHandler<RuntimeException> handle(final BiConsumer<Throwable, Optional<Payload>> handler) { return new ErrorHandler<RuntimeException>() { @Override public void handleError(final Throwable e, final Optional<Payload> payload) throws RuntimeException { handler.accept(e, payload); } }; } private Errors(); static ErrorHandler<RuntimeException> ignore(); static ErrorHandler<RuntimeException> handle(final BiConsumer<Throwable, Optional<Payload>> handler); static void ignore(final Throwable e, final Optional<Payload> payload); } | @Test public void test2() { Errors.handle((error, payload) -> { }).handleError(new Exception(), Optional.empty()); }
@Test public void test3() { Errors.handle(Errors::ignore).handleError(new Exception(), Optional.empty()); } |
JksServerConfigurator implements HttpServerConfigurator { private int getPort(ServerConfiguration configuration) { return configuration.getInteger(ConfigKies.HTTPS_PORT, ConfigKies.DEFAULT_HTTPS_PORT); } @Override void configureHttpServer(VertxContext context, HttpServerOptions options); } | @Test public void givenSslEnabledInConfiguration_whenHttpsPortIsMissingInConfiguration_thenShouldUseDefaultHttpsPort() throws Exception { configuration.put(SSL_CONFIGURATION_KEY, TRUE); configuration.remove(HTTPS_PORT); configureServer(); assertThat(options.getPort()).isEqualTo(DEFAULT_HTTPS_PORT); }
@Test public void givenSslEnabledInConfiguration_whenHttpsPortIsSetInConfiguration_thenShouldUsePortFromConfiguration() throws Exception { configuration.put(SSL_CONFIGURATION_KEY, TRUE); configuration.put(HTTPS_PORT, DEFAULT_TEST_SSL_PORT); configureServer(); assertThat(options.getPort()).isEqualTo(DEFAULT_TEST_SSL_PORT); } |
HttpServiceDiscovery { public void getWebClient(Function<Record, Boolean> filter, Handler<AsyncResult<WebClient>> handler) { HttpEndpoint.getWebClient(serviceDiscovery, filter, handler); } HttpServiceDiscovery(ServiceDiscovery serviceDiscovery); void publish(HttpEndpointConfiguration configuration, Handler<AsyncResult<Record>> handler); void getHttpClient(Function<Record, Boolean> filter, Handler<AsyncResult<HttpClient>> handler); void getHttpClient(Function<Record, Boolean> filter, JsonObject configuration, Handler<AsyncResult<HttpClient>> handler); void getHttpClient(JsonObject jsonFilter, Handler<AsyncResult<HttpClient>> handler); void getHttpClient(JsonObject jsonFilter, JsonObject configuration, Handler<AsyncResult<HttpClient>> handler); void getWebClient(Function<Record, Boolean> filter, Handler<AsyncResult<WebClient>> handler); void getWebClient(Function<Record, Boolean> filter, JsonObject configuration, Handler<AsyncResult<WebClient>> handler); void getWebClient(JsonObject jsonFilter, Handler<AsyncResult<WebClient>> handler); void getWebClient(JsonObject jsonFilter, JsonObject configuration, Handler<AsyncResult<WebClient>> handler); } | @Test public void givenServiceDiscovery_whenPublishHttpServiceAndAskingForItsWebClientByJsonWithConfiguration_thenShouldGetTheClient(TestContext context) throws Exception { publishHttpEndpoint(httpEndpointConfiguration.metadata(metadata)); getWebClient(jsonFilter, metadata, context.asyncAssertSuccess(Assert::assertNotNull)); }
@Test public void givenServiceDiscovery_whenPublishHttpServiceAndAskingForItsWebClientByFilter_thenShouldGetTheClient(TestContext context) throws Exception { publishHttpEndpoint(httpEndpointConfiguration); getWebClient(record -> record.getName().equals(SERVICE_NAME), context.asyncAssertSuccess(Assert::assertNotNull)); }
@Test public void givenServiceDiscovery_whenPublishHttpServiceAndAskingForItsWebClientByFilterWithConfiguration_thenShouldGetTheClient(TestContext context) throws Exception { publishHttpEndpoint(httpEndpointConfiguration.metadata(metadata)); getWebClient(record -> record.getName().equals(SERVICE_NAME), metadata, context.asyncAssertSuccess(Assert::assertNotNull)); }
@Test public void givenServiceDiscovery_whenPublishHttpServiceAndAskingForItsWebClientByJson_thenShouldGetTheClient(TestContext context) throws Exception { publishHttpEndpoint(httpEndpointConfiguration); getWebClient(jsonFilter, context.asyncAssertSuccess(Assert::assertNotNull)); } |
MessageSourceServiceDiscovery { public <T> void getConsumer(Function<Record, Boolean> filter, Handler<AsyncResult<MessageConsumer<T>>> handler) { MessageSource.getConsumer(serviceDiscovery, filter, handler); } MessageSourceServiceDiscovery(ServiceDiscovery serviceDiscovery); void publish(MessageSourceConfiguration configuration, Handler<AsyncResult<Record>> handler); void getConsumer(Function<Record, Boolean> filter, Handler<AsyncResult<MessageConsumer<T>>> handler); void getConsumer(JsonObject jsonFilter, Handler<AsyncResult<MessageConsumer<T>>> handler); } | @Test public void givenServiceDiscovery_whenPublishingMessageSourceAndAskingForItsConsumer_thenShouldGetTheConsumer(TestContext context) throws Exception { publishMessageSourceService(messageSourceConfiguration); vertxServiceDiscovery.messageSource().getConsumer(record -> record.getName().equals(SERVICE_NAME), context.asyncAssertSuccess()); }
@Test public void givenServiceDiscovery_whenPublishingMessageSourceAndAskingForItsConsumerByJson_thenShouldGetTheConsumer(TestContext context) throws Exception { publishMessageSourceService(messageSourceConfiguration); vertxServiceDiscovery.messageSource().getConsumer(new JsonObject().put("name", SERVICE_NAME), context.asyncAssertSuccess()); } |
RedisServiceDiscovery { public void getClient(Function<Record, Boolean> filter, Handler<AsyncResult<RedisClient>> handler) { RedisDataSource.getRedisClient(serviceDiscovery, filter, handler); } RedisServiceDiscovery(ServiceDiscovery serviceDiscovery); void publish(DataSourceServiceConfiguration configuration, Handler<AsyncResult<Record>> handler); void getClient(Function<Record, Boolean> filter, Handler<AsyncResult<RedisClient>> handler); void getClient(Function<Record, Boolean> filter, JsonObject configuration, Handler<AsyncResult<RedisClient>> handler); void getClient(JsonObject jsonFilter, Handler<AsyncResult<RedisClient>> handler); void getClient(JsonObject jsonFilter, JsonObject configuration, Handler<AsyncResult<RedisClient>> handler); } | @Test public void givenServiceDiscovery_whenPublishingRedisDataSourceAndAskingForItsClient_thenShouldGetTheClient(TestContext context) throws Exception { publishRedisDataSourceService(dataSourceConfiguration); vertxServiceDiscovery.redis().getClient(filter(), context.asyncAssertSuccess()); }
@Test public void givenServiceDiscovery_whenPublishingRedisDataAndAskingForItsClientWithConfiguration_thenShouldGetTheClient(TestContext context) throws Exception { publishRedisDataSourceService(dataSourceConfiguration.metadata(metadata)); vertxServiceDiscovery.redis().getClient(filter(), metadata, context.asyncAssertSuccess()); }
@Test public void givenServiceDiscovery_whenPublishingRedisDataAndAskingForItsClientByJson_thenShouldGetTheClient(TestContext context) throws Exception { publishRedisDataSourceService(dataSourceConfiguration); vertxServiceDiscovery.redis().getClient(jsonFilter, context.asyncAssertSuccess()); }
@Test public void givenServiceDiscovery_whenPublishingRedisDataAndAskingForItsClientByJsonWithConfiguration_thenShouldGetTheClient(TestContext context) throws Exception { publishRedisDataSourceService(dataSourceConfiguration.metadata(metadata)); vertxServiceDiscovery.redis().getClient(jsonFilter, metadata, context.asyncAssertSuccess()); } |
EventBusServiceDiscovery { public <T> void getProxy(Class<T> serviceClass, Handler<AsyncResult<T>> handler) { EventBusService.getProxy(serviceDiscovery, serviceClass, handler); } EventBusServiceDiscovery(ServiceDiscovery serviceDiscovery); void publish(EventBusServiceConfiguration configuration, Handler<AsyncResult<Record>> handler); void getProxy(Class<T> serviceClass, Handler<AsyncResult<T>> handler); void getServiceProxy(Function<Record, Boolean> filter, Class<T> serviceClass, Handler<AsyncResult<T>> handler); void getServiceProxy(JsonObject jsonFilter, Class<T> serviceClass, Handler<AsyncResult<T>> handler); } | @Test public void givenServiceDiscovery_whenPublishEventBusServiceAndAskingForItsProxy_thenShouldGetTheService(TestContext context) throws Exception { publishEventBusService(eventBusConfiguration); vertxServiceDiscovery.eventBus().getProxy(TestService.class, context.asyncAssertSuccess(Assert::assertNotNull)); } |
EventBusServiceDiscovery { public <T> void getServiceProxy(Function<Record, Boolean> filter, Class<T> serviceClass, Handler<AsyncResult<T>> handler) { EventBusService.getServiceProxy(serviceDiscovery, filter, serviceClass, handler); } EventBusServiceDiscovery(ServiceDiscovery serviceDiscovery); void publish(EventBusServiceConfiguration configuration, Handler<AsyncResult<Record>> handler); void getProxy(Class<T> serviceClass, Handler<AsyncResult<T>> handler); void getServiceProxy(Function<Record, Boolean> filter, Class<T> serviceClass, Handler<AsyncResult<T>> handler); void getServiceProxy(JsonObject jsonFilter, Class<T> serviceClass, Handler<AsyncResult<T>> handler); } | @Test public void givenServiceDiscovery_whenPublishEventBusServiceAndAskingForItsServiceProxy_thenShouldGetTheService(TestContext context) throws Exception { publishEventBusService(eventBusConfiguration); vertxServiceDiscovery.eventBus().getServiceProxy(record -> record.getName().equals(SERVICE_NAME), TestService.class, context.asyncAssertSuccess(Assert::assertNotNull)); }
@Test public void givenServiceDiscovery_whenPublishEventBusServiceAndAskingForItsServiceProxyByJson_thenShouldGetTheService(TestContext context) throws Exception { publishEventBusService(eventBusConfiguration); vertxServiceDiscovery.eventBus().getServiceProxy(jsonFilter, TestService.class, context.asyncAssertSuccess(Assert::assertNotNull)); } |
JDBCServiceDiscovery { public void getClient(Function<Record, Boolean> filter, Handler<AsyncResult<JDBCClient>> handler) { JDBCDataSource.getJDBCClient(serviceDiscovery, filter, handler); } JDBCServiceDiscovery(ServiceDiscovery serviceDiscovery); void publish(DataSourceServiceConfiguration configuration, Handler<AsyncResult<Record>> handler); void getClient(Function<Record, Boolean> filter, Handler<AsyncResult<JDBCClient>> handler); void getClient(Function<Record, Boolean> filter, JsonObject configuration, Handler<AsyncResult<JDBCClient>> handler); void getClient(JsonObject jsonFilter, Handler<AsyncResult<JDBCClient>> handler); void getClient(JsonObject jsonFilter, JsonObject configuration, Handler<AsyncResult<JDBCClient>> handler); } | @Test public void givenServiceDiscovery_whenPublishingMessageSourceAndAskingForItsClient_thenShouldGetTheClient(TestContext context) throws Exception { publishJDBCDataSourceService(dataSourceConfiguration); vertxServiceDiscovery.jdbc().getClient(filter(), context.asyncAssertSuccess()); }
@Test public void givenServiceDiscovery_whenPublishingMessageSourceAndAskingForItsClientWithConfiguration_thenShouldGetTheClient(TestContext context) throws Exception { publishJDBCDataSourceService(dataSourceConfiguration.metadata(metadata)); vertxServiceDiscovery.jdbc().getClient(filter(), metadata, context.asyncAssertSuccess()); }
@Test public void givenServiceDiscovery_whenPublishingMessageSourceAndAskingForItsClientByJson_thenShouldGetTheClient(TestContext context) throws Exception { publishJDBCDataSourceService(dataSourceConfiguration); vertxServiceDiscovery.jdbc().getClient(jsonFilter, context.asyncAssertSuccess()); }
@Test public void givenServiceDiscovery_whenPublishingMessageSourceAndAskingForItsClientByJsonWithConfiguration_thenShouldGetTheClient(TestContext context) throws Exception { publishJDBCDataSourceService(dataSourceConfiguration.metadata(metadata)); vertxServiceDiscovery.jdbc().getClient(jsonFilter, metadata, context.asyncAssertSuccess()); } |
MongoServiceDiscovery { public void getClient(Function<Record, Boolean> filter, Handler<AsyncResult<MongoClient>> handler) { MongoDataSource.getMongoClient(serviceDiscovery, filter, handler); } MongoServiceDiscovery(ServiceDiscovery serviceDiscovery); void publish(DataSourceServiceConfiguration configuration, Handler<AsyncResult<Record>> handler); void getClient(Function<Record, Boolean> filter, Handler<AsyncResult<MongoClient>> handler); void getClient(JsonObject jsonFilter, Handler<AsyncResult<MongoClient>> handler); void getClient(JsonObject jsonFilter, JsonObject configuration, Handler<AsyncResult<MongoClient>> handler); } | @Test public void givenServiceDiscovery_whenPublishingRedisDataSourceAndAskingForItsClient_thenShouldGetTheClient(TestContext context) throws Exception { publishMongoDataSourceService(dataSourceConfiguration); vertxServiceDiscovery.mongo().getClient(filter(), context.asyncAssertSuccess()); }
@Test public void givenServiceDiscovery_whenPublishingRedisDataAndAskingForItsClientByJson_thenShouldGetTheClient(TestContext context) throws Exception { publishMongoDataSourceService(dataSourceConfiguration); vertxServiceDiscovery.mongo().getClient(jsonFilter, context.asyncAssertSuccess()); }
@Test public void givenServiceDiscovery_whenPublishingRedisDataAndAskingForItsClientByJsonWithConfiguration_thenShouldGetTheClient(TestContext context) throws Exception { publishMongoDataSourceService(dataSourceConfiguration.metadata(metadata)); vertxServiceDiscovery.mongo().getClient(jsonFilter, metadata, context.asyncAssertSuccess()); } |
VertxServiceDiscovery { public void publishRecord(Record record, Handler<AsyncResult<Record>> handler) { serviceDiscovery.publish(record, handler); } VertxServiceDiscovery(Vertx vertx); ServiceDiscovery serviceDiscovery(); HttpServiceDiscovery http(); EventBusServiceDiscovery eventBus(); MessageSourceServiceDiscovery messageSource(); JDBCServiceDiscovery jdbc(); RedisServiceDiscovery redis(); MongoServiceDiscovery mongo(); void unpublish(Record record, Handler<AsyncResult<Void>> handler); void publishRecord(Record record, Handler<AsyncResult<Record>> handler); void lookup(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupByJson(JsonObject jsonFilter, Handler<AsyncResult<Record>> handler); void lookupAll(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllByJson(JsonObject jsonFilter, Handler<AsyncResult<List<Record>>> handler); ServiceReference lookupForAReference(Record record); ServiceReference lookupForAReferenceWithConfiguration(Record record, JsonObject configuration); void releaseServiceObject(Object object); } | @Test public void givenServiceDiscovery_whenPublishingRecord_thenTheRecordShouldBePublished(TestContext context) throws Exception { vertxServiceDiscovery.publishRecord(record, context.asyncAssertSuccess()); } |
VertxServiceDiscovery { public void lookup(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler) { lookup(filter, false, handler); } VertxServiceDiscovery(Vertx vertx); ServiceDiscovery serviceDiscovery(); HttpServiceDiscovery http(); EventBusServiceDiscovery eventBus(); MessageSourceServiceDiscovery messageSource(); JDBCServiceDiscovery jdbc(); RedisServiceDiscovery redis(); MongoServiceDiscovery mongo(); void unpublish(Record record, Handler<AsyncResult<Void>> handler); void publishRecord(Record record, Handler<AsyncResult<Record>> handler); void lookup(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupByJson(JsonObject jsonFilter, Handler<AsyncResult<Record>> handler); void lookupAll(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllByJson(JsonObject jsonFilter, Handler<AsyncResult<List<Record>>> handler); ServiceReference lookupForAReference(Record record); ServiceReference lookupForAReferenceWithConfiguration(Record record, JsonObject configuration); void releaseServiceObject(Object object); } | @Test(expected = InvalidFilterException.class) public void givenServiceDiscovery_whenLookupForARecordWithNullFilter_thenShouldThrowException() throws Exception { lookup(null, ar -> { }); }
@Test public void givenServiceDiscovery_whenLookupForARecordUnmatchingPredicate_thenShouldGetNullRecord(TestContext context) throws Exception { publishTestRecord(record); lookup(r -> r.getName().equals(NOT_EXISTED_NAME), context.asyncAssertSuccess(context::assertNull)); }
@Test public void givenServiceDiscovery_whenLookupForARecordMatchingPredicate_thenShouldGetTheRecord(TestContext context) throws Exception { publishTestRecord(record); lookup(r -> r.getName().equals(SERVICE_NAME), context.asyncAssertSuccess(record -> { context.assertEquals(SERVICE_NAME, record.getName()); })); } |
JksServerConfigurator implements HttpServerConfigurator { private String getPath(ServerConfiguration configuration) { return configuration.getString(ConfigKies.SSL_JKS_PATH); } @Override void configureHttpServer(VertxContext context, HttpServerOptions options); } | @Test public void givenSslEnabledInConfigurationWithJksPathAndPassword_whenConfiguringServer_thenHttpOptionSslShouldBeEnabledAndConfiguredWithThePathAndPassword() throws Exception { configuration.put(SSL_CONFIGURATION_KEY, TRUE); configureServer(); assertThat(options.isSsl()).isTrue(); assertThat(options.getKeyStoreOptions() instanceof JksOptions).isTrue(); assertThat(options.getKeyStoreOptions().getPath()).isEqualTo(TEST_JKS_PATH); assertThat(options.getKeyStoreOptions().getPassword()).isEqualTo(TEST_JKS_SECRET); } |
VertxServiceDiscovery { public void lookupIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler) { lookup(filter, true, handler); } VertxServiceDiscovery(Vertx vertx); ServiceDiscovery serviceDiscovery(); HttpServiceDiscovery http(); EventBusServiceDiscovery eventBus(); MessageSourceServiceDiscovery messageSource(); JDBCServiceDiscovery jdbc(); RedisServiceDiscovery redis(); MongoServiceDiscovery mongo(); void unpublish(Record record, Handler<AsyncResult<Void>> handler); void publishRecord(Record record, Handler<AsyncResult<Record>> handler); void lookup(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupByJson(JsonObject jsonFilter, Handler<AsyncResult<Record>> handler); void lookupAll(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllByJson(JsonObject jsonFilter, Handler<AsyncResult<List<Record>>> handler); ServiceReference lookupForAReference(Record record); ServiceReference lookupForAReferenceWithConfiguration(Record record, JsonObject configuration); void releaseServiceObject(Object object); } | @Test(expected = InvalidFilterException.class) public void givenServiceDiscovery_whenLookupForARecordIncludingOutOfServicePassingNullFilter_thenShouldThrowException(TestContext context) throws Exception { lookupIncludeOutOfService(null, ar -> { }); }
@Test public void givenServiceDiscovery_whenLookupForARecordIncludingOutOfService_thenShouldGetTheRecord(TestContext context) throws Exception { publishTestRecord(record.setStatus(Status.OUT_OF_SERVICE)); lookupIncludeOutOfService(r -> r.getName().equals(SERVICE_NAME), context.asyncAssertSuccess(record -> { context.assertEquals(Status.OUT_OF_SERVICE, record.getStatus()); })); } |
VertxServiceDiscovery { public void lookupByJson(JsonObject jsonFilter, Handler<AsyncResult<Record>> handler) { serviceDiscovery.getRecord(jsonFilter, handler); } VertxServiceDiscovery(Vertx vertx); ServiceDiscovery serviceDiscovery(); HttpServiceDiscovery http(); EventBusServiceDiscovery eventBus(); MessageSourceServiceDiscovery messageSource(); JDBCServiceDiscovery jdbc(); RedisServiceDiscovery redis(); MongoServiceDiscovery mongo(); void unpublish(Record record, Handler<AsyncResult<Void>> handler); void publishRecord(Record record, Handler<AsyncResult<Record>> handler); void lookup(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupByJson(JsonObject jsonFilter, Handler<AsyncResult<Record>> handler); void lookupAll(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllByJson(JsonObject jsonFilter, Handler<AsyncResult<List<Record>>> handler); ServiceReference lookupForAReference(Record record); ServiceReference lookupForAReferenceWithConfiguration(Record record, JsonObject configuration); void releaseServiceObject(Object object); } | @Test public void givenServiceDiscovery_whenLookupByJsonForARecordPassingNull_thenShouldGetTheRecord(TestContext context) throws Exception { publishTestRecord(record); lookupByJson(null, context.asyncAssertSuccess(record -> { context.assertEquals(SERVICE_NAME, record.getName()); })); }
@Test public void givenServiceDiscovery_whenLookupByJsonForARecordWithAName_thenShouldGetARecordWithThatName(TestContext context) throws Exception { publishTestRecord(record); lookupByJson(jsonFilter, context.asyncAssertSuccess(record -> { context.assertEquals(SERVICE_NAME, record.getName()); })); } |
VertxServiceDiscovery { public void lookupAll(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler) { lookupAll(filter, false, handler); } VertxServiceDiscovery(Vertx vertx); ServiceDiscovery serviceDiscovery(); HttpServiceDiscovery http(); EventBusServiceDiscovery eventBus(); MessageSourceServiceDiscovery messageSource(); JDBCServiceDiscovery jdbc(); RedisServiceDiscovery redis(); MongoServiceDiscovery mongo(); void unpublish(Record record, Handler<AsyncResult<Void>> handler); void publishRecord(Record record, Handler<AsyncResult<Record>> handler); void lookup(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupByJson(JsonObject jsonFilter, Handler<AsyncResult<Record>> handler); void lookupAll(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllByJson(JsonObject jsonFilter, Handler<AsyncResult<List<Record>>> handler); ServiceReference lookupForAReference(Record record); ServiceReference lookupForAReferenceWithConfiguration(Record record, JsonObject configuration); void releaseServiceObject(Object object); } | @Test(expected = InvalidFilterException.class) public void givenServiceDiscovery_whenLookupForAllRecordsPassingNullFilter_thenShouldThrowException() throws Exception { lookupAll(null, ar -> { }); }
@Test public void givenServiceDiscovery_whenLookupForAllRecordsWithUnmatchingPredicate_thenShouldNotGetAnyRecord(TestContext context) throws Exception { publishTestRecord(record); publishTestRecord(otherRecord); lookupAll(record -> record.getName().equals(NOT_EXISTED_NAME), context.asyncAssertSuccess(records -> { context.assertTrue(records.isEmpty()); })); }
@Test public void givenServiceDiscovery_whenLookupForAllRecordsWithMatchingPredicate_thenShouldGetAllRecordsMatching(TestContext context) throws Exception { publishTestRecord(record); publishTestRecord(otherRecord); lookupAll(record -> record.getName().contains(SERVICE_NAME), context.asyncAssertSuccess(records -> { context.assertEquals(2, records.size()); })); } |
VertxServiceDiscovery { public void lookupAllIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler) { lookupAll(filter, true, handler); } VertxServiceDiscovery(Vertx vertx); ServiceDiscovery serviceDiscovery(); HttpServiceDiscovery http(); EventBusServiceDiscovery eventBus(); MessageSourceServiceDiscovery messageSource(); JDBCServiceDiscovery jdbc(); RedisServiceDiscovery redis(); MongoServiceDiscovery mongo(); void unpublish(Record record, Handler<AsyncResult<Void>> handler); void publishRecord(Record record, Handler<AsyncResult<Record>> handler); void lookup(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupByJson(JsonObject jsonFilter, Handler<AsyncResult<Record>> handler); void lookupAll(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllByJson(JsonObject jsonFilter, Handler<AsyncResult<List<Record>>> handler); ServiceReference lookupForAReference(Record record); ServiceReference lookupForAReferenceWithConfiguration(Record record, JsonObject configuration); void releaseServiceObject(Object object); } | @Test(expected = InvalidFilterException.class) public void givenServiceDiscovery_whenLookupForAllRecordsIncludingOutOfServicePassingNullFilter_thenShouldThrowException(TestContext context) throws Exception { lookupAllIncludeOutOfService(null, ar -> { }); }
@Test public void givenServiceDiscovery_whenLookupForAllRecordsIncludingOutOfService_thenShouldGetAllRecordsIncludingOutOfService(TestContext context) throws Exception { publishTestRecord(record.setStatus(Status.OUT_OF_SERVICE)); publishTestRecord(otherRecord); lookupAllIncludeOutOfService(record -> record.getName().contains(SERVICE_NAME), context.asyncAssertSuccess(records -> { context.assertEquals(2, records.size()); })); } |
HttpServiceDiscovery { public void getHttpClient(Function<Record, Boolean> filter, Handler<AsyncResult<HttpClient>> handler) { HttpEndpoint.getClient(serviceDiscovery, filter, handler); } HttpServiceDiscovery(ServiceDiscovery serviceDiscovery); void publish(HttpEndpointConfiguration configuration, Handler<AsyncResult<Record>> handler); void getHttpClient(Function<Record, Boolean> filter, Handler<AsyncResult<HttpClient>> handler); void getHttpClient(Function<Record, Boolean> filter, JsonObject configuration, Handler<AsyncResult<HttpClient>> handler); void getHttpClient(JsonObject jsonFilter, Handler<AsyncResult<HttpClient>> handler); void getHttpClient(JsonObject jsonFilter, JsonObject configuration, Handler<AsyncResult<HttpClient>> handler); void getWebClient(Function<Record, Boolean> filter, Handler<AsyncResult<WebClient>> handler); void getWebClient(Function<Record, Boolean> filter, JsonObject configuration, Handler<AsyncResult<WebClient>> handler); void getWebClient(JsonObject jsonFilter, Handler<AsyncResult<WebClient>> handler); void getWebClient(JsonObject jsonFilter, JsonObject configuration, Handler<AsyncResult<WebClient>> handler); } | @Test public void givenServiceDiscovery_whenPublishHttpServiceAndAskingForItsHttpClientByFilter_thenShouldGetTheClient(TestContext context) throws Exception { publishHttpEndpoint(httpEndpointConfiguration); getHttpClient(record -> record.getName().equals(SERVICE_NAME), context.asyncAssertSuccess(Assert::assertNotNull)); }
@Test public void givenServiceDiscovery_whenPublishHttpServiceAndAskingForItsHttpClientByFilterWithConfiguration_thenShouldGetTheClient(TestContext context) throws Exception { publishHttpEndpoint(httpEndpointConfiguration.metadata(metadata)); getHttpClient(record -> record.getName().equals(SERVICE_NAME), metadata, context.asyncAssertSuccess(Assert::assertNotNull)); }
@Test public void givenServiceDiscovery_whenPublishHttpServiceAndAskingForItsHttpClientByJson_thenShouldGetTheClient(TestContext context) throws Exception { publishHttpEndpoint(httpEndpointConfiguration); getHttpClient(jsonFilter, context.asyncAssertSuccess(Assert::assertNotNull)); }
@Test public void givenServiceDiscovery_whenPublishHttpServiceAndAskingForItsHttpClientByJsonWithConfiguration_thenShouldGetTheClient(TestContext context) throws Exception { publishHttpEndpoint(httpEndpointConfiguration.metadata(metadata)); getHttpClient(jsonFilter, metadata, context.asyncAssertSuccess(Assert::assertNotNull)); } |
VertxServiceDiscovery { public void lookupAllByJson(JsonObject jsonFilter, Handler<AsyncResult<List<Record>>> handler) { serviceDiscovery.getRecords(jsonFilter, handler); } VertxServiceDiscovery(Vertx vertx); ServiceDiscovery serviceDiscovery(); HttpServiceDiscovery http(); EventBusServiceDiscovery eventBus(); MessageSourceServiceDiscovery messageSource(); JDBCServiceDiscovery jdbc(); RedisServiceDiscovery redis(); MongoServiceDiscovery mongo(); void unpublish(Record record, Handler<AsyncResult<Void>> handler); void publishRecord(Record record, Handler<AsyncResult<Record>> handler); void lookup(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupByJson(JsonObject jsonFilter, Handler<AsyncResult<Record>> handler); void lookupAll(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllByJson(JsonObject jsonFilter, Handler<AsyncResult<List<Record>>> handler); ServiceReference lookupForAReference(Record record); ServiceReference lookupForAReferenceWithConfiguration(Record record, JsonObject configuration); void releaseServiceObject(Object object); } | @Test public void givenServiceDiscovery_whenLookupForAllRecordsByJsonPassingNull_thenShouldGetAllRecords(TestContext context) throws Exception { publishTestRecord(record); publishTestRecord(otherRecord); lookupAllByJson(null, context.asyncAssertSuccess(records -> { context.assertEquals(2, records.size()); })); }
@Test public void givenServiceDiscovery_whenLookupForAllRecordsWithNameByJson_thenShouldGetAllRecordsMatching(TestContext context) throws Exception { publishTestRecord(record.setMetadata(metadata)); publishTestRecord(otherRecord.setMetadata(metadata)); lookupAllByJson(metadata, context.asyncAssertSuccess(records -> { context.assertEquals(2, records.size()); })); } |
VertxServiceDiscovery { public ServiceReference lookupForAReference(Record record) { return serviceDiscovery.getReference(record); } VertxServiceDiscovery(Vertx vertx); ServiceDiscovery serviceDiscovery(); HttpServiceDiscovery http(); EventBusServiceDiscovery eventBus(); MessageSourceServiceDiscovery messageSource(); JDBCServiceDiscovery jdbc(); RedisServiceDiscovery redis(); MongoServiceDiscovery mongo(); void unpublish(Record record, Handler<AsyncResult<Void>> handler); void publishRecord(Record record, Handler<AsyncResult<Record>> handler); void lookup(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupByJson(JsonObject jsonFilter, Handler<AsyncResult<Record>> handler); void lookupAll(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllByJson(JsonObject jsonFilter, Handler<AsyncResult<List<Record>>> handler); ServiceReference lookupForAReference(Record record); ServiceReference lookupForAReferenceWithConfiguration(Record record, JsonObject configuration); void releaseServiceObject(Object object); } | @Test public void givenServiceDiscovery_whenPublishServiceAndLookupForItsServiceReference_thenShouldGetTheReference(TestContext context) throws Exception { publishTestRecord(record, context.asyncAssertSuccess(record -> { assertNotNull(vertxServiceDiscovery.lookupForAReference(record)); })); } |
VertxServiceDiscovery { public ServiceReference lookupForAReferenceWithConfiguration(Record record, JsonObject configuration) { return serviceDiscovery.getReferenceWithConfiguration(record, configuration); } VertxServiceDiscovery(Vertx vertx); ServiceDiscovery serviceDiscovery(); HttpServiceDiscovery http(); EventBusServiceDiscovery eventBus(); MessageSourceServiceDiscovery messageSource(); JDBCServiceDiscovery jdbc(); RedisServiceDiscovery redis(); MongoServiceDiscovery mongo(); void unpublish(Record record, Handler<AsyncResult<Void>> handler); void publishRecord(Record record, Handler<AsyncResult<Record>> handler); void lookup(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler); void lookupByJson(JsonObject jsonFilter, Handler<AsyncResult<Record>> handler); void lookupAll(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler); void lookupAllByJson(JsonObject jsonFilter, Handler<AsyncResult<List<Record>>> handler); ServiceReference lookupForAReference(Record record); ServiceReference lookupForAReferenceWithConfiguration(Record record, JsonObject configuration); void releaseServiceObject(Object object); } | @Test public void givenServiceDiscovery_whenPublishServiceWithMetadataAndLookupForItsServiceReferencePassingConfiguration_thenShouldGetTheReferenceUponTheseConfigurations(TestContext context) throws Exception { publishTestRecord(record, context.asyncAssertSuccess(record -> { ServiceReference reference = vertxServiceDiscovery.lookupForAReferenceWithConfiguration(record, metadata); assertEquals(VALUE, reference.record().getMetadata().getString(KEY)); })); } |
ListItemsUniqueModel extends AbstractValueModel { public void setValue(Object newValue) { throw new UnsupportedOperationException("ListItemsUniqueModel is read-only"); } ListItemsUniqueModel(ObservableList<E> list, Class<E> beanClass, String propertyName); Object getValue(); boolean calculate(); void setValue(Object newValue); } | @Test public void testEventsOnPropertyChange() { ObservableList<ValueHolder> list = new ArrayListModel<ValueHolder>(); ValueHolder v1 = new ValueHolder("A"); list.add(v1); ValueHolder v2 = new ValueHolder("B"); list.add(v2); ListItemsUniqueModel<ValueHolder> unique = new ListItemsUniqueModel<ValueHolder>(list, ValueHolder.class, "value"); PropertyChangeListener listener = EasyMock.createStrictMock(PropertyChangeListener.class); listener.propertyChange(JUnitUtil.eqPropertyChangeEvent( new PropertyChangeEvent(unique, "value", true, false))); listener.propertyChange(JUnitUtil.eqPropertyChangeEvent( new PropertyChangeEvent(unique, "value", false, true))); EasyMock.replay(listener); unique.addPropertyChangeListener(listener); v1.setValue("B"); v1.setValue("Bar"); EasyMock.verify(listener); } |
CollectionUtil { public static <E> E getElementAtIndex(Collection<E> set, int idx) { if (idx >= set.size() || idx < 0) { throw new IndexOutOfBoundsException(); } Iterator<E> it = set.iterator(); for (int i = 0; i < idx; ++i) { it.next(); } return it.next(); } static E getElementAtIndex(Collection<E> set, int idx); static int getIndexOfElement(Collection<E> set, Object child); static boolean containsAllAndOnly(List<?> c1, List<?> c2); static boolean nextLexicographicElement(int x[], int c[]); } | @Test public void testGetElementAtIndex() { assertEquals("A", CollectionUtil.getElementAtIndex(d_set, 0)); assertEquals("B", CollectionUtil.getElementAtIndex(d_set, 1)); }
@Test(expected=IndexOutOfBoundsException.class) public void testGetElementAtIndexTooHigh() { CollectionUtil.getElementAtIndex(d_set, 2); }
@Test(expected=IndexOutOfBoundsException.class) public void testGetElementAtIndexNegative() { CollectionUtil.getElementAtIndex(d_set, -1); } |
CollectionUtil { public static <E> int getIndexOfElement(Collection<E> set, Object child) { int i = 0; for (E e : set) { if (e.equals(child)) { return i; } ++i; } return -1; } static E getElementAtIndex(Collection<E> set, int idx); static int getIndexOfElement(Collection<E> set, Object child); static boolean containsAllAndOnly(List<?> c1, List<?> c2); static boolean nextLexicographicElement(int x[], int c[]); } | @Test public void testGetIndexOfElement() { assertEquals(0, CollectionUtil.getIndexOfElement(d_set, "A")); assertEquals(1, CollectionUtil.getIndexOfElement(d_set, "B")); assertEquals(-1, CollectionUtil.getIndexOfElement(d_set, "C")); } |
CollectionUtil { public static boolean nextLexicographicElement(int x[], int c[]) { assert(x.length == c.length); final int l = x.length; if (l < 1) { return false; } for (int i = l - 1; i >= 0; --i) { ++x[i]; if (x[i] == c[i]) { x[i] = 0; } else { return true; } } return false; } static E getElementAtIndex(Collection<E> set, int idx); static int getIndexOfElement(Collection<E> set, Object child); static boolean containsAllAndOnly(List<?> c1, List<?> c2); static boolean nextLexicographicElement(int x[], int c[]); } | @Test public void testNextLexicographicElement() { int c[] = new int[] {1, 2, 3, 1}; int x[] = new int[] {0, 0, 0, 0}; assertTrue(CollectionUtil.nextLexicographicElement(x, c)); assertArrayEquals(new int[] {0, 0, 1, 0}, x); assertTrue(CollectionUtil.nextLexicographicElement(x, c)); assertArrayEquals(new int[] {0, 0, 2, 0}, x); assertTrue(CollectionUtil.nextLexicographicElement(x, c)); assertArrayEquals(new int[] {0, 1, 0, 0}, x); assertTrue(CollectionUtil.nextLexicographicElement(x, c)); assertArrayEquals(new int[] {0, 1, 1, 0}, x); assertTrue(CollectionUtil.nextLexicographicElement(x, c)); assertArrayEquals(new int[] {0, 1, 2, 0}, x); assertFalse(CollectionUtil.nextLexicographicElement(x, c)); assertArrayEquals(new int[] {0, 0, 0, 0}, x); assertFalse(CollectionUtil.nextLexicographicElement(new int[] { 0 }, new int[] { 1 })); assertTrue(CollectionUtil.nextLexicographicElement(new int[] { 0 }, new int[] { 2 })); } |
GuardedObservableList extends AbstractObservableList<E> { @Override public void add(int index, E element) { check(element); d_nested.add(index, element); } GuardedObservableList(ObservableList<E> nested, Predicate<? super E> predicate); @Override E get(int index); @Override int size(); @Override void add(int index, E element); @Override E set(int index, E element); @Override E remove(int index); } | @Test(expected=IllegalArgumentException.class) public void testConstructionWithNonEmptyList() { ObservableList<Integer> list = new ArrayListModel<Integer>(); list.add(1); d_list = new GuardedObservableList<Integer>(list, new Predicate<Number>() { public boolean evaluate(Number object) { return object.doubleValue() > 0.0; } }); }
@Test(expected=IllegalArgumentException.class) public void testAddBadValue() { d_list.add(-1); } |
GuardedObservableList extends AbstractObservableList<E> { @Override public E set(int index, E element) { check(element); return d_nested.set(index, element); } GuardedObservableList(ObservableList<E> nested, Predicate<? super E> predicate); @Override E get(int index); @Override int size(); @Override void add(int index, E element); @Override E set(int index, E element); @Override E remove(int index); } | @Test(expected=IllegalArgumentException.class) public void testSetBadValue() { d_list.set(1, -1); } |
FilteredObservableList extends AbstractObservableList<E> { @Override public void add(final int index, final E element) { if(!d_filter.evaluate(element)) throw new IllegalArgumentException("Cannot add " + element + ", it does not pass the filter of " + this); if(index < d_indices.size()) { d_inner.add(d_indices.get(index), element); } else { d_inner.add(d_inner.size(), element); } } FilteredObservableList(final ObservableList<E> inner, final Predicate<E> filter); void setFilter(final Predicate<E> filter); @Override E get(final int index); @Override void add(final int index, final E element); @Override E set(final int index, final E element); @Override E remove(final int index); @Override int size(); } | @Test public void testContentsUpdateAddNone() { ListDataListener mock = createStrictMock(ListDataListener.class); replay(mock); d_outer.addListDataListener(mock); d_inner.add(2, "Haank"); assertEquals(Arrays.asList("Gert", "Jan"), d_outer); verify(mock); }
@Test public void testSublistUpdating() { ObservableList<String> list = new SortedSetModel<String>(Arrays.asList("Aa", "Ab", "Ba", "Bb")); ObservableList<String> aList = new FilteredObservableList<String>(list, new Predicate<String>(){ public boolean evaluate(String obj) { return obj.charAt(0) == 'A'; }}); ObservableList<String> bList = new FilteredObservableList<String>(list, new Predicate<String>(){ public boolean evaluate(String obj) { return obj.charAt(0) == 'B'; }}); assertEquals(Arrays.asList("Aa", "Ab"), aList); assertEquals(Arrays.asList("Ba", "Bb"), bList); list.add("Ac"); assertEquals(Arrays.asList("Aa", "Ab", "Ac"), aList); assertEquals(Arrays.asList("Ba", "Bb"), bList); }
@Test(expected=IllegalArgumentException.class) public void testAddNonAcceptable() { d_outer.add("Maarten"); } |
FilteredObservableList extends AbstractObservableList<E> { private void intervalAdded(final int lower, final int upper) { final int delta = upper - lower + 1; final int first = firstAtLeast(lower); updateIndices(first, delta); final int oldSize = d_indices.size(); for(int i = upper; i >= lower; --i) { if (d_filter.evaluate(d_inner.get(i))) { d_indices.add(first, i); } } final int inserted = d_indices.size() - oldSize; if (inserted > 0) { fireIntervalAdded(first, first + inserted - 1); } } FilteredObservableList(final ObservableList<E> inner, final Predicate<E> filter); void setFilter(final Predicate<E> filter); @Override E get(final int index); @Override void add(final int index, final E element); @Override E set(final int index, final E element); @Override E remove(final int index); @Override int size(); } | @Test public void testContentsUpdateAddAllIndex() { ListDataListener mock = createStrictMock(ListDataListener.class); mock.intervalAdded(ListDataEventMatcher.eqListDataEvent(new ListDataEvent(d_outer, ListDataEvent.INTERVAL_ADDED, 1, 2))); replay(mock); d_outer.addListDataListener(mock); d_inner.addAll(2, Arrays.asList("Henk", "Bart")); assertEquals(Arrays.asList("Gert", "Henk", "Bart", "Jan"), d_outer); verify(mock); }
@Test public void testContentsUpdateAddAllEnd() { ListDataListener mock = createStrictMock(ListDataListener.class); mock.intervalAdded(ListDataEventMatcher.eqListDataEvent(new ListDataEvent(d_outer, ListDataEvent.INTERVAL_ADDED, 2, 3))); replay(mock); d_outer.addListDataListener(mock); d_inner.addAll(Arrays.asList("Henk", "Bart")); assertEquals(Arrays.asList("Gert", "Jan", "Henk", "Bart"), d_outer); verify(mock); } |
ListMinimumSizeModel extends AbstractValueModel { public Boolean getValue() { return d_val; } ListMinimumSizeModel(ListModel list, int minSize); Boolean getValue(); void setValue(Object value); } | @Test public void testInitialValues() { assertFalse(new ListMinimumSizeModel(new ArrayListModel<String>(), 1).getValue()); assertTrue(new ListMinimumSizeModel(new ArrayListModel<String>(Arrays.asList("Test")), 1).getValue()); assertFalse(new ListMinimumSizeModel(new ArrayListModel<String>(Arrays.asList("Test")), 2).getValue()); assertTrue(new ListMinimumSizeModel(new ArrayListModel<String>(Arrays.asList("Test", "Test")), 2).getValue()); } |
FilteredObservableList extends AbstractObservableList<E> { @Override public E remove(final int index) { return d_inner.remove((int) d_indices.get(index)); } FilteredObservableList(final ObservableList<E> inner, final Predicate<E> filter); void setFilter(final Predicate<E> filter); @Override E get(final int index); @Override void add(final int index, final E element); @Override E set(final int index, final E element); @Override E remove(final int index); @Override int size(); } | @Test public void testContentsUpdateRemoveNone() { ListDataListener mock = createStrictMock(ListDataListener.class); replay(mock); d_outer.addListDataListener(mock); d_inner.remove("Daan"); assertEquals(Arrays.asList("Gert", "Jan"), d_outer); verify(mock); } |
FilteredObservableList extends AbstractObservableList<E> { private void intervalRemoved(final int lower, final int upper) { final int first = firstAtLeast(lower); if (first >= d_indices.size()) { return; } final int last = firstOver(upper); d_indices.removeAll(new ArrayList<Integer>(d_indices.subList(first, last))); final int delta = upper - lower + 1; updateIndices(first, -delta); if (last > first) { fireIntervalRemoved(first, last - 1); } } FilteredObservableList(final ObservableList<E> inner, final Predicate<E> filter); void setFilter(final Predicate<E> filter); @Override E get(final int index); @Override void add(final int index, final E element); @Override E set(final int index, final E element); @Override E remove(final int index); @Override int size(); } | @Test public void testContentsUpdateRemoveAll() { ListDataListener mock = createStrictMock(ListDataListener.class); mock.intervalRemoved(ListDataEventMatcher.eqListDataEvent(new ListDataEvent(d_outer, ListDataEvent.INTERVAL_REMOVED, 0, 1))); replay(mock); d_outer.addListDataListener(mock); d_inner.clear(); assertEquals(Collections.emptyList(), d_outer); verify(mock); } |
FilteredObservableList extends AbstractObservableList<E> { @Override public E set(final int index, final E element) { if(!d_filter.evaluate(element)) throw new IllegalArgumentException("Cannot add " + element + ", it does not pass the filter."); return d_inner.set(d_indices.get(index), element); } FilteredObservableList(final ObservableList<E> inner, final Predicate<E> filter); void setFilter(final Predicate<E> filter); @Override E get(final int index); @Override void add(final int index, final E element); @Override E set(final int index, final E element); @Override E remove(final int index); @Override int size(); } | @Test public void testContentsUpdateFirstElement() { d_inner.set(0, "Gaart"); assertEquals(Arrays.asList("Jan"), d_outer); d_inner.set(0, "Gert"); assertEquals(Arrays.asList("Gert", "Jan"), d_outer); }
@Test public void testContentsUpdateLastElement() { d_inner.set(3, "Klees"); assertEquals(Arrays.asList("Gert", "Jan", "Klees"), d_outer); }
@Test public void testContentsUpdateSetNoChangeExcl() { ListDataListener mock = createStrictMock(ListDataListener.class); replay(mock); d_outer.addListDataListener(mock); d_inner.set(3, "Paard"); assertEquals(Arrays.asList("Gert", "Jan"), d_outer); verify(mock); }
@Test(expected=IllegalArgumentException.class) public void testSetNonAcceptable() { d_outer.set(1, "Maarten"); } |
FilteredObservableList extends AbstractObservableList<E> { public void setFilter(final Predicate<E> filter) { d_filter = filter; final int oldSize = size(); if(!isEmpty()) { d_indices.clear(); fireIntervalRemoved(0, oldSize - 1); } initializeIndices(); if(!isEmpty()) { fireIntervalAdded(0, size() - 1); } } FilteredObservableList(final ObservableList<E> inner, final Predicate<E> filter); void setFilter(final Predicate<E> filter); @Override E get(final int index); @Override void add(final int index, final E element); @Override E set(final int index, final E element); @Override E remove(final int index); @Override int size(); } | @Test public void testSetFilter() { ListDataListener mock = createStrictMock(ListDataListener.class); mock.intervalRemoved(ListDataEventMatcher.eqListDataEvent(new ListDataEvent(d_outer, ListDataEvent.INTERVAL_REMOVED, 0, 1))); mock.intervalAdded(ListDataEventMatcher.eqListDataEvent(new ListDataEvent(d_outer, ListDataEvent.INTERVAL_ADDED, 0, 2))); replay(mock); d_outer.addListDataListener(mock); d_outer.setFilter(new Predicate<String>() { public boolean evaluate(String str) { return !str.equals("Gert"); } }); assertEquals(Arrays.asList("Daan", "Jan", "Klaas"), d_outer); verify(mock); } |
ListMinimumSizeModel extends AbstractValueModel { public void setValue(Object value) { throw new UnsupportedOperationException(); } ListMinimumSizeModel(ListModel list, int minSize); Boolean getValue(); void setValue(Object value); } | @Test(expected=UnsupportedOperationException.class) public void testSetValueNotSupported() { new ListMinimumSizeModel(new ArrayListModel<String>(), 2).setValue(true); } |
SortedSetModel extends AbstractList<E> implements ObservableList<E> { @Override public E remove(int index) { if (index >= 0 && index < size()) { E e = get(index); d_set.remove(e); d_listenerManager.fireIntervalRemoved(index, index); return e; } throw new IndexOutOfBoundsException(); } SortedSetModel(); SortedSetModel(Comparator<? super E> comparator); SortedSetModel(Collection<? extends E> c); @Override int size(); @Override E get(int index); @Override void add(int index, E element); @Override E remove(int index); @Override boolean remove(Object o); int getSize(); Object getElementAt(int index); void addListDataListener(ListDataListener l); void removeListDataListener(ListDataListener l); SortedSet<E> getSet(); } | @Test public void testRemoving() { assertTrue(d_filledList.remove("Daan")); assertEquals(Arrays.asList("Gert", "Margreth"), d_filledList); assertEquals("Gert", d_filledList.remove(0)); assertEquals(Arrays.asList("Margreth"), d_filledList); resetFilledList(); d_filledList.clear(); assertEquals(Collections.emptyList(), d_filledList); resetFilledList(); ListIterator<String> it = d_filledList.listIterator(); int i = 0; while (it.hasNext()) { it.next(); if (i % 2 == 0) { it.remove(); } ++i; } assertEquals(Collections.singletonList("Gert"), d_filledList); } |
SortedSetModel extends AbstractList<E> implements ObservableList<E> { @Override public void add(int index, E element) { if (!d_set.contains(element)) { d_set.add(element); int idx = indexOf(element); d_listenerManager.fireIntervalAdded(idx, idx); } } SortedSetModel(); SortedSetModel(Comparator<? super E> comparator); SortedSetModel(Collection<? extends E> c); @Override int size(); @Override E get(int index); @Override void add(int index, E element); @Override E remove(int index); @Override boolean remove(Object o); int getSize(); Object getElementAt(int index); void addListDataListener(ListDataListener l); void removeListDataListener(ListDataListener l); SortedSet<E> getSet(); } | @Test public void testAdding() { SortedSetModel<String> ssm = new SortedSetModel<String>(); ssm.add(0, "Gert"); assertEquals(Arrays.asList("Gert"), ssm); ssm.add(0, "Margreth"); assertEquals(Arrays.asList("Gert", "Margreth"), ssm); } |
SortedSetModel extends AbstractList<E> implements ObservableList<E> { public SortedSet<E> getSet() { return new TreeSet<E>(d_set); } SortedSetModel(); SortedSetModel(Comparator<? super E> comparator); SortedSetModel(Collection<? extends E> c); @Override int size(); @Override E get(int index); @Override void add(int index, E element); @Override E remove(int index); @Override boolean remove(Object o); int getSize(); Object getElementAt(int index); void addListDataListener(ListDataListener l); void removeListDataListener(ListDataListener l); SortedSet<E> getSet(); } | @Test public void testGetSet() { assertEquals(new TreeSet<String>(d_filledList), d_filledList.getSet()); } |
ValueEqualsModel extends AbstractConverter { public void setValue(final Object newValue) { throw new UnsupportedOperationException(getClass().getSimpleName() + " is read-only"); } ValueEqualsModel(final ValueModel model, final Object expectedValue); void setValue(final Object newValue); Object convertFromSubject(final Object subjectValue); void setExpected(Object expectedValue); } | @Test public void testEqualsExpected() { ValueHolder valueModel = new ValueHolder("name"); ValueEqualsModel equalsModel = new ValueEqualsModel(valueModel, "name"); assertEquals(Boolean.TRUE, equalsModel.getValue()); PropertyChangeListener listener = EasyMock.createStrictMock(PropertyChangeListener.class); listener.propertyChange(JUnitUtil.eqPropertyChangeEvent(new PropertyChangeEvent(equalsModel, "value", true, false))); EasyMock.replay(listener); equalsModel.addPropertyChangeListener(listener); valueModel.setValue("naem"); EasyMock.verify(listener); } |
ValueEqualsModel extends AbstractConverter { public void setExpected(Object expectedValue) { Object oldVal = getValue(); d_expectedValue = expectedValue; firePropertyChange("value", oldVal, getValue()); } ValueEqualsModel(final ValueModel model, final Object expectedValue); void setValue(final Object newValue); Object convertFromSubject(final Object subjectValue); void setExpected(Object expectedValue); } | @Test public void testChangeExpected() { ValueHolder valueModel = new ValueHolder("name"); ValueEqualsModel equalsModel = new ValueEqualsModel(valueModel, "name"); assertEquals(Boolean.TRUE, equalsModel.getValue()); PropertyChangeListener listener = EasyMock.createStrictMock(PropertyChangeListener.class); listener.propertyChange(JUnitUtil.eqPropertyChangeEvent(new PropertyChangeEvent(equalsModel, "value", true, false))); EasyMock.replay(listener); equalsModel.addPropertyChangeListener(listener); equalsModel.setExpected(15); EasyMock.verify(listener); } |
DateUtil { public static Date getCurrentDateWithoutTime() { Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.AM_PM, Calendar.AM); Date date = cal.getTime(); return date; } static Date getCurrentDateWithoutTime(); } | @SuppressWarnings("deprecation") @Test public void testGetCurrentDateWithoutTime() { Date now = new Date(); Date woTime = DateUtil.getCurrentDateWithoutTime(); assertEquals(now.getYear(), woTime.getYear()); assertEquals(now.getMonth(), woTime.getMonth()); assertEquals(now.getDay(), woTime.getDay()); assertEquals(0, woTime.getHours()); assertEquals(0, woTime.getMinutes()); assertEquals(0, woTime.getSeconds()); } |
Statistics { public static EstimateWithPrecision meanDifference( double m0, double s0, double n0, double m1, double s1, double n1) { double md = m1 - m0; double se = Math.sqrt((s0 * s0) / n0 + (s1 * s1) / n1); return new EstimateWithPrecision(md, se); } private Statistics(); static double logit(double p); static double ilogit(double x); static EstimateWithPrecision logOddsRatio(
int a, int n, int c, int m, boolean corrected); static EstimateWithPrecision meanDifference(
double m0, double s0, double n0,
double m1, double s1, double n1); } | @Test public void testMeanDifference() { EstimateWithPrecision e = Statistics.meanDifference( -2.5, 1.6, 177, -2.6, 1.5, 176); assertEquals(-0.1, e.getPointEstimate(), EPSILON); assertEquals(0.1650678, e.getStandardError(), EPSILON); } |
SimpleSuspendableTask implements SimpleTask { public boolean wakeUp() { return d_suspendable.wakeUp(); } SimpleSuspendableTask(Suspendable suspendable, String str); SimpleSuspendableTask(Runnable runnable, String str); SimpleSuspendableTask(Runnable runnable); SimpleSuspendableTask(Suspendable suspendable); void addTaskListener(TaskListener l); void removeTaskListener(TaskListener l); void run(); boolean isStarted(); boolean isFinished(); boolean isFailed(); Throwable getFailureCause(); boolean isAborted(); boolean isSuspended(); boolean suspend(); boolean wakeUp(); boolean abort(); @Override String toString(); } | @Test public void wakeUpWakesNested() { Suspendable mockSuspendable = createStrictMock(Suspendable.class); expect(mockSuspendable.wakeUp()).andReturn(true); replay(mockSuspendable); SimpleTask task = new SimpleSuspendableTask(mockSuspendable); task.wakeUp(); verify(mockSuspendable); } |
SimpleSuspendableTask implements SimpleTask { public boolean abort() { return d_suspendable.abort(); } SimpleSuspendableTask(Suspendable suspendable, String str); SimpleSuspendableTask(Runnable runnable, String str); SimpleSuspendableTask(Runnable runnable); SimpleSuspendableTask(Suspendable suspendable); void addTaskListener(TaskListener l); void removeTaskListener(TaskListener l); void run(); boolean isStarted(); boolean isFinished(); boolean isFailed(); Throwable getFailureCause(); boolean isAborted(); boolean isSuspended(); boolean suspend(); boolean wakeUp(); boolean abort(); @Override String toString(); } | @Test public void wakeUpAbortsNested() { Suspendable mockSuspendable = createStrictMock(Suspendable.class); expect(mockSuspendable.abort()).andReturn(true); replay(mockSuspendable); SimpleTask task = new SimpleSuspendableTask(mockSuspendable); task.abort(); verify(mockSuspendable); } |
DecisionTransition implements Transition { public List<Task> transition() { if (!isReady()) { throw new RuntimeException("Not ready for transition."); } if (d_condition.evaluate()) { return Collections.singletonList(d_ifTask); } else { return Collections.singletonList(d_elTask); } } DecisionTransition(Task source, Task ifTask, Task elTask, Condition condition); List<Task> getSources(); List<Task> getTargets(); boolean isReady(); List<Task> transition(); } | @Test public void testTrueCondition() { MockTask source = new MockTask(); Task ifTask = new MockTask(); Task elTask = new MockTask(); Condition condition = createStrictMock(Condition.class); expect(condition.evaluate()).andReturn(true); replay(condition); Transition trans = new DecisionTransition(source, ifTask, elTask, condition); source.start(); source.finish(); assertEquals(Collections.singletonList(ifTask), trans.transition()); verify(condition); }
@Test public void testFalseCondition() { MockTask source = new MockTask(); Task ifTask = new MockTask(); Task elTask = new MockTask(); Condition condition = createStrictMock(Condition.class); expect(condition.evaluate()).andReturn(false); replay(condition); Transition trans = new DecisionTransition(source, ifTask, elTask, condition); source.start(); source.finish(); assertEquals(Collections.singletonList(elTask), trans.transition()); verify(condition); } |
StringNotEmptyModel extends AbstractValueModel { public Boolean getValue() { return d_val; } StringNotEmptyModel(ValueModel nested); Boolean getValue(); void setValue(Object value); } | @Test public void testInitialValues() { assertFalse(new StringNotEmptyModel(new ValueHolder(null)).getValue()); assertFalse(new StringNotEmptyModel(new ValueHolder(new Object())).getValue()); assertFalse(new StringNotEmptyModel(new ValueHolder("")).getValue()); assertTrue(new StringNotEmptyModel(new ValueHolder("Test")).getValue()); } |
ActivityModel { public Set<Task> getNextStates() { if (isFinished()) { return Collections.emptySet(); } return findAccessibleStates(d_start); } ActivityModel(Task start, Task end, Collection<? extends Transition> transitions); Set<Task> getNextStates(); boolean isFinished(); Task getStartState(); Task getEndState(); Set<Task> getStates(); Task getStateByName(String name); Set<Transition> getTransitions(); } | @Test public void testInitialState() { MockTask start = new MockTask(); start.start(); MockTask end = new MockTask(); Transition trans = new DirectTransition(start, end); ActivityModel model = new ActivityModel(start, end, Collections.singleton(trans)); assertEquals(Collections.singleton(start), model.getNextStates()); }
@Test public void testSimpleTransition() { MockTask start = new MockTask(); start.start(); MockTask end = new MockTask(); Transition trans = new DirectTransition(start, end); ActivityModel model = new ActivityModel(start, end, Collections.singleton(trans)); start.finish(); assertEquals(Collections.singleton(end), model.getNextStates()); } |
ActivityModel { public boolean isFinished() { return d_end.isFinished(); } ActivityModel(Task start, Task end, Collection<? extends Transition> transitions); Set<Task> getNextStates(); boolean isFinished(); Task getStartState(); Task getEndState(); Set<Task> getStates(); Task getStateByName(String name); Set<Transition> getTransitions(); } | @Test public void testIsFinished() { MockTask start = new MockTask(); start.start(); MockTask end = new MockTask(); Transition trans = new DirectTransition(start, end); ActivityModel model = new ActivityModel(start, end, Collections.singleton(trans)); start.finish(); end.start(); end.finish(); assertTrue(model.isFinished()); assertEquals(Collections.<Task>emptySet(), model.getNextStates()); } |
IterativeTask extends SimpleSuspendableTask { public void setReportingInterval(int interval) { ((IterativeSuspendable)d_suspendable).setReportingInterval(interval); } IterativeTask(IterativeComputation computation, String str); IterativeTask(IterativeComputation computation); void setReportingInterval(int interval); @Override String toString(); } | @Test public void testNotifyProgress() { IterativeComputation comp = new ShortComputation(10); IterativeTask task = new IterativeTask(comp); task.setReportingInterval(3); TaskListener listener = createStrictMock(TaskListener.class); listener.taskEvent(new TaskStartedEvent(task)); listener.taskEvent(new TaskProgressEvent(task, 0, 10)); listener.taskEvent(new TaskProgressEvent(task, 3, 10)); listener.taskEvent(new TaskProgressEvent(task, 6, 10)); listener.taskEvent(new TaskProgressEvent(task, 9, 10)); listener.taskEvent(new TaskProgressEvent(task, 10, 10)); listener.taskEvent(new TaskFinishedEvent(task)); replay(listener); task.addTaskListener(listener); task.run(); verify(listener); }
@Test public void testNotifyProgress2() { IterativeComputation comp = new ShortComputation(9); IterativeTask task = new IterativeTask(comp); task.setReportingInterval(3); TaskListener listener = createStrictMock(TaskListener.class); listener.taskEvent(new TaskStartedEvent(task)); listener.taskEvent(new TaskProgressEvent(task, 0, 9)); listener.taskEvent(new TaskProgressEvent(task, 3, 9)); listener.taskEvent(new TaskProgressEvent(task, 6, 9)); listener.taskEvent(new TaskProgressEvent(task, 9, 9)); listener.taskEvent(new TaskFinishedEvent(task)); replay(listener); task.addTaskListener(listener); task.run(); verify(listener); } |
StringNotEmptyModel extends AbstractValueModel { public void setValue(Object value) { throw new UnsupportedOperationException(); } StringNotEmptyModel(ValueModel nested); Boolean getValue(); void setValue(Object value); } | @Test(expected=UnsupportedOperationException.class) public void testSetValueNotSupported() { new StringNotEmptyModel(new ValueHolder(null)).setValue(true); }
@Test public void testEventChaining() { ValueHolder holder = new ValueHolder(null); StringNotEmptyModel model = new StringNotEmptyModel(holder); PropertyChangeListener mock = JUnitUtil.mockStrictListener(model, "value", false, true); model.addValueChangeListener(mock); holder.setValue("test"); holder.setValue("test2"); verify(mock); model.removeValueChangeListener(mock); mock = JUnitUtil.mockStrictListener(model, "value", true, false); model.addValueChangeListener(mock); holder.setValue(""); verify(mock); } |
StudentTTable { public static double getT(int v) { if (v < 1) { throw new IllegalArgumentException("student T distribution defined only for positive degrees of freedom"); } TDistribution dist = new TDistribution(v); return dist.inverseCumulativeProbability(0.975); } static double getT(int v); } | @Test public void testTable() { assertEquals(12.706, StudentTTable.getT(1), 0.001); assertEquals(1.998, StudentTTable.getT(63), 0.001); assertEquals(1.96, StudentTTable.getT(1000), 0.01); assertEquals(1.96, StudentTTable.getT(2000), 0.01); assertEquals(StudentTTable.getT(160) / 2 + StudentTTable.getT(140) / 2, StudentTTable.getT(150), 0.01); assertEquals(3 * StudentTTable.getT(160) / 4 + StudentTTable.getT(140) / 4, StudentTTable.getT(155), 0.01); } |
Interval { public double getLength() { return d_upperBound.doubleValue() - d_lowerBound.doubleValue(); } Interval(N lowerBound, N upperBound); N getLowerBound(); N getUpperBound(); double getLength(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } | @Test public void testGetLength() { Interval<Double> in = new Interval<Double>(1.0, 6.0); assertEquals(5.0, in.getLength(), 0.00001); } |
Interval { @Override public boolean equals(Object o) { if (o instanceof Interval<?>) { Interval<?> other = (Interval<?>) o; if (other.canEqual(this)) { if (other.getLowerBound().getClass().equals(getLowerBound().getClass())) { return ((getLowerBound().equals(other.getLowerBound())) && (getUpperBound().equals(other.getUpperBound()))); } } } return false; } Interval(N lowerBound, N upperBound); N getLowerBound(); N getUpperBound(); double getLength(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } | @Test public void testEquals() { Interval<Double> in = new Interval<Double>(1.0, 6.0); Interval<Integer> in2 = new Interval<Integer>(1, 6); assertNotEquals(in, in2); Double d = new Double(1.0); Integer i = new Integer(6); assertNotEquals(d, in); assertNotEquals(i, in2); Interval<Double> in3 = new Interval<Double>(1.0, 6.0); Interval<Integer> in4 = new Interval<Integer>(1, 6); assertEquals(in, in3); assertEquals(in.hashCode(), in3.hashCode()); assertEquals(in2, in4); assertEquals(in2.hashCode(), in4.hashCode()); Interval<Double> in5 = new Interval<Double>(2.0, 5.0); assertNotEquals(in, in5); } |
Interval { @Override public String toString() { return getLowerBound().toString() + "-" + getUpperBound().toString(); } Interval(N lowerBound, N upperBound); N getLowerBound(); N getUpperBound(); double getLength(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } | @Test public void testToString() { Interval<Double> in = new Interval<Double>(1.0, 6.0); assertEquals("1.0-6.0", in.toString()); } |
LogstashLayout implements Layout<String> { @PluginBuilderFactory @SuppressWarnings("WeakerAccess") public static Builder newBuilder() { return new Builder(); } private LogstashLayout(Builder builder); @Override String toSerializable(LogEvent event); @Override byte[] toByteArray(LogEvent event); @Override void encode(LogEvent event, ByteBufferDestination destination); @Override byte[] getFooter(); @Override byte[] getHeader(); @Override String getContentType(); @Override Map<String, String> getContentFormat(); @PluginBuilderFactory @SuppressWarnings("WeakerAccess") static Builder newBuilder(); } | @Test public void test_lineSeparator_suffix() { SimpleMessage message = new SimpleMessage("Hello, World!"); LogEvent logEvent = Log4jLogEvent .newBuilder() .setLoggerName(LogstashLayoutTest.class.getSimpleName()) .setLevel(Level.INFO) .setMessage(message) .build(); test_lineSeparator_suffix(logEvent, true); test_lineSeparator_suffix(logEvent, false); } |
MainActivity extends AppCompatActivity { @VisibleForTesting void initViews() { EditText weightText = (EditText)findViewById(R.id.text_weight); EditText heightText = (EditText)findViewById(R.id.text_height); TextView resultText = (TextView)findViewById(R.id.text_result); mCalcButton = (Button)findViewById(R.id.button_calculate); View.OnClickListener buttonListener = createButtonListener(weightText, heightText, resultText); mCalcButton.setOnClickListener(buttonListener); } } | @Test public void initViews를호출하면버튼의Listener가설정된다() { EditText weightText = mock(EditText.class); EditText heightText = mock(EditText.class); TextView resultText = mock(TextView.class); Button resultButton = mock(Button.class); View.OnClickListener buttonListener = mock(View.OnClickListener.class); MainActivity activity = spy(new MainActivity()); when(activity.findViewById(R.id.text_weight)).thenReturn(weightText); when(activity.findViewById(R.id.text_height)).thenReturn(heightText); when(activity.findViewById(R.id.text_result)).thenReturn(resultText); when(activity.findViewById(R.id.button_calculate)).thenReturn(resultButton); when(activity.createButtonListener(weightText, heightText, resultText)).thenReturn(buttonListener); activity.initViews(); verify(activity, times(1)).createButtonListener(weightText, heightText, resultText); verify(resultButton, times(1)).setOnClickListener(buttonListener); } |
SaveBmiService extends IntentService { public static void start(Context context, BmiValue bmiValue) { Intent intent = new Intent(context, SaveBmiService.class); intent.putExtra(PARAM_KEY_BMI_VALUE, bmiValue); context.startService(intent); } SaveBmiService(); @Override void onCreate(); static void start(Context context, BmiValue bmiValue); static final String ACTION_RESULT; static final String PARAM_RESULT; } | @Test public void static인start메소드를호출하면startService된다() { Context context = mock(Context.class); SaveBmiService.start(context, mock(BmiValue.class)); verify(context, times(1)).startService((Intent) any()); } |
SaveBmiService extends IntentService { @Override protected void onHandleIntent(Intent intent) { if (intent == null) { return; } Serializable extra = intent.getSerializableExtra(PARAM_KEY_BMI_VALUE); if (extra == null || !(extra instanceof BmiValue)) { return; } BmiValue bmiValue = (BmiValue)extra; boolean result = saveToRemoteServer(bmiValue); sendLocalBroadcast(result); } SaveBmiService(); @Override void onCreate(); static void start(Context context, BmiValue bmiValue); static final String ACTION_RESULT; static final String PARAM_RESULT; } | @Test public void onHandleIntentにnull을전달하면아무것도하지않는다() { SaveBmiService service = spy(new SaveBmiService()); service.onHandleIntent(null); verify(service, never()).sendLocalBroadcast(anyBoolean()); verify(service, never()).saveToRemoteServer((BmiValue) any()); }
@Test public void onHandleIntent에파라미터없는Intent를전달하면아무것도하지않는다() { SaveBmiService service = spy(new SaveBmiService()); service.onHandleIntent(mock(Intent.class)); verify(service, never()).sendLocalBroadcast(anyBoolean()); verify(service, never()).saveToRemoteServer((BmiValue)any()); }
@Test public void onHandleIntent에BmiValue형이외의데이터가들어간Intent를전달하면아무것도하지않는다() { Intent intent = mock(Intent.class); when(intent.getSerializableExtra(SaveBmiService.PARAM_KEY_BMI_VALUE)).thenReturn("hoge"); SaveBmiService service = spy(new SaveBmiService()); service.onHandleIntent(intent); verify(service, never()).sendLocalBroadcast(anyBoolean()); verify(service, never()).saveToRemoteServer((BmiValue)any()); }
@Test public void onHandleIntent에바르게데이터가들어간Intent를전달하면데이터저장과Broadcast가이루어진다() { BmiValue bmiValue = mock(BmiValue.class); Intent intent = mock(Intent.class); when(intent.getSerializableExtra(SaveBmiService.PARAM_KEY_BMI_VALUE)).thenReturn(bmiValue); SaveBmiService service = spy(new SaveBmiService()); doReturn(false).when(service).saveToRemoteServer((BmiValue)any()); doNothing().when(service).sendLocalBroadcast(anyBoolean()); service.onHandleIntent(intent); verify(service, times(1)).sendLocalBroadcast(anyBoolean()); verify(service, times(1)).saveToRemoteServer((BmiValue)any()); } |
BmiCalculator { public BmiValue calculate(float heightInMeter, float weightInKg) { if (heightInMeter < 0 || weightInKg < 0) { throw new RuntimeException("키와 몸무게는 양수로 지정해주세요"); } float bmiValue = weightInKg / (heightInMeter * heightInMeter); return createValueObj(bmiValue); } BmiValue calculate(float heightInMeter, float weightInKg); } | @Test(expected = RuntimeException.class) public void 신장에음수값을넘기면예외가발생한다() { calculator.calculate(-1f, 60.0f); |
BmiValue implements Serializable { public float toFloat() { int rounded = Math.round(mValue * 100); return rounded / 100f; } BmiValue(float value); float toFloat(); String getMessage(); } | @Test public void 생성시에전달한Float값을소수점2자리까지반올림해반환한다() { BmiValue bmiValue = new BmiValue(20.00511f); Assert.assertEquals(20.01f, bmiValue.toFloat()); }
@Test public void 생성시에전달한Float값을소수점2자리까지버림해반환한다() { BmiValue bmiValue = new BmiValue(20.00499f); Assert.assertEquals(20.00f, bmiValue.toFloat()); } |
DriverSettings extends AbstractPropSettings { public String getGeckcoDriverPath() { return getProperty("GeckoDriverPath", geckoDriverPath); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(String path); void setEdgeDriverPath(String path); String getFirefoxBinaryPath(); String getGeckcoDriverPath(); String getChromeDriverPath(); String getIEDriverPath(); String getEdgeDriverPath(); Boolean useProxy(); } | @Test public void testGetGeckcoDriverPath() { String expResult; if (isWin) { expResult = "./lib/Drivers/geckodriver.exe"; } else { expResult = "./lib/Drivers/geckodriver"; } String result = ds.getGeckcoDriverPath(); assertEquals(result, expResult); } |
FParser { public static Object eval(String s) { String func = FN(s); s = s.replaceFirst(func, ""); String[] params = {}; if (s.length() >= 2) { String param = s.substring(1, s.lastIndexOf(")")); params = param.split(RX, -1); } return String.valueOf(EXE(func, params)); } static List<String> getFuncList(); static Object eval(String s); static String evaljs(String script); static List<String> FUNCTIONS; } | @Test public void testEval_DateTest() { System.out.println("eval date fn"); String s; Object result; s = "Date(0,\"MM-dd-yy\")"; result = FParser.eval(s); assertTrue(result.toString().matches("(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])-\\d{2}"), "date " + result); s = "Date(0,\"MM dd yyyy\")"; result = FParser.eval(s); assertTrue(result.toString().matches("(0[1-9]|1[012]) (0[1-9]|[12][0-9]|3[01]) \\d{4}"), "date " + result); s = "Date(0,\"MM:dd:yyyy\")"; result = FParser.eval(s); assertTrue(result.toString().matches("(0[1-9]|1[012]):(0[1-9]|[12][0-9]|3[01]):\\d{4}"), "date " + result); s = "Date(0,\"dd/MM/yyyy\")"; result = FParser.eval(s); assertTrue(result.toString().matches("(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/\\d{4}"), "date " + result); }
@Test(invocationCount = 10) public void testEval() { System.out.println("Eval"); String s = "Concat(=Round(=Random(4)),[email protected])"; Object result = FParser.eval(s); assertTrue(result.toString().matches("[0-9]{4}[email protected]"), "random email " + result); } |
FParser { public static String evaljs(String script) { try { return JS.eval("JSON.stringify(" + script + ")").toString(); } catch (ScriptException ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); } return "undefined"; } static List<String> getFuncList(); static Object eval(String s); static String evaljs(String script); static List<String> FUNCTIONS; } | @Test(invocationCount = 10) public void testEvaljs() { System.out.println("Evaljs"); String script = "floor(100 + random() * 900)"; String result = FParser.evaljs(script); assertTrue(result.matches("[0-9]{3}"), "Test random "); script = "'test'+ floor(100 + random() * 900)+'[email protected]'"; result = (String) JSONValue.parse(FParser.evaljs(script)); assertTrue(result.matches("test[0-9]{3}[email protected]"), "Test random email "); } |
KeyMap { public static String resolveContextVars(String in, Map<?,?> vMap) { return replaceKeys(in, CONTEXT_VARS, true, 1, vMap); } static Map<Object, Object> getSystemVars(); static String resolveContextVars(String in, Map<?,?> vMap); static String resolveEnvVars(String in); static String replaceKeys(String in, Pattern pattern, boolean preserveKeys, int passes, Map<?,?>... maps); static String replaceKeys(String in, Pattern p); static String resolveSystemVars(String in); static final Pattern CONTEXT_VARS; static final Pattern ENV_VARS; static final Pattern USER_VARS; } | @Test public void testResolveContextVars() { System.out.println("resolveContextVars"); String in = "this is a {scenario}/{testset} -> {testset}/{release} for {project}.{release}.{testcase} "; String expResult = "this is a myscn/ts -> ts/rel for pro.rel.tc "; String result = KeyMap.resolveContextVars(in, vMap); assertEquals(expResult, result); } |
KeyMap { public static String resolveEnvVars(String in) { return replaceKeys(in, ENV_VARS); } static Map<Object, Object> getSystemVars(); static String resolveContextVars(String in, Map<?,?> vMap); static String resolveEnvVars(String in); static String replaceKeys(String in, Pattern pattern, boolean preserveKeys, int passes, Map<?,?>... maps); static String replaceKeys(String in, Pattern p); static String resolveSystemVars(String in); static final Pattern CONTEXT_VARS; static final Pattern ENV_VARS; static final Pattern USER_VARS; } | @Test public void testResolveEnvVars() { System.out.println("resolveEnvVars"); String in = "${val.1}-${var.1}-${val.2}-${val.1}-${val.3}-${val.4}-${var.4}-${var.1}-${var.2}-"; String expResult = "1-x-b-1-c-val.4-var.4-x-y-"; String result = KeyMap.resolveEnvVars(in); assertEquals(expResult, result); } |
KeyMap { public static String replaceKeys(String in, Pattern pattern, boolean preserveKeys, int passes, Map<?,?>... maps) { String out = in; for (int pass = 1; pass <= passes; pass++) { Matcher m = pattern.matcher(in); String match, key; while (m.find()) { match = m.group(); key = m.group(1); Boolean resolved = false; if (maps != null) { for (Map<?, ?> map : maps) { if ((resolved = map.containsKey(key))) { out = out.replace(match, Objects.toString(map.get(key))); break; } } } if (!resolved && !preserveKeys) { out = out.replace(match, key); } } in=out; } return out; } static Map<Object, Object> getSystemVars(); static String resolveContextVars(String in, Map<?,?> vMap); static String resolveEnvVars(String in); static String replaceKeys(String in, Pattern pattern, boolean preserveKeys, int passes, Map<?,?>... maps); static String replaceKeys(String in, Pattern p); static String resolveSystemVars(String in); static final Pattern CONTEXT_VARS; static final Pattern ENV_VARS; static final Pattern USER_VARS; } | @Test public void testReplaceKeysUserVariables() { System.out.println("replaceKeys"); String in = "this is a %scenario%/%testset% -> %testset%/%release% for %project%.%testcase%/%%release%%. "; boolean preserveKeys = true; String result; String expResult = "this is a myscn/ts -> ts/rel for pro.tc/%rel%. "; result = KeyMap.replaceKeys(in, KeyMap.USER_VARS, preserveKeys, 1, vMap); assertEquals(expResult, result); expResult = "this is a myscn/ts -> ts/rel for pro.tc/L2. "; result = KeyMap.replaceKeys(in, KeyMap.USER_VARS, preserveKeys, 2, vMap); assertEquals(expResult, result); }
@Test public void testReplaceKeys_String_Pattern() { System.out.println("replaceKeys"); String in = "${val.1}-${var.1}-${val.2}-${val.1}-${val.3}-${val.4}-${var.4}-${var.1}-${var.2}-"; String expResult = "1-x-b-1-c-val.4-var.4-x-y-"; String result = KeyMap.replaceKeys(in, KeyMap.ENV_VARS); assertEquals(expResult, result); } |
ChromeEmulators { public static String getPrefLocation() { if (SystemUtils.IS_OS_WINDOWS) { return SystemUtils.getUserHome().getAbsolutePath() + "/AppData/Local/Google/Chrome/User Data/Default"; } if (SystemUtils.IS_OS_MAC_OSX) { return SystemUtils.getUserHome().getAbsolutePath()+"/Library/Application Support/Google/Chrome/Default"; } if (SystemUtils.IS_OS_LINUX) { return SystemUtils.getUserHome().getAbsolutePath()+"/.config/google-chrome/Default"; } return "OSNotConfigured"; } static void sync(); static String getPrefLocation(); static List<String> getEmulatorsList(); } | @Test(enabled = false) public void testGetPrefLocation() { System.out.println("getPrefLocation"); File file = new File(ChromeEmulators.getPrefLocation(), "Preferences"); if (!file.exists()) { System.out.println(file.getAbsolutePath()); System.out.println("------------------------"); Stream.of(file.listFiles()) .map(File::getAbsolutePath).forEach(System.out::println); fail("Unable to fine preference file"); } } |
ChromeEmulators { public static void sync() { try { LOG.info("Trying to load emulators from Chrome Installation"); File file = new File(getPrefLocation(), "Preferences"); if (file.exists()) { Map map = MAPPER.readValue(file, Map.class); Map devtools = (Map) map.get("devtools"); Map prefs = (Map) devtools.get("preferences"); String stdemulators = (String) prefs.get("standardEmulatedDeviceList"); List list = MAPPER.readValue(stdemulators, List.class); EMULATORS.clear(); EMULATORS.addAll( (List<String>) list.stream() .map((device) -> { return ((Map) device).get("title"); }) .map((val) -> val.toString()) .collect(Collectors.toList())); saveList(); } else { LOG.severe("Either Chrome is not installed or OS not supported"); } } catch (IOException ex) { LOG.log(Level.SEVERE, null, ex); } } static void sync(); static String getPrefLocation(); static List<String> getEmulatorsList(); } | @Test(enabled = false) public void testSync() { System.out.println("sync"); ChromeEmulators.sync(); assertTrue(!ChromeEmulators.getEmulatorsList().isEmpty(), "EmulatorsList is Empty"); } |
ChromeEmulators { public static List<String> getEmulatorsList() { load(); return EMULATORS; } static void sync(); static String getPrefLocation(); static List<String> getEmulatorsList(); } | @Test(enabled = false) public void testGetEmulatorsList() { System.out.println("getEmulatorsList"); List<String> result = ChromeEmulators.getEmulatorsList(); assertTrue(Stream.of("Nexus 5", "Galaxy S5", "Nexus 6P", "iPhone 5", "iPhone 6 Plus") .allMatch(result::contains), "Some/all emulators missing in the EmulatorsList" ); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.