src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
BridgeSerializationUtils { public static byte[] serializeOneOffLockWhitelist(Pair<List<OneOffWhiteListEntry>, Integer> data) { List<OneOffWhiteListEntry> entries = data.getLeft(); Integer disableBlockHeight = data.getRight(); int serializationSize = entries.size() * 2 + 1; byte[][] serializedLockWhitelist = new byte[se... | @Test public void serializeLockWhitelist() throws Exception { byte[][] addressesBytes = new byte[][]{ BtcECKey.fromPrivate(BigInteger.valueOf(100)).getPubKeyHash(), BtcECKey.fromPrivate(BigInteger.valueOf(200)).getPubKeyHash(), BtcECKey.fromPrivate(BigInteger.valueOf(300)).getPubKeyHash(), BtcECKey.fromPrivate(BigInteg... |
BridgeSerializationUtils { public static Pair<HashMap<Address, OneOffWhiteListEntry>, Integer> deserializeOneOffLockWhitelistAndDisableBlockHeight(byte[] data, NetworkParameters parameters) { if (data == null || data.length == 0) { return null; } RLPList rlpList = (RLPList)RLP.decode2(data).get(0); int serializedAddres... | @Test public void deserializeOneOffLockWhitelistAndDisableBlockHeight() throws Exception { byte[][] addressesBytes = Arrays.asList(100, 200, 300, 400).stream() .map(k -> BtcECKey.fromPrivate(BigInteger.valueOf(k))) .sorted(BtcECKey.PUBKEY_COMPARATOR) .map(k -> k.getPubKeyHash()) .toArray(byte[][]::new); byte[][] rlpByt... |
BridgeSerializationUtils { public static byte[] serializeReleaseRequestQueue(ReleaseRequestQueue queue) { List<ReleaseRequestQueue.Entry> entries = queue.getEntriesWithoutHash(); byte[][] bytes = new byte[entries.size() * 2][]; int n = 0; for (ReleaseRequestQueue.Entry entry : entries) { bytes[n++] = RLP.encodeElement(... | @Test public void serializeRequestQueue() throws Exception { List<ReleaseRequestQueue.Entry> sampleEntries = Arrays.asList( new ReleaseRequestQueue.Entry(mockAddressHash160("ccdd"), Coin.valueOf(10)), new ReleaseRequestQueue.Entry(mockAddressHash160("bb"), Coin.valueOf(50)), new ReleaseRequestQueue.Entry(mockAddressHas... |
BridgeSerializationUtils { public static List<ReleaseRequestQueue.Entry> deserializeReleaseRequestQueue(byte[] data, NetworkParameters networkParameters) { return deserializeReleaseRequestQueue(data, networkParameters, false); } private BridgeSerializationUtils(); static byte[] serializeMap(SortedMap<Keccak256, BtcTra... | @Test public void deserializeRequestQueue_emptyOrNull() throws Exception { assertEquals(0, BridgeSerializationUtils.deserializeReleaseRequestQueue(null, NetworkParameters.fromID(NetworkParameters.ID_REGTEST)).size()); assertEquals(0, BridgeSerializationUtils.deserializeReleaseRequestQueue(new byte[]{}, NetworkParameter... |
BridgeSerializationUtils { public static byte[] serializeReleaseTransactionSet(ReleaseTransactionSet set) { List<ReleaseTransactionSet.Entry> entries = set.getEntriesWithoutHash().stream().collect(Collectors.toList()); entries.sort(ReleaseTransactionSet.Entry.BTC_TX_COMPARATOR); byte[][] bytes = new byte[entries.size()... | @Test public void serializeTransactionSet() throws Exception { Set<ReleaseTransactionSet.Entry> sampleEntries = new HashSet<>(Arrays.asList( new ReleaseTransactionSet.Entry(mockBtcTransactionSerialize("ccdd"), 10L), new ReleaseTransactionSet.Entry(mockBtcTransactionSerialize("bb"), 20L), new ReleaseTransactionSet.Entry... |
BridgeSerializationUtils { public static ReleaseTransactionSet deserializeReleaseTransactionSet(byte[] data, NetworkParameters networkParameters) { return deserializeReleaseTransactionSet(data, networkParameters, false); } private BridgeSerializationUtils(); static byte[] serializeMap(SortedMap<Keccak256, BtcTransacti... | @Test public void deserializeTransactionSet_emptyOrNull() throws Exception { assertEquals(0, BridgeSerializationUtils.deserializeReleaseTransactionSet(null, NetworkParameters.fromID(NetworkParameters.ID_REGTEST)).getEntries().size()); assertEquals(0, BridgeSerializationUtils.deserializeReleaseTransactionSet(new byte[]{... |
Value { public boolean isEmpty() { if (isNull()) { return true; } if (isBytes() && asBytes().length == 0) { return true; } if (isList() && asList().isEmpty()) { return true; } if (isString() && asString().equals("")) { return true; } return false; } Value(); Value(Object obj); static Value fromRlpEncoded(byte[] data);... | @Test public void isEmpty_Array() { Value val = new Value(new String[0]); assertTrue(val.isEmpty()); }
@Test public void isEmpty_Null() { Value val = new Value(null); assertTrue(val.isEmpty()); }
@Test public void isEmpty_EmptyString() { Value val = new Value(""); assertTrue(val.isEmpty()); }
@Test public void isEmpty_... |
BridgeSerializationUtils { public static byte[] serializeInteger(Integer value) { return RLP.encodeBigInteger(BigInteger.valueOf(value)); } private BridgeSerializationUtils(); static byte[] serializeMap(SortedMap<Keccak256, BtcTransaction> map); static SortedMap<Keccak256, BtcTransaction> deserializeMap(byte[] data, N... | @Test public void serializeInteger() { Assert.assertEquals(BigInteger.valueOf(123), RLP.decodeBigInteger(BridgeSerializationUtils.serializeInteger(123), 0)); Assert.assertEquals(BigInteger.valueOf(1200), RLP.decodeBigInteger(BridgeSerializationUtils.serializeInteger(1200), 0)); } |
BridgeSerializationUtils { public static Integer deserializeInteger(byte[] data) { return RLP.decodeBigInteger(data, 0).intValue(); } private BridgeSerializationUtils(); static byte[] serializeMap(SortedMap<Keccak256, BtcTransaction> map); static SortedMap<Keccak256, BtcTransaction> deserializeMap(byte[] data, Network... | @Test public void deserializeInteger() { Assert.assertEquals(123, BridgeSerializationUtils.deserializeInteger(RLP.encodeBigInteger(BigInteger.valueOf(123))).intValue()); Assert.assertEquals(1200, BridgeSerializationUtils.deserializeInteger(RLP.encodeBigInteger(BigInteger.valueOf(1200))).intValue()); } |
LockWhitelist { public Integer getSize() { return whitelistedAddresses.size(); } LockWhitelist(Map<Address, LockWhitelistEntry> whitelistedAddresses); LockWhitelist(Map<Address, LockWhitelistEntry> whitelistedAddresses, int disableBlockHeight); boolean isWhitelisted(Address address); boolean isWhitelisted(byte[] addre... | @Test public void getSize() { Assert.assertEquals(4, whitelist.getSize().intValue()); } |
LockWhitelist { public List<Address> getAddresses() { return new ArrayList<>(whitelistedAddresses.keySet()); } LockWhitelist(Map<Address, LockWhitelistEntry> whitelistedAddresses); LockWhitelist(Map<Address, LockWhitelistEntry> whitelistedAddresses, int disableBlockHeight); boolean isWhitelisted(Address address); bool... | @Test public void getAddresses() { Assert.assertNotSame(whitelist.getAddresses(), addresses); Assert.assertThat(whitelist.getAddresses(), containsInAnyOrder(addresses.keySet().toArray())); } |
LockWhitelist { public boolean isWhitelisted(Address address) { return whitelistedAddresses.containsKey(address); } LockWhitelist(Map<Address, LockWhitelistEntry> whitelistedAddresses); LockWhitelist(Map<Address, LockWhitelistEntry> whitelistedAddresses, int disableBlockHeight); boolean isWhitelisted(Address address);... | @Test public void isWhitelisted() { for (Address address : addresses.keySet()) { assertExistance(address, true); } Address randomAddress = Address.fromBase58( NetworkParameters.fromID(NetworkParameters.ID_REGTEST), "n3PLxDiwWqa5uH7fSbHCxS6VAjD9Y7Rwkj" ); assertExistance(randomAddress, false); } |
LockWhitelist { public boolean put(Address address, LockWhitelistEntry entry) { if (whitelistedAddresses.containsKey(address)) { return false; } whitelistedAddresses.put(address, entry); return true; } LockWhitelist(Map<Address, LockWhitelistEntry> whitelistedAddresses); LockWhitelist(Map<Address, LockWhitelistEntry> ... | @Test public void addOneOff() { Address randomAddress = Address.fromBase58( NetworkParameters.fromID(NetworkParameters.ID_REGTEST), "n3WzdjG7S2GjDbY1pJYxsY1VSQDkm4KDcm" ); assertExistance(randomAddress, false); Assert.assertTrue(whitelist.put(randomAddress, new OneOffWhiteListEntry(randomAddress, Coin.CENT))); assertEx... |
LockWhitelist { public boolean remove(Address address) { return whitelistedAddresses.remove(address) != null; } LockWhitelist(Map<Address, LockWhitelistEntry> whitelistedAddresses); LockWhitelist(Map<Address, LockWhitelistEntry> whitelistedAddresses, int disableBlockHeight); boolean isWhitelisted(Address address); boo... | @Test public void remove() { Assert.assertTrue(whitelist.isWhitelisted(existingAddress)); Assert.assertTrue(whitelist.isWhitelisted(existingAddress.getHash160())); Assert.assertTrue(whitelist.remove(existingAddress)); Assert.assertFalse(whitelist.isWhitelisted(existingAddress)); Assert.assertFalse(whitelist.isWhitelist... |
LockWhitelist { public void consume(Address address) { LockWhitelistEntry entry = whitelistedAddresses.get(address); if (entry == null) { return; } entry.consume(); if (entry.isConsumed()) { this.remove(address); } } LockWhitelist(Map<Address, LockWhitelistEntry> whitelistedAddresses); LockWhitelist(Map<Address, LockW... | @Test public void consume() { assertExistance(existingAddress, true); whitelist.consume(existingAddress); assertExistance(existingAddress, false); Assert.assertFalse(whitelist.remove(existingAddress)); }
@Test public void cantLockOneOffAfterConsume() { Address randomAddress = Address.fromBase58( NetworkParameters.fromI... |
RLP { public static byte[] decodeIP4Bytes(byte[] data, int index) { int offset = 1; final byte[] result = new byte[4]; for (int i = 0; i < 4; i++) { result[i] = decodeOneByteItem(data, index + offset); if ((data[index + offset] & 0xFF) > OFFSET_SHORT_ITEM) { offset += 2; } else { offset += 1; } } return result; } stat... | @Test public void test1() throws UnknownHostException { String peersPacket = "F8 4E 11 F8 4B C5 36 81 " + "CC 0A 29 82 76 5F B8 40 D8 D6 0C 25 80 FA 79 5C " + "FC 03 13 EF DE BA 86 9D 21 94 E7 9E 7C B2 B5 22 " + "F7 82 FF A0 39 2C BB AB 8D 1B AC 30 12 08 B1 37 " + "E0 DE 49 98 33 4F 3B CF 73 FA 11 7E F2 13 F8 74 " + "1... |
LockWhitelist { public <T extends LockWhitelistEntry> List<T> getAll(Class<T> type) { return whitelistedAddresses.values().stream() .filter(e -> e.getClass() == type) .map(type::cast) .collect(Collectors.toList()); } LockWhitelist(Map<Address, LockWhitelistEntry> whitelistedAddresses); LockWhitelist(Map<Address, LockW... | @Test public void getAllByType() { Assert.assertArrayEquals( addresses.values().stream().filter(e -> e.getClass() == OneOffWhiteListEntry.class).map(e-> e.address()).sorted().toArray(), whitelist.getAll(OneOffWhiteListEntry.class).stream().map(e-> e.address()).toArray() ); Assert.assertArrayEquals( addresses.values().s... |
CoinbaseInformation { public Sha256Hash getWitnessMerkleRoot() { return witnessMerkleRoot; } CoinbaseInformation(Sha256Hash witnessMerkleRoot); Sha256Hash getWitnessMerkleRoot(); } | @Test public void getWitnessMerkleRoot() { Sha256Hash secondHashTx = Sha256Hash.wrap(Hex.decode("e3d0840a0825fb7d880e5cb8306745352920a8c7e8a30fac882b275e26c6bb65")); Sha256Hash witnessRoot = MerkleTreeUtils.combineLeftRight(Sha256Hash.ZERO_HASH, secondHashTx); CoinbaseInformation instance = new CoinbaseInformation(witn... |
BridgeStorageProvider { public Federation getNewFederation() { if (newFederation != null) { return newFederation; } Optional<Integer> storageVersion = getStorageVersion(NEW_FEDERATION_FORMAT_VERSION); newFederation = safeGetFromRepository(NEW_FEDERATION_KEY, data -> data == null ? null : deserializeFederationAccordingT... | @Test public void getNewFederation_initialVersion() throws IOException { List<Integer> storageCalls = new ArrayList<>(); List<Integer> deserializeCalls = new ArrayList<>(); Federation newFederation = buildMockFederation(100, 200, 300); PowerMockito.mockStatic(BridgeSerializationUtils.class); Repository repositoryMock =... |
BridgeStorageProvider { public Federation getOldFederation() { if (oldFederation != null || shouldSaveOldFederation) { return oldFederation; } Optional<Integer> storageVersion = getStorageVersion(OLD_FEDERATION_FORMAT_VERSION); oldFederation = safeGetFromRepository(OLD_FEDERATION_KEY, data -> data == null ? null : dese... | @Test public void getOldFederation_initialVersion() throws IOException { List<Integer> storageCalls = new ArrayList<>(); List<Integer> deserializeCalls = new ArrayList<>(); Federation oldFederation = buildMockFederation(100, 200, 300); PowerMockito.mockStatic(BridgeSerializationUtils.class); Repository repositoryMock =... |
RLP { public static int decodeInt(byte[] data, int index) { int value = 0; if ((data[index] & 0xFF) < OFFSET_SHORT_ITEM) { return data[index]; } else if ((data[index] & 0xFF) >= OFFSET_SHORT_ITEM && (data[index] & 0xFF) < OFFSET_LONG_ITEM) { byte length = (byte) (data[index] - OFFSET_SHORT_ITEM); byte pow = (byte) (len... | @Test public void test2() throws UnknownHostException { String peersPacket = "F8 4E 11 F8 4B C5 36 81 " + "CC 0A 29 82 76 5F B8 40 D8 D6 0C 25 80 FA 79 5C " + "FC 03 13 EF DE BA 86 9D 21 94 E7 9E 7C B2 B5 22 " + "F7 82 FF A0 39 2C BB AB 8D 1B AC 30 12 08 B1 37 " + "E0 DE 49 98 33 4F 3B CF 73 FA 11 7E F2 13 F8 74 " + "1... |
BridgeStorageProvider { public PendingFederation getPendingFederation() { if (pendingFederation != null || shouldSavePendingFederation) { return pendingFederation; } Optional<Integer> storageVersion = getStorageVersion(PENDING_FEDERATION_FORMAT_VERSION); pendingFederation = safeGetFromRepository(PENDING_FEDERATION_KEY,... | @Test public void getPendingFederation_initialVersion() throws IOException { List<Integer> storageCalls = new ArrayList<>(); List<Integer> deserializeCalls = new ArrayList<>(); PendingFederation pendingFederation = buildMockPendingFederation(100, 200, 300); PowerMockito.mockStatic(BridgeSerializationUtils.class); Repos... |
BridgeStorageProvider { public ABICallElection getFederationElection(AddressBasedAuthorizer authorizer) { if (federationElection != null) { return federationElection; } federationElection = safeGetFromRepository(FEDERATION_ELECTION_KEY, data -> (data == null)? new ABICallElection(authorizer) : BridgeSerializationUtils.... | @Test public void getFederationElection_nonNullBytes() throws IOException { List<Integer> calls = new ArrayList<>(); AddressBasedAuthorizer authorizerMock = mock(AddressBasedAuthorizer.class); ABICallElection electionMock = mock(ABICallElection.class); PowerMockito.mockStatic(BridgeSerializationUtils.class); Repository... |
BridgeStorageProvider { public void saveFederationElection() { if (federationElection == null) { return; } safeSaveToRepository(FEDERATION_ELECTION_KEY, federationElection, BridgeSerializationUtils::serializeElection); } BridgeStorageProvider(Repository repository, RskAddress contractAddress, BridgeConstants bridgeCons... | @Test public void saveFederationElection() throws IOException { ABICallElection electionMock = mock(ABICallElection.class); List<Integer> storageBytesCalls = new ArrayList<>(); List<Integer> serializeCalls = new ArrayList<>(); PowerMockito.mockStatic(BridgeSerializationUtils.class); Repository repositoryMock = mock(Rep... |
RLP { public static byte[] encodeByte(byte singleByte) { if ((singleByte & 0xFF) == 0) { return new byte[]{(byte) OFFSET_SHORT_ITEM}; } else if ((singleByte & 0xFF) <= 0x7F) { return new byte[]{singleByte}; } else { return new byte[]{(byte) (OFFSET_SHORT_ITEM + 1), singleByte}; } } static int decodeInt(byte[] data, in... | @Test public void test4() { byte[] expected = {(byte) 0x80}; byte[] data = encodeByte((byte) 0); assertArrayEquals(expected, data); byte[] expected2 = {(byte) 0x78}; data = encodeByte((byte) 120); assertArrayEquals(expected2, data); byte[] expected3 = {(byte) 0x7F}; data = encodeByte((byte) 127); assertArrayEquals(expe... |
BridgeStorageProvider { public LockWhitelist getLockWhitelist() { if (lockWhitelist != null) { return lockWhitelist; } Pair<HashMap<Address, OneOffWhiteListEntry>, Integer> oneOffWhitelistAndDisableBlockHeightData = safeGetFromRepository(LOCK_ONE_OFF_WHITELIST_KEY, data -> BridgeSerializationUtils.deserializeOneOffLock... | @Test public void getLockWhitelist_nonNullBytes() { List<Integer> calls = new ArrayList<>(); LockWhitelist whitelistMock = new LockWhitelist(new HashMap<>()); LockWhitelistEntry oneOffEntry = new OneOffWhiteListEntry(getBtcAddress("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"), Coin.COIN); LockWhitelistEntry unlimitedEntr... |
BridgeStorageProvider { public void saveLockWhitelist() { if (lockWhitelist == null) { return; } List<OneOffWhiteListEntry> oneOffEntries = lockWhitelist.getAll(OneOffWhiteListEntry.class); safeSaveToRepository(LOCK_ONE_OFF_WHITELIST_KEY, Pair.of(oneOffEntries, lockWhitelist.getDisableBlockHeight()), BridgeSerializatio... | @Test public void saveLockWhitelist() { LockWhitelist whitelistMock = mock(LockWhitelist.class); List<Integer> storageBytesCalls = new ArrayList<>(); List<Integer> serializeCalls = new ArrayList<>(); PowerMockito.mockStatic(BridgeSerializationUtils.class); Repository repositoryMock = mock(Repository.class); BridgeStora... |
BridgeStorageProvider { public ReleaseRequestQueue getReleaseRequestQueue() throws IOException { if (releaseRequestQueue != null) { return releaseRequestQueue; } List<ReleaseRequestQueue.Entry> entries = new ArrayList<>(); entries.addAll(getFromRepository( RELEASE_REQUEST_QUEUE, data -> BridgeSerializationUtils.deseria... | @Test public void getReleaseRequestQueue_before_rskip_146_activation() throws IOException { Repository repositoryMock = mock(Repository.class); BridgeStorageProvider storageProvider = new BridgeStorageProvider(repositoryMock, mockAddress("aabbccdd"), config.getNetworkConstants().getBridgeConstants(), activationsBeforeF... |
BridgeStorageProvider { public ReleaseTransactionSet getReleaseTransactionSet() throws IOException { if (releaseTransactionSet != null) { return releaseTransactionSet; } Set<ReleaseTransactionSet.Entry> entries = new HashSet<>(getFromRepository(RELEASE_TX_SET, data -> BridgeSerializationUtils.deserializeReleaseTransact... | @Test public void getReleaseTransactionSet_before_rskip_146_activation() throws IOException { Repository repositoryMock = mock(Repository.class); BridgeStorageProvider storageProvider = new BridgeStorageProvider(repositoryMock, mockAddress("aabbccdd"), config.getNetworkConstants().getBridgeConstants(), activationsBefor... |
BridgeStorageProvider { public ABICallElection getFeePerKbElection(AddressBasedAuthorizer authorizer) { if (feePerKbElection != null) { return feePerKbElection; } feePerKbElection = safeGetFromRepository(FEE_PER_KB_ELECTION_KEY, data -> BridgeSerializationUtils.deserializeElection(data, authorizer)); return feePerKbEle... | @Test public void getFeePerKbElection_emptyVotes() { AddressBasedAuthorizer authorizerMock = mock(AddressBasedAuthorizer.class); Repository repositoryMock = mock(Repository.class); BridgeStorageProvider storageProvider = new BridgeStorageProvider(repositoryMock, mockAddress("aabbccdd"), config.getNetworkConstants().get... |
BridgeStorageProvider { public Coin getLockingCap() { if (activations.isActive(RSKIP134)) { if (this.lockingCap == null) { this.lockingCap = safeGetFromRepository(LOCKING_CAP_KEY, BridgeSerializationUtils::deserializeCoin); } return this.lockingCap; } return null; } BridgeStorageProvider(Repository repository, RskAddre... | @Test public void getLockingCap_before_fork() { Repository repository = mock(Repository.class); when(repository.getStorageBytes(PrecompiledContracts.BRIDGE_ADDR, DataWord.fromString("lockingCap"))).thenReturn(new byte[] { 1 }); BridgeStorageProvider provider0 = new BridgeStorageProvider( repository, PrecompiledContract... |
RLP { public static byte[] encodeShort(short singleShort) { if ((singleShort & 0xFF) == singleShort) { return encodeByte((byte) singleShort); } else { return new byte[]{(byte) (OFFSET_SHORT_ITEM + 2), (byte) (singleShort >> 8 & 0xFF), (byte) (singleShort >> 0 & 0xFF)}; } } static int decodeInt(byte[] data, int index);... | @Test public void test5() { byte[] expected = {(byte) 0x80}; byte[] data = encodeShort((byte) 0); assertArrayEquals(expected, data); byte[] expected2 = {(byte) 0x78}; data = encodeShort((byte) 120); assertArrayEquals(expected2, data); byte[] expected3 = { (byte) 0x7F}; data = encodeShort((byte) 127); assertArrayEquals(... |
BridgeStorageProvider { public Optional<Long> getHeightIfBtcTxhashIsAlreadyProcessed(Sha256Hash btcTxHash) throws IOException { Map<Sha256Hash, Long> processed = getBtcTxHashesAlreadyProcessed(); if (processed.containsKey(btcTxHash)) { return Optional.of(processed.get(btcTxHash)); } if (!activations.isActive(RSKIP134))... | @Test public void getHeightIfBtcTxhashIsAlreadyProcessed_before_RSKIP134_does_not_use_new_storage() throws IOException { Repository repository = mock(Repository.class); Sha256Hash hash = Sha256Hash.ZERO_HASH; HashMap<Sha256Hash, Long> hashes = new HashMap<>(); hashes.put(hash, 1L); when(repository.getStorageBytes(Preco... |
BridgeStorageProvider { public void saveHeightBtcTxHashAlreadyProcessed() { if (btcTxHashesToSave == null) { return; } btcTxHashesToSave.forEach((btcTxHash, height) -> safeSaveToRepository(getStorageKeyForBtcTxHashAlreadyProcessed(btcTxHash), height, BridgeSerializationUtils::serializeLong) ); } BridgeStorageProvider(R... | @Test public void saveHeightBtcTxHashAlreadyProcessed() throws IOException { Repository repository = mock(Repository.class); Sha256Hash hash = Sha256Hash.ZERO_HASH; BridgeStorageProvider provider0 = new BridgeStorageProvider( repository, PrecompiledContracts.BRIDGE_ADDR, config.getNetworkConstants().getBridgeConstants(... |
BridgeStorageProvider { public CoinbaseInformation getCoinbaseInformation(Sha256Hash blockHash) { if (!activations.isActive(RSKIP143)) { return null; } if (coinbaseInformationMap == null) { coinbaseInformationMap = new HashMap<>(); } if (coinbaseInformationMap.containsKey(blockHash)) { return coinbaseInformationMap.get... | @Test public void getCoinBaseInformation_before_RSKIP143() { Repository repository = mock(Repository.class); Sha256Hash hash = Sha256Hash.ZERO_HASH; BridgeStorageProvider provider = new BridgeStorageProvider( repository, PrecompiledContracts.BRIDGE_ADDR, config.getNetworkConstants().getBridgeConstants(), activationsBef... |
Federation { public List<FederationMember> getMembers() { return members; } Federation(List<FederationMember> members, Instant creationTime, long creationBlockNumber, NetworkParameters btcParams); List<FederationMember> getMembers(); List<BtcECKey> getBtcPublicKeys(); int getNumberOfSignaturesRequired(); Instant getCr... | @Test public void membersImmutable() { boolean exception = false; try { federation.getMembers().add(new FederationMember(new BtcECKey(), new ECKey(), new ECKey())); } catch (Exception e) { exception = true; } Assert.assertTrue(exception); exception = false; try { federation.getMembers().remove(0); } catch (Exception e)... |
Federation { @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || this.getClass() != other.getClass()) { return false; } Federation otherFederation = (Federation) other; return this.getNumberOfSignaturesRequired() == otherFederation.getNumberOfSignaturesRequired() && ... | @Test public void testEquals_basic() { Assert.assertTrue(federation.equals(federation)); Assert.assertFalse(federation.equals(null)); Assert.assertFalse(federation.equals(new Object())); Assert.assertFalse(federation.equals("something else")); }
@Test public void testEquals_differentNumberOfMembers() { Federation other... |
RLP { public static byte[] encodeInt(int singleInt) { if ((singleInt & 0xFF) == singleInt) { return encodeByte((byte) singleInt); } else if ((singleInt & 0xFFFF) == singleInt) { return encodeShort((short) singleInt); } else if ((singleInt & 0xFFFFFF) == singleInt) { return new byte[]{(byte) (OFFSET_SHORT_ITEM + 3), (by... | @Test public void testEncodeInt() { byte[] expected = {(byte) 0x80}; byte[] data = encodeInt(0); assertArrayEquals(expected, data); assertEquals(0, RLP.decodeInt(data, 0)); byte[] expected2 = {(byte) 0x78}; data = encodeInt(120); assertArrayEquals(expected2, data); assertEquals(120, RLP.decodeInt(data, 0)); byte[] expe... |
Federation { public Integer getBtcPublicKeyIndex(BtcECKey key) { for (int i = 0; i < members.size(); i++) { if (Arrays.equals(key.getPubKey(), members.get(i).getBtcPublicKey().getPubKey())) { return i; } } return null; } Federation(List<FederationMember> members, Instant creationTime, long creationBlockNumber, Network... | @Test public void getBtcPublicKeyIndex() { for (int i = 0; i < federation.getBtcPublicKeys().size(); i++) { Assert.assertEquals(i, federation.getBtcPublicKeyIndex(sortedPublicKeys.get(i)).intValue()); } Assert.assertNull(federation.getBtcPublicKeyIndex(BtcECKey.fromPrivate(BigInteger.valueOf(1234)))); } |
Federation { public boolean hasBtcPublicKey(BtcECKey key) { return getBtcPublicKeyIndex(key) != null; } Federation(List<FederationMember> members, Instant creationTime, long creationBlockNumber, NetworkParameters btcParams); List<FederationMember> getMembers(); List<BtcECKey> getBtcPublicKeys(); int getNumberOfSignatu... | @Test public void hasBtcPublicKey() { for (int i = 0; i < federation.getBtcPublicKeys().size(); i++) { Assert.assertTrue(federation.hasBtcPublicKey(sortedPublicKeys.get(i))); } Assert.assertFalse(federation.hasBtcPublicKey(BtcECKey.fromPrivate(BigInteger.valueOf(1234)))); } |
Federation { public boolean hasMemberWithRskAddress(byte[] address) { return members.stream() .anyMatch(m -> Arrays.equals(m.getRskPublicKey().getAddress(), address)); } Federation(List<FederationMember> members, Instant creationTime, long creationBlockNumber, NetworkParameters btcParams); List<FederationMember> getMe... | @Test public void hasMemberWithRskAddress() { for (int i = 0; i < federation.getBtcPublicKeys().size(); i++) { Assert.assertTrue(federation.hasMemberWithRskAddress(rskAddresses.get(i))); } byte[] nonFederateRskAddress = ECKey.fromPrivate(BigInteger.valueOf(1234)).getAddress(); Assert.assertFalse(federation.hasMemberWit... |
Federation { @Override public String toString() { return String.format("%d of %d signatures federation", getNumberOfSignaturesRequired(), members.size()); } Federation(List<FederationMember> members, Instant creationTime, long creationBlockNumber, NetworkParameters btcParams); List<FederationMember> getMembers(); List... | @Test public void testToString() { Assert.assertEquals("4 of 6 signatures federation", federation.toString()); } |
Federation { public boolean isMember(FederationMember federationMember){ return this.members.contains(federationMember); } Federation(List<FederationMember> members, Instant creationTime, long creationBlockNumber, NetworkParameters btcParams); List<FederationMember> getMembers(); List<BtcECKey> getBtcPublicKeys(); int... | @Test public void isMember(){ FederationMember federationMember = federation.getMembers().get(0); Assert.assertTrue(federation.isMember(federationMember)); byte[] b = new byte[20]; new Random().nextBytes(b); ECKey invalidRskKey = ECKey.fromPrivate(b); BtcECKey invalidBtcKey = BtcECKey.fromPrivate(b); FederationMember i... |
RLP { public static byte[] encodeBigInteger(BigInteger srcBigInteger) { if (srcBigInteger.equals(BigInteger.ZERO)) { return encodeByte((byte) 0); } else { return encodeElement(asUnsignedByteArray(srcBigInteger)); } } static int decodeInt(byte[] data, int index); static BigInteger decodeBigInteger(byte[] data, int inde... | @Test public void test6() { byte[] expected = new byte[]{(byte) 0x80}; byte[] data = encodeBigInteger(BigInteger.ZERO); assertArrayEquals(expected, data); }
@Test public void testEncodeBigInteger() { BigInteger test = new BigInteger("100102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", 16); String expecte... |
BridgeUtils { public static boolean isLockTx(BtcTransaction tx, List<Federation> federations, Context btcContext, BridgeConstants bridgeConstants) { for (int i = 0; i < tx.getInputs().size(); i++) { final int index = i; if (federations.stream().anyMatch(federation -> scriptCorrectlySpendsTx(tx, index, federation.getP2S... | @Test public void testIsLock() { NetworkParameters params = RegTestParams.get(); Context btcContext = new Context(params); BridgeRegTestConstants bridgeConstants = BridgeRegTestConstants.getInstance(); Federation federation = bridgeConstants.getGenesisFederation(); Wallet wallet = new BridgeBtcWallet(btcContext, Collec... |
RLP { public static byte[] encodeString(String srcString) { return encodeElement(srcString.getBytes(StandardCharsets.UTF_8)); } static int decodeInt(byte[] data, int index); static BigInteger decodeBigInteger(byte[] data, int index); static byte[] decodeIP4Bytes(byte[] data, int index); static int getFirstListElement(... | @Test public void test7() { byte[] data = encodeString(""); assertArrayEquals(new byte[]{(byte) 0x80}, data); byte[] expected = {(byte) 0x90, (byte) 0x45, (byte) 0x74, (byte) 0x68, (byte) 0x65, (byte) 0x72, (byte) 0x65, (byte) 0x75, (byte) 0x6D, (byte) 0x4A, (byte) 0x20, (byte) 0x43, (byte) 0x6C, (byte) 0x69, (byte) 0x... |
BridgeUtils { public static boolean txIsProcessable(BtcLockSender.TxType txType, ActivationConfig.ForBlock activations) { return txType == BtcLockSender.TxType.P2PKH || activations.isActive(ConsensusRule.RSKIP143); } static Wallet getFederationNoSpendWallet(Context btcContext, Federation federation); static Wallet get... | @Test public void testTxIsProcessable() { ActivationConfig.ForBlock actForBlock = mock(ActivationConfig.ForBlock.class); when(actForBlock.isActive(ConsensusRule.RSKIP143)).thenReturn(false); assertTrue(BridgeUtils.txIsProcessable(BtcLockSender.TxType.P2PKH, actForBlock)); assertFalse(BridgeUtils.txIsProcessable(BtcLock... |
BridgeUtils { public static boolean isMigrationTx(BtcTransaction btcTx, Federation activeFederation, Federation retiringFederation, Context btcContext, BridgeConstants bridgeConstants) { if (retiringFederation == null) { return false; } boolean moveFromRetiring = isReleaseTx(btcTx, retiringFederation); boolean moveToAc... | @Test public void testIsMigrationTx() { BridgeRegTestConstants bridgeConstants = BridgeRegTestConstants.getInstance(); NetworkParameters parameters = bridgeConstants.getBtcParams(); Context btcContext = new Context(parameters); List<BtcECKey> activeFederationKeys = Stream.of( BtcECKey.fromPrivate(Hex.decode("fa01")), B... |
BridgeUtils { public static Address recoverBtcAddressFromEthTransaction(org.ethereum.core.Transaction tx, NetworkParameters networkParameters) { org.ethereum.crypto.ECKey key = tx.getKey(); byte[] pubKey = key.getPubKey(true); return BtcECKey.fromPublicOnly(pubKey).toAddress(networkParameters); } static Wallet getFede... | @Test public void getAddressFromEthTransaction() { org.ethereum.core.Transaction tx = new org.ethereum.core.Transaction(TO_ADDRESS, AMOUNT, NONCE, GAS_PRICE, GAS_LIMIT, DATA, constants.getChainId()); byte[] privKey = generatePrivKey(); tx.sign(privKey); Address expectedAddress = BtcECKey.fromPrivate(privKey).toAddress(... |
BridgeUtils { public static boolean hasEnoughSignatures(Context btcContext, BtcTransaction btcTx) { Context.propagate(btcContext); for (TransactionInput input : btcTx.getInputs()) { Script scriptSig = input.getScriptSig(); List<ScriptChunk> chunks = scriptSig.getChunks(); for (int i = 1; i < chunks.size(); i++) { Scrip... | @Test public void hasEnoughSignatures_two_signatures() { byte[] sign1 = new byte[]{0x79}; byte[] sign2 = new byte[]{0x78}; BtcTransaction btcTx = createReleaseTx(Arrays.asList(sign1, sign2), 1); Assert.assertTrue(BridgeUtils.hasEnoughSignatures(mock(Context.class), btcTx)); }
@Test public void hasEnoughSignatures_one_s... |
BridgeUtils { public static int countMissingSignatures(Context btcContext, BtcTransaction btcTx) { Context.propagate(btcContext); int unsigned = 0; TransactionInput input = btcTx.getInput(0); Script scriptSig = input.getScriptSig(); List<ScriptChunk> chunks = scriptSig.getChunks(); for (int i = 1; i < chunks.size() - 1... | @Test public void countMissingSignatures_two_signatures() { byte[] sign1 = new byte[]{0x79}; byte[] sign2 = new byte[]{0x78}; BtcTransaction btcTx = createReleaseTx(Arrays.asList(sign1, sign2), 1); Assert.assertEquals(0, BridgeUtils.countMissingSignatures(mock(Context.class), btcTx)); }
@Test public void countMissingSi... |
RLP { public static byte[] encodeElement(@Nullable byte[] srcData) { if (srcData == null || srcData.length == 0) { return new byte[]{(byte) OFFSET_SHORT_ITEM}; } else if (isSingleZero(srcData)) { return srcData; } else if (srcData.length == 1 && (srcData[0] & 0xFF) < OFFSET_SHORT_ITEM) { return srcData; } else if (srcD... | @Test public void test8() { String byteArr = "ce73660a06626c1b3fda7b18ef7ba3ce17b6bf604f9541d3c6c654b7ae88b239" + "407f659c78f419025d785727ed017b6add21952d7e12007373e321dbc31824ba"; byte[] byteArray = Hex.decode(byteArr); String expected = "b840" + byteArr; assertEquals(expected, ByteUtil.toHexString(encodeElement(byte... |
BridgeUtils { public static boolean isFreeBridgeTx(Transaction rskTx, Constants constants, ActivationConfig.ForBlock activations) { RskAddress receiveAddress = rskTx.getReceiveAddress(); if (receiveAddress.equals(RskAddress.nullAddress())) { return false; } BridgeConstants bridgeConstants = constants.getBridgeConstants... | @Test public void isFreeBridgeTxTrue() { activationConfig = ActivationConfigsForTest.bridgeUnitTest(); isFreeBridgeTx(true, PrecompiledContracts.BRIDGE_ADDR, BridgeRegTestConstants.REGTEST_FEDERATION_PRIVATE_KEYS.get(0).getPrivKeyBytes()); }
@Test public void isFreeBridgeTxOtherContract() { activationConfig = Activatio... |
BridgeUtils { public static Wallet getFederationNoSpendWallet(Context btcContext, Federation federation) { return getFederationsNoSpendWallet(btcContext, Collections.singletonList(federation)); } static Wallet getFederationNoSpendWallet(Context btcContext, Federation federation); static Wallet getFederationsNoSpendWal... | @Test public void getFederationNoSpendWallet() { NetworkParameters regTestParameters = NetworkParameters.fromID(NetworkParameters.ID_REGTEST); Federation federation = new Federation(FederationTestUtils.getFederationMembersWithBtcKeys(Arrays.asList( BtcECKey.fromPublicOnly(Hex.decode("036bb9eab797eadc8b697f0e82a01d01cab... |
BridgeUtils { public static Wallet getFederationSpendWallet(Context btcContext, Federation federation, List<UTXO> utxos) { return getFederationsSpendWallet(btcContext, Collections.singletonList(federation), utxos); } static Wallet getFederationNoSpendWallet(Context btcContext, Federation federation); static Wallet get... | @Test public void getFederationSpendWallet() throws UTXOProviderException { NetworkParameters regTestParameters = NetworkParameters.fromID(NetworkParameters.ID_REGTEST); Federation federation = new Federation(FederationTestUtils.getFederationMembersWithBtcKeys(Arrays.asList( BtcECKey.fromPublicOnly(Hex.decode("036bb9ea... |
RLP { public static byte[] encodeList(byte[]... elements) { if (elements == null) { return new byte[]{(byte) OFFSET_SHORT_LIST}; } int totalLength = 0; for (byte[] element1 : elements) { totalLength += element1.length; } byte[] data; int copyPos; if (totalLength < SIZE_THRESHOLD) { data = new byte[1 + totalLength]; dat... | @Test public void test9() { byte[] actuals = encodeList(); assertArrayEquals(new byte[]{(byte) 0xc0}, actuals); }
@Test public void encodeEdgeShortList() { String expectedOutput = "f7c0c0b4600160003556601359506301000000600035040f6018590060005660805460016080530160005760003560805760203560003557"; byte[] rlpKeysList = Hex... |
Web3Impl implements Web3 { @Override public String net_version() { String s = null; try { byte netVersion = config.getNetworkConstants().getChainId(); return s = Byte.toString(netVersion); } finally { if (logger.isDebugEnabled()) { logger.debug("net_version(): {}", s); } } } protected Web3Impl(
Ethereum et... | @Test public void net_version() throws Exception { Web3Impl web3 = createWeb3(); String netVersion = web3.net_version(); assertTrue("RSK net version different than expected", netVersion.compareTo(Byte.toString(config.getNetworkConstants().getChainId())) == 0); } |
BridgeUtils { private static boolean isReleaseTx(BtcTransaction tx, Federation federation) { return isReleaseTx(tx, Collections.singletonList(federation)); } static Wallet getFederationNoSpendWallet(Context btcContext, Federation federation); static Wallet getFederationsNoSpendWallet(Context btcContext, List<Federatio... | @Test public void testIsRelease() { NetworkParameters params = RegTestParams.get(); BridgeRegTestConstants bridgeConstants = BridgeRegTestConstants.getInstance(); Federation federation = bridgeConstants.getGenesisFederation(); List<BtcECKey> federationPrivateKeys = BridgeRegTestConstants.REGTEST_FEDERATION_PRIVATE_KEYS... |
BridgeUtils { public static boolean isContractTx(Transaction rskTx) { return rskTx.getClass() == org.ethereum.vm.program.InternalTransaction.class; } static Wallet getFederationNoSpendWallet(Context btcContext, Federation federation); static Wallet getFederationsNoSpendWallet(Context btcContext, List<Federation> feder... | @Test public void testIsContractTx() { Assert.assertFalse(BridgeUtils.isContractTx(new Transaction((byte[]) null, null, null, null, null, null))); Assert.assertTrue(BridgeUtils.isContractTx(new org.ethereum.vm.program.InternalTransaction(null, 0, 0, null, null, null, null, null, null, null, null))); } |
BridgeUtils { public static Coin getCoinFromBigInteger(BigInteger value) { if (value == null) { throw new BridgeIllegalArgumentException("value cannot be null"); } try { return Coin.valueOf(value.longValueExact()); } catch(ArithmeticException e) { throw new BridgeIllegalArgumentException(e.getMessage(), e); } } static... | @Test(expected = BridgeIllegalArgumentException.class) public void getCoinFromBigInteger_bigger_than_long_value() { BridgeUtils.getCoinFromBigInteger(new BigInteger("9223372036854775808")); }
@Test(expected = BridgeIllegalArgumentException.class) public void getCoinFromBigInteger_null_value() { BridgeUtils.getCoinFromB... |
BridgeUtils { public static boolean validateHeightAndConfirmations(int height, int btcBestChainHeight, int acceptableConfirmationsAmount, Sha256Hash btcTxHash) throws Exception { if (height < 0) { throw new Exception("Height can't be lower than 0"); } int confirmations = btcBestChainHeight - height + 1; if (confirmatio... | @Test(expected = Exception.class) public void validateHeightAndConfirmations_invalid_height() throws Exception { Assert.assertFalse(BridgeUtils.validateHeightAndConfirmations(-1, 0, 0, null)); }
@Test public void validateHeightAndConfirmation_insufficient_confirmations() throws Exception { Assert.assertFalse(BridgeUtil... |
BridgeUtils { public static Sha256Hash calculateMerkleRoot(NetworkParameters networkParameters, byte[] pmtSerialized, Sha256Hash btcTxHash) throws VerificationException{ PartialMerkleTree pmt = new PartialMerkleTree(networkParameters, pmtSerialized, 0); List<Sha256Hash> hashesInPmt = new ArrayList<>(); Sha256Hash merkl... | @Test(expected = Exception.class) public void calculateMerkleRoot_invalid_pmt() { NetworkParameters networkParameters = NetworkParameters.fromID(NetworkParameters.ID_REGTEST); BridgeUtils.calculateMerkleRoot(networkParameters, Hex.decode("ab"), null); }
@Test public void calculateMerkleRoot_hashes_not_in_pmt() { byte[]... |
BridgeUtils { public static void validateInputsCount(byte[] btcTxSerialized, boolean isActiveRskip) throws VerificationException.EmptyInputsOrOutputs { if (BtcTransactionFormatUtils.getInputsCount(btcTxSerialized) == 0) { if (isActiveRskip) { if (BtcTransactionFormatUtils.getInputsCountForSegwit(btcTxSerialized) == 0) ... | @Test(expected = VerificationException.class) public void validateInputsCount_active_rskip() { BridgeUtils.validateInputsCount(Hex.decode("00000000000100"), true); }
@Test(expected = VerificationException.class) public void validateInputsCount_inactive_rskip() { BridgeConstants bridgeConstants = BridgeRegTestConstants.... |
BridgeUtils { public static boolean isInputSignedByThisFederator(BtcECKey federatorPublicKey, Sha256Hash sighash, TransactionInput input) { List<ScriptChunk> chunks = input.getScriptSig().getChunks(); for (int j = 1; j < chunks.size() - 1; j++) { ScriptChunk chunk = chunks.get(j); if (chunk.data.length == 0) { continue... | @Test public void isInputSignedByThisFederator_isSigned() { NetworkParameters params = RegTestParams.get(); BtcECKey federator1Key = new BtcECKey(); BtcECKey federator2Key = new BtcECKey(); Federation federation = new Federation( FederationMember.getFederationMembersFromKeys(Arrays.asList(federator1Key, federator2Key))... |
MerkleTreeUtils { public static Sha256Hash combineLeftRight(Sha256Hash left, Sha256Hash right) { byte[] leftBytes = left.getBytes(); byte[] rightBytes = right.getBytes(); checkNotAValid64ByteTransaction(leftBytes, rightBytes); return Sha256Hash.wrapReversed( Sha256Hash.hashTwice( reverseBytes(leftBytes), 0, 32, reverse... | @Test public void combineLeftRight() { Assert.assertEquals( Sha256Hash.wrap("ceea4835dd23fae1978a3f6f3f0aa0171e018360272dd5b98d37550fbc978d01"), MerkleTreeUtils.combineLeftRight( Sha256Hash.wrap("b945b008fbc3f357db745909958b570773fc14575a36af8bbc195b484e21f366"), Sha256Hash.wrap("9880f57b6735152a8c6d4c7e1b3bc6434ee75e4... |
BtcTransactionFormatUtils { public static Sha256Hash calculateBtcTxHash(byte[] btcTxSerialized) { return Sha256Hash.wrapReversed(Sha256Hash.hashTwice(btcTxSerialized)); } static Sha256Hash calculateBtcTxHash(byte[] btcTxSerialized); static long getInputsCount(byte[] btcTxSerialized); static long getInputsCountForSegwi... | @Test public void calculateBtcTxHash() { BtcTransaction btcTransaction = new BtcTransaction(NetworkParameters.fromID(NetworkParameters.ID_REGTEST)); Assert.assertThat(BtcTransactionFormatUtils.calculateBtcTxHash(btcTransaction.bitcoinSerialize()), is(btcTransaction.getHash())); byte[] rawBtcTransaction = Hex.decode("02... |
BtcTransactionFormatUtils { public static long getInputsCount(byte[] btcTxSerialized) { VarInt inputsCounter = new VarInt(btcTxSerialized, 4); return inputsCounter.value; } static Sha256Hash calculateBtcTxHash(byte[] btcTxSerialized); static long getInputsCount(byte[] btcTxSerialized); static long getInputsCountForSeg... | @Test public void getInputsCount() { BtcTransaction btcTransaction = new BtcTransaction(NetworkParameters.fromID(NetworkParameters.ID_REGTEST)); Assert.assertThat(BtcTransactionFormatUtils.getInputsCount(btcTransaction.bitcoinSerialize()), is(0L)); byte[] rawBtcTransaction = Hex.decode("020000000418bc858998739dbb7e7676... |
BtcTransactionFormatUtils { public static long getInputsCountForSegwit(byte[] btcTxSerialized) { VarInt inputsCounter = new VarInt(btcTxSerialized, 4); if (inputsCounter.value != 0) { return -1; } inputsCounter = new VarInt(btcTxSerialized, 5); if (inputsCounter.value != 1) { return -1; } inputsCounter = new VarInt(btc... | @Test public void getInputsCountFromSegwitTx() { String rawTx = "020000000001017001d967a340069c0b169fcbeb9cb6e0d78a27c94a41acbce762abc695aefab10000000017160014c" + "fa63de9979e2a8005e6cb516b86202860ff3971ffffffff0200c2eb0b0000000017a914291a7ddc558810708149a731f39cd3c3" + "a8782cfd870896e1110000000017a91425a2e67511a0207... |
PartialMerkleTreeFormatUtils { public static VarInt getHashesCount(byte[] pmtSerialized) { return new VarInt(pmtSerialized, BLOCK_TRANSACTION_COUNT_LENGTH); } static VarInt getHashesCount(byte[] pmtSerialized); static VarInt getFlagBitsCount(byte[] pmtSerialized); static boolean hasExpectedSize(byte[] pmtSerialized); ... | @Test public void getHashesCount() { String pmtSerializedEncoded = "030000000279e7c0da739df8a00f12c0bff55e5438f530aa5859ff9874258cd7bad3fe709746aff89" + "7e6a851faa80120d6ae99db30883699ac0428fc7192d6c3fec0ca6409010d"; byte[] pmtSerialized = Hex.decode(pmtSerializedEncoded); Assert.assertThat(PartialMerkleTreeFormatUtil... |
PartialMerkleTreeFormatUtils { public static VarInt getFlagBitsCount(byte[] pmtSerialized) { VarInt hashesCount = getHashesCount(pmtSerialized); return new VarInt( pmtSerialized, Math.addExact( BLOCK_TRANSACTION_COUNT_LENGTH + hashesCount.getOriginalSizeInBytes(), Math.multiplyExact(Math.toIntExact(hashesCount.value), ... | @Test public void getFlagBitsCount() { String pmtSerializedEncoded = "030000000279e7c0da739df8a00f12c0bff55e5438f530aa5859ff9874258cd7bad3fe709746aff89" + "7e6a851faa80120d6ae99db30883699ac0428fc7192d6c3fec0ca6409010d"; byte[] pmtSerialized = Hex.decode(pmtSerializedEncoded); Assert.assertThat(PartialMerkleTreeFormatUt... |
PartialMerkleTreeFormatUtils { public static boolean hasExpectedSize(byte[] pmtSerialized) { try { VarInt hashesCount = getHashesCount(pmtSerialized); VarInt flagBitsCount = getFlagBitsCount(pmtSerialized); int declaredSize = Math.addExact(Math.addExact(BLOCK_TRANSACTION_COUNT_LENGTH + hashesCount.getOriginalSizeInByte... | @Test public void hasExpectedSize() { String pmtSerializedEncoded = "030000000279e7c0da739df8a00f12c0bff55e5438f530aa5859ff9874258cd7bad3fe709746aff89" + "7e6a851faa80120d6ae99db30883699ac0428fc7192d6c3fec0ca6409010d"; byte[] pmtSerialized = Hex.decode(pmtSerializedEncoded); Assert.assertThat(PartialMerkleTreeFormatUti... |
BridgeEventLoggerImpl implements BridgeEventLogger { public void logLockBtc(RskAddress receiver, BtcTransaction btcTx, Address senderBtcAddress, Coin amount) { CallTransaction.Function event = BridgeEvents.LOCK_BTC.getEvent(); byte[][] encodedTopicsInBytes = event.encodeEventTopics(receiver.toString()); List<DataWord> ... | @Test public void logLockBtc() { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); List<LogInfo> eventLogs = new LinkedList<>(); BridgeEventLogger eventLogger = new BridgeEventLoggerImpl(null, activations, eventLogs); Address senderAddress = mock(Address.class); when(senderAddress.toString(... |
BridgeEventLoggerImpl implements BridgeEventLogger { public void logUpdateCollections(Transaction rskTx) { if (activations.isActive(ConsensusRule.RSKIP146)) { logUpdateCollectionsInSolidityFormat(rskTx); } else { logUpdateCollectionsInRLPFormat(rskTx); } } BridgeEventLoggerImpl(BridgeConstants bridgeConstants, Activati... | @Test public void logUpdateCollectionsBeforeRskip146HardFork() { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); List<LogInfo> eventLogs = new LinkedList<>(); when(activations.isActive(ConsensusRule.RSKIP146)).thenReturn(false); BridgeEventLogger eventLogger = new BridgeEventLoggerImpl(nu... |
BridgeEventLoggerImpl implements BridgeEventLogger { public void logAddSignature(BtcECKey federatorPublicKey, BtcTransaction btcTx, byte[] rskTxHash) { if (activations.isActive(ConsensusRule.RSKIP146)) { ECKey key = ECKey.fromPublicOnly(federatorPublicKey.getPubKey()); String federatorRskAddress = ByteUtil.toHexString(... | @Test public void logAddSignatureBeforeRskip146HardFork() { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); List<LogInfo> eventLogs = new LinkedList<>(); when(activations.isActive(ConsensusRule.RSKIP146)).thenReturn(false); BridgeEventLogger eventLogger = new BridgeEventLoggerImpl(null, a... |
BridgeEventLoggerImpl implements BridgeEventLogger { public void logReleaseBtc(BtcTransaction btcTx, byte[] rskTxHash) { if (activations.isActive(ConsensusRule.RSKIP146)) { logReleaseBtcInSolidityFormat(btcTx, rskTxHash); } else { logReleaseBtcInRLPFormat(btcTx); } } BridgeEventLoggerImpl(BridgeConstants bridgeConstant... | @Test public void logReleaseBtcBeforeRskip146() { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); List<LogInfo> eventLogs = new LinkedList<>(); when(activations.isActive(ConsensusRule.RSKIP146)).thenReturn(false); BridgeEventLogger eventLogger = new BridgeEventLoggerImpl(null, activations... |
BridgeEventLoggerImpl implements BridgeEventLogger { public void logCommitFederation(Block executionBlock, Federation oldFederation, Federation newFederation) { if (activations.isActive(ConsensusRule.RSKIP146)) { logCommitFederationInSolidityFormat(executionBlock, oldFederation, newFederation); } else { logCommitFedera... | @Test public void logCommitFederationBeforeRskip146() { BridgeConstants constantsMock = mock(BridgeConstants.class); ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); List<LogInfo> eventLogs = new LinkedList<>(); when(activations.isActive(ConsensusRule.RSKIP146)).thenReturn(false); when(con... |
BridgeEventLoggerImpl implements BridgeEventLogger { public void logReleaseBtcRequested(byte[] rskTransactionHash, BtcTransaction btcTx, Coin amount) { CallTransaction.Function event = BridgeEvents.RELEASE_REQUESTED.getEvent(); byte[][] encodedTopicsInBytes = event.encodeEventTopics(rskTransactionHash, btcTx.getHash().... | @Test public void logReleaseBtcRequested() { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); List<LogInfo> eventLogs = new LinkedList<>(); when(activations.isActive(ConsensusRule.RSKIP146)).thenReturn(true); BridgeEventLogger eventLogger = new BridgeEventLoggerImpl(null, activations, even... |
ReleaseRequestQueue { public void add(Address destination, Coin amount, Keccak256 rskTxHash) { entries.add(new Entry(destination, amount, rskTxHash)); } ReleaseRequestQueue(List<Entry> entries); List<Entry> getEntriesWithoutHash(); List<Entry> getEntriesWithHash(); List<Entry> getEntries(); void add(Address destination... | @Test public void add() { Assert.assertFalse(queue.getEntries().contains(new ReleaseRequestQueue.Entry(mockAddress(10), Coin.valueOf(10)))); queue.add(mockAddress(10), Coin.valueOf(10), null); Assert.assertTrue(queue.getEntries().contains(new ReleaseRequestQueue.Entry(mockAddress(10), Coin.valueOf(10)))); } |
ReleaseRequestQueue { public void process(int maxIterations, Processor processor) { ListIterator<Entry> iterator = entries.listIterator(); List<Entry> toRetry = new ArrayList<>(); int i = 0; while (iterator.hasNext() && i < maxIterations) { Entry entry = iterator.next(); iterator.remove(); ++i; if (!processor.process(e... | @Test public void process() { class Indexer { public int index = 0; } Indexer idx = new Indexer(); queue.process(30, entry -> { assertEquals(entry, queueEntries.get(idx.index)); return idx.index++ % 2 == 0; }); assertEquals(5, idx.index); assertEquals(Arrays.asList( new ReleaseRequestQueue.Entry(mockAddress(5), Coin.CO... |
P2shP2wpkhBtcLockSender implements BtcLockSender { public boolean tryParse(BtcTransaction btcTx) { if (btcTx == null) { return false; } if (!btcTx.hasWitness()) { return false; } if (btcTx.getInput(0).getScriptBytes() == null) { return false; } if (btcTx.getInput(0).getScriptSig().getChunks().size() != 1) { return fals... | @Test public void doesnt_parse_if_transaction_is_null() { BtcLockSender btcLockSender = new P2shP2wpkhBtcLockSender(); Assert.assertFalse(btcLockSender.tryParse(null)); }
@Test public void doesnt_parse_if_transaction_doesnt_have_witness() { BtcTransaction btcTx = new BtcTransaction(networkParameters); BtcLockSender btc... |
RLP { public static void fullTraverse(byte[] msgData, int level, int startPos, int endPos, int levelToIndex, Queue<Integer> index) { try { if (msgData == null || msgData.length == 0) { return; } int pos = startPos; while (pos < endPos) { if (level == levelToIndex) { index.add(pos); } if ((msgData[pos] & 0xFF) >= OFFSET... | @Test public void test11() { String tx = "F86E12F86B80881BC16D674EC8000094CD2A3D9F938E13CD947EC05ABC7FE734DF8DD8268609184E72A00064801BA0C52C114D4F5A3BA904A9B3036E5E118FE0DBB987FE3955DA20F2CD8F6C21AB9CA06BA4C2874299A55AD947DBC98A25EE895AABF6B625C26C435E84BFD70EDF2F69"; byte[] payload = Hex.decode(tx); Queue<Integer> ind... |
P2shMultisigBtcLockSender implements BtcLockSender { public boolean tryParse(BtcTransaction btcTx) { if (btcTx == null) { return false; } if (btcTx.getInputs().size() == 0) { return false; } if (btcTx.getInput(0).getScriptBytes() == null) { return false; } Script scriptSig = btcTx.getInput(0).getScriptSig(); if (script... | @Test public void doesnt_parse_if_transaction_is_null() { BtcLockSender btcLockSender = new P2shMultisigBtcLockSender(); Assert.assertFalse(btcLockSender.tryParse(null)); }
@Test public void doesnt_parse_if_tx_doesnt_have_inputs() { BtcTransaction btcTx = new BtcTransaction(networkParameters); BtcLockSender btcLockSend... |
RLP { @Nonnull public static ArrayList<RLPElement> decode2(@CheckForNull byte[] msgData) { ArrayList<RLPElement> elements = new ArrayList<>(); if (msgData == null) { return elements; } int tlength = msgData.length; int position = 0; while (position < tlength) { Pair<RLPElement, Integer> next = decodeElement(msgData, po... | @Test public void test12() { String tx = "F86E12F86B80881BC16D674EC8000094CD2A3D9F938E13CD947EC05ABC7FE734DF8DD8268609184E72A00064801BA0C52C114D4F5A3BA904A9B3036E5E118FE0DBB987FE3955DA20F2CD8F6C21AB9CA06BA4C2874299A55AD947DBC98A25EE895AABF6B625C26C435E84BFD70EDF2F69"; byte[] payload = Hex.decode(tx); ArrayList<RLPEleme... |
P2shP2wshBtcLockSender implements BtcLockSender { public boolean tryParse(BtcTransaction btcTx) { if (btcTx == null) { return false; } if (!btcTx.hasWitness()) { return false; } if (btcTx.getInput(0).getScriptBytes() == null) { return false; } if (btcTx.getInput(0).getScriptSig().getChunks().size() != 1) { return false... | @Test public void doesnt_parse_if_transaction_is_null() { BtcLockSender btcLockSender = new P2shP2wshBtcLockSender(); Assert.assertFalse(btcLockSender.tryParse(null)); }
@Test public void doesnt_parse_if_transaction_doesnt_have_witness() { BtcTransaction btcTx = new BtcTransaction(networkParameters); BtcLockSender btcL... |
P2pkhBtcLockSender implements BtcLockSender { public boolean tryParse (BtcTransaction btcTx) { if (btcTx == null) { return false; } if (btcTx.getInputs().size() == 0) { return false; } if (btcTx.getInput(0).getScriptBytes() == null) { return false; } Script scriptSig = btcTx.getInput(0).getScriptSig(); if (scriptSig.ge... | @Test public void doesnt_parse_if_tx_is_null() { BtcLockSender btcLockSender = new P2pkhBtcLockSender(); Assert.assertFalse(btcLockSender.tryParse(null)); }
@Test public void doesnt_parse_if_tx_doesnt_have_inputs() { BtcTransaction btcTx = new BtcTransaction(networkParameters); BtcLockSender btcLockSender = new P2pkhBt... |
BtcLockSenderProvider { public Optional<BtcLockSender> tryGetBtcLockSender(BtcTransaction tx) { if (tx == null) { return Optional.empty(); } BtcLockSender result; result = new P2pkhBtcLockSender(); if (result.tryParse(tx)) { return Optional.of(result); } result = new P2shP2wpkhBtcLockSender(); if (result.tryParse(tx)) ... | @Test public void gets_null_if_btc_transaction_is_not_valid() { BtcLockSenderProvider provider = new BtcLockSenderProvider(); assertFalse(provider.tryGetBtcLockSender(null).isPresent()); assertFalse(provider.tryGetBtcLockSender(new BtcTransaction(params)).isPresent()); }
@Test public void gets_valid_sender_from_p2pkh_b... |
RepositoryBtcBlockStoreWithCache implements BtcBlockStoreWithCache { @Override public synchronized StoredBlock getChainHead() { byte[] ba = repository.getStorageBytes(contractAddress, DataWord.fromString(BLOCK_STORE_CHAIN_HEAD_KEY)); if (ba == null) { return null; } return byteArrayToStoredBlock(ba); } RepositoryBtcBlo... | @Test public void getChainHead_Test() throws BlockStoreException { BtcBlockStoreWithCache btcBlockStore = createBlockStore(); assertEquals(networkParameters.getGenesisBlock(), btcBlockStore.getChainHead().getHeader()); } |
RepositoryBtcBlockStoreWithCache implements BtcBlockStoreWithCache { @Override public NetworkParameters getParams() { return btcNetworkParams; } RepositoryBtcBlockStoreWithCache(NetworkParameters btcNetworkParams, Repository repository, Map<Sha256Hash, StoredBlock> cacheBlocks, RskAddress contractAddress); @Override sy... | @Test public void getParams_Test() { BtcBlockStoreWithCache btcBlockStore = createBlockStore(); assertEquals(networkParameters, btcBlockStore.getParams()); } |
FederationSupport { public Federation getActiveFederation() { switch (getActiveFederationReference()) { case NEW: return provider.getNewFederation(); case OLD: return provider.getOldFederation(); case GENESIS: default: return bridgeConstants.getGenesisFederation(); } } FederationSupport(BridgeConstants bridgeConstants,... | @Test public void whenNewFederationIsNullThenActiveFederationIsGenesisFederation() { Federation genesisFederation = getNewFakeFederation(0); when(provider.getNewFederation()) .thenReturn(null); when(bridgeConstants.getGenesisFederation()) .thenReturn(genesisFederation); assertThat(federationSupport.getActiveFederation(... |
FederationSupport { public byte[] getMemberPublicKeyOfType(List<FederationMember> members, int index, FederationMember.KeyType keyType, String errorPrefix) { if (index < 0 || index >= members.size()) { throw new IndexOutOfBoundsException(String.format("%s index must be between 0 and %d", errorPrefix, members.size() - 1... | @Test public void getMemberPublicKeyOfType() { BtcECKey btcKey0 = new BtcECKey(); ECKey rskKey0 = new ECKey(); ECKey mstKey0 = new ECKey(); BtcECKey btcKey1 = new BtcECKey(); ECKey rskKey1 = new ECKey(); ECKey mstKey1 = new ECKey(); List<FederationMember> members = Arrays.asList( new FederationMember(btcKey0, rskKey0, ... |
Bridge extends PrecompiledContracts.PrecompiledContract { @Override public byte[] execute(byte[] data) { try { if (rskTx == null) { throw new RuntimeException("Rsk Transaction is null"); } BridgeParsedData bridgeParsedData = parseData(data); if (bridgeParsedData == null) { String errorMessage = String.format("Invalid d... | @Test public void getLockingCap_before_RSKIP134_activation() { doReturn(false).when(activationConfig).isActive(eq(RSKIP134), anyLong()); BridgeSupport bridgeSupportMock = mock(BridgeSupport.class); Bridge bridge = getBridgeInstance(bridgeSupportMock); byte[] data = BridgeMethods.GET_LOCKING_CAP.getFunction().encode(new... |
FederationMember { @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || this.getClass() != other.getClass()) { return false; } FederationMember otherFederationMember = (FederationMember) other; return Arrays.equals(btcPublicKey.getPubKey(), otherFederationMember.btcPu... | @Test public void testEquals_basic() { Assert.assertTrue(member.equals(member)); Assert.assertFalse(member.equals(null)); Assert.assertFalse(member.equals(new Object())); Assert.assertFalse(member.equals("something else")); }
@Test public void testEquals_sameKeys() { FederationMember otherMember = new FederationMember(... |
RemascFeesPayer { public void payMiningFees(byte[] blockHash, Coin value, RskAddress toAddress, List<LogInfo> logs) { this.transferPayment(value, toAddress); this.logPayment(blockHash, value, toAddress, logs); } RemascFeesPayer(Repository repository, RskAddress contractAddress); List<ProgramSubtrace> getSubtraces(); vo... | @Test public void payMiningFees() { Repository repositoryMock = Mockito.mock(Repository.class); RemascFeesPayer feesPayer = new RemascFeesPayer(repositoryMock, PrecompiledContracts.REMASC_ADDR); byte[] blockHash = { 0x1, 0x2 }; Coin value = Coin.valueOf(7L); RskAddress toAddress = new RskAddress("6c386a4b26f73c802f3467... |
RemascStorageProvider { public Coin getRewardBalance() { if (rewardBalance != null) { return rewardBalance; } DataWord address = DataWord.fromString(REWARD_BALANCE_KEY); DataWord value = this.repository.getStorageValue(this.contractAddress, address); if (value == null) { return Coin.ZERO; } return new Coin(value.getDat... | @Test public void getDefautRewardBalance() { RskAddress accountAddress = randomAddress(); Repository repository = createRepository(); RemascStorageProvider provider = new RemascStorageProvider(repository, accountAddress); Assert.assertEquals(Coin.ZERO, provider.getRewardBalance()); } |
RLP { public static byte[] encode(Object input) { Value val = new Value(input); if (val.isList()) { List<Object> inputArray = val.asList(); if (inputArray.isEmpty()) { return encodeLength(inputArray.size(), OFFSET_SHORT_LIST); } byte[] output = ByteUtil.EMPTY_BYTE_ARRAY; for (Object object : inputArray) { output = conc... | @Test(expected = RuntimeException.class) public void testEncodeNull() { encode(null); }
@Test public void testRlpEncode() { assertEquals(result01, ByteUtil.toHexString(encode(test01))); assertEquals(result02, ByteUtil.toHexString(encode(test02))); assertEquals(result03, ByteUtil.toHexString(encode(test03))); assertEqua... |
RemascStorageProvider { public Coin getBurnedBalance() { if (burnedBalance != null) { return burnedBalance; } DataWord address = DataWord.fromString(BURNED_BALANCE_KEY); DataWord value = this.repository.getStorageValue(this.contractAddress, address); if (value == null) { return Coin.ZERO; } return new Coin(value.getDat... | @Test public void getDefautBurnedBalance() { RskAddress accountAddress = randomAddress(); Repository repository = createRepository(); RemascStorageProvider provider = new RemascStorageProvider(repository, accountAddress); Assert.assertEquals(Coin.ZERO, provider.getBurnedBalance()); } |
RemascStorageProvider { public Boolean getBrokenSelectionRule() { if (brokenSelectionRule!= null) { return brokenSelectionRule; } DataWord address = DataWord.fromString(BROKEN_SELECTION_RULE_KEY); byte[] bytes = this.repository.getStorageBytes(this.contractAddress, address); if (bytes == null || bytes.length == 0) { re... | @Test public void getDefaultBrokenSelectionRule() { RskAddress accountAddress = randomAddress(); Repository repository = createRepository(); RemascStorageProvider provider = new RemascStorageProvider(repository, accountAddress); Assert.assertEquals(Boolean.FALSE, provider.getBrokenSelectionRule()); } |
RemascStorageProvider { public Coin getFederationBalance() { if (federationBalance != null) { return federationBalance ; } DataWord address = DataWord.fromString(FEDERATION_BALANCE_KEY); DataWord value = this.repository.getStorageValue(this.contractAddress, address); if (value == null) { return Coin.ZERO; } return new ... | @Test public void alwaysPaysFedBeforeRFS() throws IOException { RskSystemProperties config = spy(new TestSystemProperties()); when(config.getActivationConfig()).thenReturn(ActivationConfigsForTest.allBut(ConsensusRule.RSKIP85)); long minerFee = 21000; long txValue = 10000; long gasPrice = 1L; BlockChainBuilder builder ... |
RemascFederationProvider { public int getFederationSize() { return this.federationSupport.getFederationSize(); } RemascFederationProvider(
ActivationConfig activationConfig,
BridgeConstants bridgeConstants,
Repository repository,
Block processingBlock); int getFederationS... | @Test public void getDefaultFederationSize() { RemascFederationProvider provider = getRemascFederationProvider(); Assert.assertEquals(3, provider.getFederationSize()); } |
RemascFederationProvider { public RskAddress getFederatorAddress(int n) { byte[] publicKey = this.federationSupport.getFederatorBtcPublicKey(n); return new RskAddress(ECKey.fromPublicOnly(publicKey).getAddress()); } RemascFederationProvider(
ActivationConfig activationConfig,
BridgeConstants bri... | @Test public void getFederatorAddress() { RemascFederationProvider provider = getRemascFederationProvider(); byte[] address = provider.getFederatorAddress(0).getBytes(); Assert.assertNotNull(address); Assert.assertEquals(20, address.length); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.