gpt4 book ai didi

org.bitcoinj.wallet.WalletProtobufSerializer类的使用及代码示例

转载 作者:知者 更新时间:2024-03-24 23:17:05 28 4
gpt4 key购买 nike

本文整理了Java中org.bitcoinj.wallet.WalletProtobufSerializer类的一些代码示例,展示了WalletProtobufSerializer类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。WalletProtobufSerializer类的具体详情如下:
包路径:org.bitcoinj.wallet.WalletProtobufSerializer
类名称:WalletProtobufSerializer

WalletProtobufSerializer介绍

[英]Serialize and de-serialize a wallet to a byte stream containing a protocol buffer. Protocol buffers are a data interchange format developed by Google with an efficient binary representation, a type safe specification language and compilers that generate code to work with those data structures for many languages. Protocol buffers can have their format evolved over time: conceptually they represent data using (tag, length, value) tuples. The format is defined by the wallet.proto file in the bitcoinj source distribution.

This class is used through its static methods. The most common operations are writeWallet and readWallet, which do the obvious operations on Output/InputStreams. You can use a java.io.ByteArrayInputStream and equivalent java.io.ByteArrayOutputStream if you'd like byte arrays instead. The protocol buffer can also be manipulated in its object form if you'd like to modify the flattened data structure before serialization to binary.

You can extend the wallet format with additional fields specific to your application if you want, but make sure to either put the extra data in the provided extension areas, or select tag numbers that are unlikely to be used by anyone else.
[中]将钱包序列化并反序列化为包含protocol buffer的字节流。协议缓冲区是谷歌开发的一种数据交换格式,具有高效的二进制表示、类型安全规范语言和编译器,这些编译器生成代码,用于处理多种语言的数据结构。协议缓冲区的格式可以随着时间的推移而变化:从概念上讲,它们使用(标记、长度、值)元组表示数据。格式由钱包定义。bitcoinj源发行版中的原型文件。
此类通过其静态方法使用。最常见的操作是writeWallet和readWallet,它们对输出/输入流执行明显的操作。你可以使用java。伊奥。ByteArrayInputStream和等效java。伊奥。ByteArrayOutputStream,如果您想要字节数组的话。如果您想在序列化为二进制之前修改平坦的数据结构,还可以以对象形式操纵协议缓冲区。
如果需要,您可以使用特定于应用程序的其他字段扩展钱包格式,但请确保将额外数据放在提供的扩展区域中,或者选择其他人不太可能使用的标签号。

代码示例

代码示例来源:origin: cash.bitcoinj/bitcoinj-core

private Wallet loadWallet(boolean shouldReplayWallet) throws Exception {
  Wallet wallet;
  FileInputStream walletStream = new FileInputStream(vWalletFile);
  try {
    List<WalletExtension> extensions = provideWalletExtensions();
    WalletExtension[] extArray = extensions.toArray(new WalletExtension[extensions.size()]);
    Protos.Wallet proto = WalletProtobufSerializer.parseToProto(walletStream);
    final WalletProtobufSerializer serializer;
    if (walletFactory != null)
      serializer = new WalletProtobufSerializer(walletFactory);
    else
      serializer = new WalletProtobufSerializer();
    wallet = serializer.readWallet(params, extArray, proto);
    if (shouldReplayWallet)
      wallet.reset();
  } finally {
    walletStream.close();
  }
  return wallet;
}

代码示例来源:origin: greenaddress/GreenBits

private Wallet roundTrip(Wallet wallet) throws UnreadableWalletException {
  Protos.Wallet protos = new WalletProtobufSerializer().walletToProto(wallet);
  return new WalletProtobufSerializer().readWallet(PARAMS, null, protos);
}

代码示例来源:origin: greenaddress/GreenBits

private static Wallet roundTripClientWallet(Wallet wallet) throws Exception {
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  new WalletProtobufSerializer().writeWallet(wallet, bos);
  org.bitcoinj.wallet.Protos.Wallet proto = WalletProtobufSerializer.parseToProto(new ByteArrayInputStream(bos.toByteArray()));
  StoredPaymentChannelClientStates state = new StoredPaymentChannelClientStates(null, failBroadcaster);
  return new WalletProtobufSerializer().readWallet(wallet.getParams(), new WalletExtension[] { state }, proto);
}

代码示例来源:origin: greenaddress/GreenBits

/**
 * Uses protobuf serialization to save the wallet to the given file stream. To learn more about this file format, see
 * {@link WalletProtobufSerializer}.
 */
public void saveToFileStream(OutputStream f) throws IOException {
  lock.lock();
  try {
    new WalletProtobufSerializer().writeWallet(this, f);
  } finally {
    lock.unlock();
  }
}

代码示例来源:origin: fr.acinq/bitcoinj-core

/** Returns a wallet deserialized from the given input stream and wallet extensions. */
public static Wallet loadFromFileStream(InputStream stream, @Nullable WalletExtension... walletExtensions) throws UnreadableWalletException {
  Wallet wallet = new WalletProtobufSerializer().readWallet(stream, walletExtensions);
  if (!wallet.isConsistent()) {
    log.error("Loaded an inconsistent wallet");
  }
  return wallet;
}

