Skip to content

Commit

Permalink
SPVBlockStore: compare magic header as bytes, not string
Browse files Browse the repository at this point in the history
This gets rid of several bytes to/from string conversions.
  • Loading branch information
schildbach committed Jul 12, 2024
1 parent 77de868 commit a13783d
Showing 1 changed file with 9 additions and 7 deletions.
16 changes: 9 additions & 7 deletions core/src/main/java/org/bitcoinj/store/SPVBlockStore.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package org.bitcoinj.store;

import org.bitcoinj.base.internal.ByteUtils;
import org.bitcoinj.core.Block;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.ProtocolException;
Expand Down Expand Up @@ -59,6 +60,8 @@ public class SPVBlockStore implements BlockStore {
public static final int DEFAULT_CAPACITY = 10000;
@Deprecated
public static final String HEADER_MAGIC = "SPVB";
// Magic header.
private static final byte[] MAGIC_HEADER = HEADER_MAGIC.getBytes(StandardCharsets.US_ASCII);

protected volatile MappedByteBuffer buffer;
protected final NetworkParameters params;
Expand Down Expand Up @@ -158,10 +161,10 @@ else if (fileLength < randomAccessFile.length())

// Check or initialize the header bytes to ensure we don't try to open some random file.
if (exists) {
byte[] header = new byte[4];
buffer.get(header);
if (!new String(header, StandardCharsets.US_ASCII).equals(HEADER_MAGIC))
throw new BlockStoreException("Header bytes do not equal " + HEADER_MAGIC);
byte[] currentHeader = new byte[4];
buffer.get(currentHeader);
if (!Arrays.equals(currentHeader, MAGIC_HEADER))
throw new BlockStoreException("Magic header expected, got: " + ByteUtils.formatHex(currentHeader));
} else {
initNewStore(params.getGenesisBlock());
}
Expand All @@ -176,9 +179,8 @@ else if (fileLength < randomAccessFile.length())
}

private void initNewStore(Block genesisBlock) throws Exception {
byte[] header;
header = HEADER_MAGIC.getBytes(StandardCharsets.US_ASCII);
buffer.put(header);
((Buffer) buffer).rewind();
buffer.put(MAGIC_HEADER);
// Insert the genesis block.
lock.lock();
try {
Expand Down

0 comments on commit a13783d

Please sign in to comment.