Skip to content

Commit

Permalink
Script: two private constructors for clarity
Browse files Browse the repository at this point in the history
This also makes parameter validation more consistent.
  • Loading branch information
msgilligan authored and schildbach committed Sep 25, 2024
1 parent 55c71b4 commit caaec74
Showing 1 changed file with 18 additions and 10 deletions.
28 changes: 18 additions & 10 deletions core/src/main/java/org/bitcoinj/script/Script.java
Original file line number Diff line number Diff line change
Expand Up @@ -247,9 +247,7 @@ public static Script of(List<ScriptChunk> chunks) {
* @return script that wraps the chunks
*/
public static Script of(List<ScriptChunk> chunks, Instant creationTime) {
chunks = Collections.unmodifiableList(new ArrayList<>(chunks)); // defensive copy
Objects.requireNonNull(creationTime);
return new Script(null, chunks, creationTime);
return new Script(chunks, creationTime);
}

/**
Expand All @@ -275,10 +273,7 @@ public static Script parse(byte[] program) throws ScriptException {
* @throws ScriptException if the program could not be parsed
*/
public static Script parse(byte[] program, Instant creationTime) throws ScriptException {
Objects.requireNonNull(creationTime);
program = Arrays.copyOf(program, program.length); // defensive copy
List<ScriptChunk> chunks = parseIntoChunks(program);
return new Script(program, chunks, creationTime);
return new Script(program, creationTime);
}

/**
Expand Down Expand Up @@ -340,9 +335,22 @@ private static void parseIntoChunksPartial(byte[] program, List<ScriptChunk> chu
}
}

private Script(byte[] programBytes, List<ScriptChunk> chunks, Instant creationTime) {
this.program = programBytes;
this.chunks = chunks;

// When constructing from a program, we store both program and chunks
private Script(byte[] program, Instant creationTime) {
Objects.requireNonNull(program);
Objects.requireNonNull(creationTime);
this.program = Arrays.copyOf(program, program.length); // defensive copy;
this.chunks = parseIntoChunks(this.program);
this.creationTime = creationTime;
}

// When constructing from chunks, we store only chunks, and generate program when getter is called
private Script(List<ScriptChunk> chunks, Instant creationTime) {
Objects.requireNonNull(chunks);
Objects.requireNonNull(creationTime);
this.program = null;
this.chunks = Collections.unmodifiableList(new ArrayList<>(chunks)); // defensive copy
this.creationTime = creationTime;
}

Expand Down

0 comments on commit caaec74

Please sign in to comment.