3
0
mirror of https://github.com/Qortal/altcoinj.git synced 2025-02-07 14:54:15 +00:00

Cheap test to see if an input stream is a wallet.

This commit is contained in:
Andreas Schildbach 2014-04-05 23:07:01 +02:00
parent 918ceb8f55
commit e640d1eec3
2 changed files with 44 additions and 0 deletions

View File

@ -1,5 +1,6 @@
/**
* Copyright 2012 Google Inc.
* Copyright 2014 Andreas Schildbach
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -25,7 +26,10 @@ import com.google.bitcoin.script.Script;
import com.google.bitcoin.wallet.WalletTransaction;
import com.google.common.collect.Lists;
import com.google.protobuf.ByteString;
import com.google.protobuf.CodedInputStream;
import com.google.protobuf.TextFormat;
import com.google.protobuf.WireFormat;
import org.bitcoinj.wallet.Protos;
import org.bitcoinj.wallet.Protos.Wallet.EncryptionType;
import org.slf4j.Logger;
@ -693,4 +697,25 @@ public class WalletProtobufSerializer {
default: confidence.setSource(TransactionConfidence.Source.UNKNOWN); break;
}
}
/**
* Cheap test to see if input stream is a wallet. This checks for a magic value at the beginning of the stream.
*
* @param is
* input stream to test
* @return true if input stream is a wallet
*/
public static boolean isWallet(InputStream is) {
try {
final CodedInputStream cis = CodedInputStream.newInstance(is);
final int tag = cis.readTag();
final int field = WireFormat.getTagFieldNumber(tag);
if (field != 1) // network_identifier
return false;
final String network = cis.readString();
return NetworkParameters.fromID(network) != null;
} catch (IOException x) {
return false;
}
}
}

View File

@ -1,3 +1,20 @@
/**
* Copyright 2012 Google Inc.
* Copyright 2014 Andreas Schildbach
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.bitcoin.store;
@ -246,6 +263,8 @@ public class WalletProtobufSerializerTest {
ByteArrayOutputStream output = new ByteArrayOutputStream();
//System.out.println(WalletProtobufSerializer.walletToText(wallet));
new WalletProtobufSerializer().writeWallet(wallet, output);
ByteArrayInputStream test = new ByteArrayInputStream(output.toByteArray());
assertTrue(WalletProtobufSerializer.isWallet(test));
ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
return new WalletProtobufSerializer().readWallet(input);
}