代码示例来源:origin: fr.acinq/bitcoinj-core

readTransaction(txProto, wallet.getParams());
    WalletTransaction wtx = connectTransactionOutputs(params, txProto);
    wallet.addWalletTransaction(wtx);
    wallet.setLastBlockSeenHash(null);
  } else {
    wallet.setLastBlockSeenHash(byteStringToHash(walletProto.getLastSeenBlockHash()));
loadExtensions(wallet, extensions != null ? extensions : new WalletExtension[0], walletProto);

代码示例来源:origin: greenaddress/GreenBits

private static Wallet roundTrip(Wallet wallet) throws Exception {
  ByteArrayOutputStream output = new ByteArrayOutputStream();
  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);
}

代码示例来源:origin: fr.acinq/bitcoinj-core

Protos.Wallet walletProto = parseToProto(input);
  final String paramsID = walletProto.getNetworkIdentifier();
  NetworkParameters params = NetworkParameters.fromID(paramsID);
  if (params == null)
    throw new UnreadableWalletException("Unknown network parameters ID " + paramsID);
  return readWallet(params, extensions, walletProto, forceReset);
} catch (IOException e) {
  throw new UnreadableWalletException("Could not parse input stream to protobuf", e);

代码示例来源:origin: cash.bitcoinj/bitcoinj-core

Protos.Transaction txProto = makeTxProto(wtx);
  walletBuilder.addTransaction(txProto);
  walletBuilder.setLastSeenBlockHash(hashToByteString(lastSeenBlockHash));
  walletBuilder.setLastSeenBlockHeight(wallet.getLastBlockSeenHeight());
populateExtensions(wallet, walletBuilder);

代码示例来源:origin: cash.bitcoinj/bitcoinj-core

Protos.Transaction.Builder txBuilder = Protos.Transaction.newBuilder();
txBuilder.setPool(getProtoPool(wtx))
     .setHash(hashToByteString(tx.getHash()))
     .setVersion((int) tx.getVersion());
  Protos.TransactionInput.Builder inputBuilder = Protos.TransactionInput.newBuilder()
    .setScriptBytes(ByteString.copyFrom(input.getScriptBytes()))
    .setTransactionOutPointHash(hashToByteString(input.getOutpoint().getHash()))
    .setTransactionOutPointIndex((int) input.getOutpoint().getIndex());
  if (input.hasSequence())
    Sha256Hash spendingHash = spentBy.getParentTransaction().getHash();
    int spentByTransactionIndex = spentBy.getParentTransaction().getInputs().indexOf(spentBy);
    outputBuilder.setSpentByTransactionHash(hashToByteString(spendingHash))
           .setSpentByTransactionIndex(spentByTransactionIndex);
if (appearsInHashes != null) {
  for (Map.Entry<Sha256Hash, Integer> entry : appearsInHashes.entrySet()) {
    txBuilder.addBlockHash(hashToByteString(entry.getKey()));
    txBuilder.addBlockRelativityOffsets(entry.getValue());
  TransactionConfidence confidence = tx.getConfidence();
  Protos.TransactionConfidence.Builder confidenceBuilder = Protos.TransactionConfidence.newBuilder();
  writeConfidence(txBuilder, confidence, confidenceBuilder);

代码示例来源:origin: HashEngineering/dashj

Protos.Wallet proto = WalletProtobufSerializer.parseToProto(stream);
  proto = attemptHexConversion(proto);
  System.out.println(proto.toString());
  || (action == ActionEnum.SYNC
    && options.has("force"));
WalletProtobufSerializer loader = new WalletProtobufSerializer();
if (options.has("ignore-mandatory-extensions"))
  loader.setRequireMandatoryExtensions(false);
walletInputStream = new BufferedInputStream(new FileInputStream(walletFile));
wallet = loader.readWallet(walletInputStream, forceReset, (WalletExtension[])(null));
if (!wallet.getParams().equals(params)) {
  System.err.println("Wallet does not match requested network parameters: " +

代码示例来源:origin: fr.acinq/bitcoinj-core

/**
 * <p>Loads wallet data from the given protocol buffer and inserts it into the given Wallet object. This is primarily
 * useful when you wish to pre-register extension objects. Note that if loading fails the provided Wallet object
 * may be in an indeterminate state and should be thrown away.</p>
 *
 * <p>A wallet can be unreadable for various reasons, such as inability to open the file, corrupt data, internally
 * inconsistent data, a wallet extension marked as mandatory that cannot be handled and so on. You should always
 * handle {@link UnreadableWalletException} and communicate failure to the user in an appropriate manner.</p>
 *
 * @throws UnreadableWalletException thrown in various error conditions (see description).
 */
public Wallet readWallet(InputStream input, @Nullable WalletExtension... walletExtensions) throws UnreadableWalletException {
  return readWallet(input, false, walletExtensions);
}

代码示例来源:origin: greenaddress/GreenBits

@Test
public void testLastBlockSeenHash() throws Exception {
  // Test the lastBlockSeenHash field works.
  // LastBlockSeenHash should be empty if never set.
  Wallet wallet = new Wallet(PARAMS);
  Protos.Wallet walletProto = new WalletProtobufSerializer().walletToProto(wallet);
  ByteString lastSeenBlockHash = walletProto.getLastSeenBlockHash();
  assertTrue(lastSeenBlockHash.isEmpty());
  // Create a block.
  Block block = PARAMS.getDefaultSerializer().makeBlock(BlockTest.blockBytes);
  Sha256Hash blockHash = block.getHash();
  wallet.setLastBlockSeenHash(blockHash);
  wallet.setLastBlockSeenHeight(1);
  // Roundtrip the wallet and check it has stored the blockHash.
  Wallet wallet1 = roundTrip(wallet);
  assertEquals(blockHash, wallet1.getLastBlockSeenHash());
  assertEquals(1, wallet1.getLastBlockSeenHeight());
  // Test the Satoshi genesis block (hash of all zeroes) is roundtripped ok.
  Block genesisBlock = MainNetParams.get().getGenesisBlock();
  wallet.setLastBlockSeenHash(genesisBlock.getHash());
  Wallet wallet2 = roundTrip(wallet);
  assertEquals(genesisBlock.getHash(), wallet2.getLastBlockSeenHash());
}

代码示例来源:origin: HashEngineering/dashj

if (spendingTx == null) {
    throw new UnreadableWalletException(String.format(Locale.US, "Could not connect %s to %s",
        tx.getHashAsString(), byteStringToHash(spentByTransactionHash)));
Protos.TransactionConfidence confidenceProto = txProto.getConfidence();
TransactionConfidence confidence = tx.getConfidence();
readConfidence(params, tx, confidenceProto, confidence);

代码示例来源:origin: cash.bitcoinj/bitcoinj-core

/**
 * Formats the given wallet (transactions and keys) to the given output stream in protocol buffer format.<p>
 *
 * Equivalent to <tt>walletToProto(wallet).writeTo(output);</tt>
 */
public void writeWallet(Wallet wallet, OutputStream output) throws IOException {
  Protos.Wallet walletProto = walletToProto(wallet);
  walletProto.writeTo(output);
}

代码示例来源:origin: fr.acinq/bitcoinj-core

confidenceBuilder.setOverridingTransaction(hashToByteString(overridingHash));

代码示例来源:origin: cash.bitcoinj/bitcoinj-core

TransactionOutPoint outpoint = new TransactionOutPoint(params,
      inputProto.getTransactionOutPointIndex() & 0xFFFFFFFFL,
      byteStringToHash(inputProto.getTransactionOutPointHash())
  );
  Coin value = inputProto.hasValue() ? Coin.valueOf(inputProto.getValue()) : null;
  if (txProto.getBlockRelativityOffsetsCount() > 0)
    relativityOffset = txProto.getBlockRelativityOffsets(i);
  tx.addBlockAppearance(byteStringToHash(blockHash), relativityOffset);
Sha256Hash protoHash = byteStringToHash(txProto.getHash());
if (!tx.getHash().equals(protoHash))
  throw new UnreadableWalletException(String.format(Locale.US, "Transaction did not deserialize completely: %s vs %s", tx.getHash(), protoHash));
if (txMap.containsKey(txProto.getHash()))
  throw new UnreadableWalletException("Wallet contained duplicate transaction " + byteStringToHash(txProto.getHash()));
txMap.put(txProto.getHash(), tx);

代码示例来源:origin: cash.bitcoinj/bitcoinj-core

readTransaction(txProto, wallet.getParams());
    WalletTransaction wtx = connectTransactionOutputs(params, txProto);
    wallet.addWalletTransaction(wtx);
    wallet.setLastBlockSeenHash(null);
  } else {
    wallet.setLastBlockSeenHash(byteStringToHash(walletProto.getLastSeenBlockHash()));
loadExtensions(wallet, extensions != null ? extensions : new WalletExtension[0], walletProto);

代码示例来源:origin: greenaddress/GreenBits

/** Returns a wallet deserialized from the given input stream and wallet extensions. */
public static Wallet loadFromFileStream(InputStream stream, @Nullable WalletExtension... walletExtensions) throws UnreadableWalletException {
  Wallet wallet = new WalletProtobufSerializer().readWallet(stream, walletExtensions);
  if (!wallet.isConsistent()) {
    log.error("Loaded an inconsistent wallet");
  }
  return wallet;
}

代码示例来源:origin: greenaddress/GreenBits

Protos.Wallet walletProto = parseToProto(input);
  final String paramsID = walletProto.getNetworkIdentifier();
  NetworkParameters params = NetworkParameters.fromID(paramsID);
  if (params == null)
    throw new UnreadableWalletException("Unknown network parameters ID " + paramsID);
  return readWallet(params, extensions, walletProto, forceReset);
} catch (IOException e) {
  throw new UnreadableWalletException("Could not parse input stream to protobuf", e);

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com