From 61b2fd21e6f623850ad8b5df9f0cec4a0c0908cc Mon Sep 17 00:00:00 2001 From: Craig Raw Date: Wed, 13 Oct 2021 15:20:22 +0200 Subject: [PATCH] add support for retrieving added nodes, refactor nodeRangeToString --- .../drongo/wallet/WalletNode.java | 74 ++++++++++++++++++- 1 file changed, 72 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/sparrowwallet/drongo/wallet/WalletNode.java b/src/main/java/com/sparrowwallet/drongo/wallet/WalletNode.java index d97cc17..fc699fd 100644 --- a/src/main/java/com/sparrowwallet/drongo/wallet/WalletNode.java +++ b/src/main/java/com/sparrowwallet/drongo/wallet/WalletNode.java @@ -130,11 +130,16 @@ public class WalletNode extends Persistable implements Comparable { return value; } - public synchronized void fillToIndex(int index) { + public synchronized Set fillToIndex(int index) { + Set newNodes = new TreeSet<>(); for(int i = 0; i <= index; i++) { WalletNode node = new WalletNode(getKeyPurpose(), i); - children.add(node); + if(children.add(node)) { + newNodes.add(node); + } } + + return newNodes; } /** @@ -245,4 +250,69 @@ public class WalletNode extends Persistable implements Comparable { return changed; } + + public static String nodeRangesToString(Set nodes) { + return nodeRangesToString(nodes.stream().map(WalletNode::getDerivationPath).collect(Collectors.toList())); + } + + public static String nodeRangesToString(Collection nodeDerivations) { + List sortedDerivations = new ArrayList<>(nodeDerivations); + + if(nodeDerivations.isEmpty()) { + return "[]"; + } + + List> contiguous = splitToContiguous(sortedDerivations); + + String abbrev = "["; + for(Iterator> iter = contiguous.iterator(); iter.hasNext(); ) { + List range = iter.next(); + abbrev += range.get(0); + if(range.size() > 1) { + abbrev += "-" + range.get(range.size() - 1); + } + if(iter.hasNext()) { + abbrev += ", "; + } + } + abbrev += "]"; + + return abbrev; + } + + private static List> splitToContiguous(List input) { + List> result = new ArrayList<>(); + int prev = 0; + + int keyPurpose = getKeyPurpose(input.get(0)); + int index = getIndex(input.get(0)); + + for (int cur = 0; cur < input.size(); cur++) { + if(getKeyPurpose(input.get(cur)) != keyPurpose || getIndex(input.get(cur)) != index) { + result.add(input.subList(prev, cur)); + prev = cur; + } + index = getIndex(input.get(cur)) + 1; + keyPurpose = getKeyPurpose(input.get(cur)); + } + result.add(input.subList(prev, input.size())); + + return result; + } + + private static int getKeyPurpose(String path) { + List childNumbers = KeyDerivation.parsePath(path); + if(childNumbers.isEmpty()) { + return -1; + } + return childNumbers.get(0).num(); + } + + private static int getIndex(String path) { + List childNumbers = KeyDerivation.parsePath(path); + if(childNumbers.isEmpty()) { + return -1; + } + return childNumbers.get(childNumbers.size() - 1).num(); + } }