|
| 1 | +/* |
| 2 | + * Copyright 2019 Blockchain Technology Partners Licensed under the Apache License, Version 2.0 (the |
| 3 | + * "License"); you may not use this file except in compliance with the License. You may obtain a |
| 4 | + * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable |
| 5 | + * law or agreed to in writing, software distributed under the License is distributed on an "AS IS" |
| 6 | + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License |
| 7 | + * for the specific language governing permissions and limitations under the License. |
| 8 | + * ------------------------------------------------------------------------------ |
| 9 | + */ |
| 10 | +package com.blockchaintp.sawtooth; |
| 11 | + |
| 12 | +import static org.bitcoinj.core.Utils.HEX; |
| 13 | +import static sawtooth.sdk.processor.Utils.hash512; |
| 14 | + |
| 15 | +import java.nio.charset.StandardCharsets; |
| 16 | +import java.security.SecureRandom; |
| 17 | +import java.util.Collection; |
| 18 | + |
| 19 | +import com.blockchaintp.keymanager.KeyManager; |
| 20 | +import com.blockchaintp.utils.VersionedEnvelopeUtils; |
| 21 | +import com.google.protobuf.ByteString; |
| 22 | + |
| 23 | +import org.slf4j.Logger; |
| 24 | +import org.slf4j.LoggerFactory; |
| 25 | + |
| 26 | +import sawtooth.sdk.messaging.Future; |
| 27 | +import sawtooth.sdk.messaging.Stream; |
| 28 | +import sawtooth.sdk.protobuf.Batch; |
| 29 | +import sawtooth.sdk.protobuf.BatchHeader; |
| 30 | +import sawtooth.sdk.protobuf.ClientBatchSubmitRequest; |
| 31 | +import sawtooth.sdk.protobuf.Message; |
| 32 | +import sawtooth.sdk.protobuf.Transaction; |
| 33 | +import sawtooth.sdk.protobuf.TransactionHeader; |
| 34 | + |
| 35 | +/** |
| 36 | + * Utility methods and constants useful for interacting with Sawtooth as a |
| 37 | + * client. |
| 38 | + */ |
| 39 | +public final class SawtoothClientUtils { |
| 40 | + |
| 41 | + |
| 42 | + private SawtoothClientUtils() { |
| 43 | + } |
| 44 | + |
| 45 | + /** |
| 46 | + * A SecureRandom for use in creating batches. |
| 47 | + */ |
| 48 | + private static SecureRandom secureRandom; |
| 49 | + private static int randomBytesGenerated; |
| 50 | + |
| 51 | + private static final Logger LOGGER = LoggerFactory.getLogger(SawtoothClientUtils.class); |
| 52 | + |
| 53 | + private static final int MAX_BYTES_PER_SEED = 10 * 1024 * 1024; |
| 54 | + |
| 55 | + /** |
| 56 | + * Create a batch. Transaction passed are specified to be processed in order. |
| 57 | + * |
| 58 | + * @param keyManager A key manager handling the identity to be used for signing |
| 59 | + * etc. |
| 60 | + * @param txns a collection of transactions |
| 61 | + * @return the assembled batch |
| 62 | + */ |
| 63 | + public static Batch makeSawtoothBatch(final KeyManager keyManager, final Collection<Transaction> txns) { |
| 64 | + BatchHeader.Builder batchHeaderBldr = BatchHeader.newBuilder().clearSignerPublicKey() |
| 65 | + .setSignerPublicKey(keyManager.getPublicKeyInHex()); |
| 66 | + for (Transaction tx : txns) { |
| 67 | + batchHeaderBldr.addTransactionIds(tx.getHeaderSignature()); |
| 68 | + } |
| 69 | + var batchHeader = batchHeaderBldr.build(); |
| 70 | + String signedHeader = keyManager.sign(batchHeader.toByteArray()); |
| 71 | + return Batch.newBuilder().setHeader(batchHeader.toByteString()).setHeaderSignature(signedHeader) |
| 72 | + .addAllTransactions(txns).build(); |
| 73 | + } |
| 74 | + |
| 75 | + /** |
| 76 | + * Make a sawtooth transaction based on the provided parameters. |
| 77 | + * |
| 78 | + * @param keyManager a keymanager to provide the necessary identity |
| 79 | + * info |
| 80 | + * @param familyName the family name |
| 81 | + * @param familyVersion the family version |
| 82 | + * @param inputAddresses state addresses required for input to this |
| 83 | + * transaction |
| 84 | + * @param outputAddresses state addresses this transaction will output |
| 85 | + * to |
| 86 | + * @param dependentTransactionIds transaction ids this transaction is dependent |
| 87 | + * upon |
| 88 | + * @param payload the ByteString payload of this transaction |
| 89 | + * @return the transaction |
| 90 | + */ |
| 91 | + public static Transaction makeSawtoothTransaction(final KeyManager keyManager, final String familyName, |
| 92 | + final String familyVersion, final Collection<String> inputAddresses, final Collection<String> outputAddresses, |
| 93 | + final Collection<String> dependentTransactionIds, final ByteString payload) { |
| 94 | + ByteString wrappedPayload = VersionedEnvelopeUtils.wrap(payload); |
| 95 | + String payloadHash = hash512(wrappedPayload.toByteArray()); |
| 96 | + TransactionHeader.Builder txnHeaderBldr = TransactionHeader.newBuilder().setFamilyName(familyName) |
| 97 | + .setFamilyVersion(familyVersion).clearBatcherPublicKey().setBatcherPublicKey(keyManager.getPublicKeyInHex()) |
| 98 | + .setNonce(SawtoothClientUtils.generateNonce()).setPayloadSha512(payloadHash).addAllInputs(inputAddresses) |
| 99 | + .addAllOutputs(outputAddresses).addAllDependencies(dependentTransactionIds) |
| 100 | + .setSignerPublicKey(keyManager.getPublicKeyInHex()); |
| 101 | + TransactionHeader txnHeader = txnHeaderBldr.build(); |
| 102 | + |
| 103 | + String signedHeader = keyManager.sign(txnHeader.toByteArray()); |
| 104 | + return Transaction.newBuilder().setHeader(txnHeader.toByteString()).setHeaderSignature(signedHeader) |
| 105 | + .setPayload(wrappedPayload).build(); |
| 106 | + } |
| 107 | + |
| 108 | + /** |
| 109 | + * Generate a random nonce. |
| 110 | + * |
| 111 | + * @return the nonce |
| 112 | + */ |
| 113 | + public static String generateNonce() { |
| 114 | + final var seedByteCount = 20; |
| 115 | + synchronized (SawtoothClientUtils.class) { |
| 116 | + if (null == secureRandom) { |
| 117 | + LOGGER.debug("Generating nonce - acquiring SecureRandom"); |
| 118 | + secureRandom = new SecureRandom(); |
| 119 | + randomBytesGenerated = -1; |
| 120 | + } |
| 121 | + if (randomBytesGenerated == -1) { |
| 122 | + LOGGER.debug("Generating nonce - regenerating seed"); |
| 123 | + secureRandom.setSeed(secureRandom.generateSeed(seedByteCount)); |
| 124 | + randomBytesGenerated = seedByteCount; |
| 125 | + } else { |
| 126 | + randomBytesGenerated += seedByteCount; |
| 127 | + } |
| 128 | + if (randomBytesGenerated > MAX_BYTES_PER_SEED) { |
| 129 | + randomBytesGenerated = -1; |
| 130 | + } |
| 131 | + } |
| 132 | + |
| 133 | + var nonceBytes = new byte[seedByteCount]; |
| 134 | + LOGGER.debug("Generating nonce - generating nonce"); |
| 135 | + secureRandom.nextBytes(nonceBytes); |
| 136 | + LOGGER.debug("Generating nonce - nonce generated"); |
| 137 | + return HEX.encode(nonceBytes); |
| 138 | + } |
| 139 | + |
| 140 | + /** |
| 141 | + * For a given string return its sha512, transform the encoding problems into |
| 142 | + * RuntimeErrors. |
| 143 | + * |
| 144 | + * @param arg a string |
| 145 | + * @return the hash512 of the string |
| 146 | + */ |
| 147 | + public static String getHash(final String arg) { |
| 148 | + byte[] data = arg.getBytes(StandardCharsets.UTF_8); |
| 149 | + return hash512(data); |
| 150 | + } |
| 151 | + |
| 152 | + /** |
| 153 | + * Subit the Batch to the sawtooth Stream. |
| 154 | + * |
| 155 | + * @param batch the batch to submit |
| 156 | + * @param stream the stream to submit to |
| 157 | + * @return a Future upon which to wait |
| 158 | + */ |
| 159 | + public static Future submitBatch(final Batch batch, final Stream stream) { |
| 160 | + final ClientBatchSubmitRequest cbsReq = ClientBatchSubmitRequest.newBuilder().addBatches(batch).build(); |
| 161 | + return stream.send(Message.MessageType.CLIENT_BATCH_SUBMIT_REQUEST, cbsReq.toByteString()); |
| 162 | + } |
| 163 | +} |
0 commit comments