Add toString() methods to a few data structures and use them to make the output of the trader demo a bit nicer.

Import Base58 code from bitcoinj and use it for rendering pubkeys (note: not calculated in the same way as Bitcoin).
This commit is contained in:
Mike Hearn 2016-02-04 17:38:45 +01:00
parent 9a818247bb
commit a06d4d23bd
11 changed files with 384 additions and 9 deletions

View File

@ -0,0 +1,18 @@
/*
* Copyright 2015 Distributed Ledger Group LLC. Distributed as Licensed Company IP to DLG Group Members
* pursuant to the August 7, 2015 Advisory Services Agreement and subject to the Company IP License terms
* set forth therein.
*
* All other rights reserved.
*/
package core.crypto;
public class AddressFormatException extends IllegalArgumentException {
public AddressFormatException() {
super();
}
public AddressFormatException(String message) {
super(message);
}
}

View File

@ -0,0 +1,177 @@
/*
* Copyright 2015 Distributed Ledger Group LLC. Distributed as Licensed Company IP to DLG Group Members
* pursuant to the August 7, 2015 Advisory Services Agreement and subject to the Company IP License terms
* set forth therein.
*
* All other rights reserved.
*/
package core.crypto;
import core.*;
import java.math.*;
import java.util.*;
/**
* Base58 is a way to encode Bitcoin addresses (or arbitrary data) as alphanumeric strings.
* <p>
* Note that this is not the same base58 as used by Flickr, which you may find referenced around the Internet.
* <p>
* Satoshi explains: why base-58 instead of standard base-64 encoding?
* <ul>
* <li>Don't want 0OIl characters that look the same in some fonts and
* could be used to create visually identical looking account numbers.</li>
* <li>A string with non-alphanumeric characters is not as easily accepted as an account number.</li>
* <li>E-mail usually won't line-break if there's no punctuation to break at.</li>
* <li>Doubleclicking selects the whole number as one word if it's all alphanumeric.</li>
* </ul>
* <p>
* However, note that the encoding/decoding runs in O(n&sup2;) time, so it is not useful for large data.
* <p>
* The basic idea of the encoding is to treat the data bytes as a large number represented using
* base-256 digits, convert the number to be represented using base-58 digits, preserve the exact
* number of leading zeros (which are otherwise lost during the mathematical operations on the
* numbers), and finally represent the resulting base-58 digits as alphanumeric ASCII characters.
*
* NB: This class originally comes from the Apache licensed bitcoinj library. The original author of this code is the
* same as the original author of the R3 repository.
*/
public class Base58 {
public static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray();
private static final char ENCODED_ZERO = ALPHABET[0];
private static final int[] INDEXES = new int[128];
static {
Arrays.fill(INDEXES, -1);
for (int i = 0; i < ALPHABET.length; i++) {
INDEXES[ALPHABET[i]] = i;
}
}
/**
* Encodes the given bytes as a base58 string (no checksum is appended).
*
* @param input the bytes to encode
* @return the base58-encoded string
*/
public static String encode(byte[] input) {
if (input.length == 0) {
return "";
}
// Count leading zeros.
int zeros = 0;
while (zeros < input.length && input[zeros] == 0) {
++zeros;
}
// Convert base-256 digits to base-58 digits (plus conversion to ASCII characters)
input = Arrays.copyOf(input, input.length); // since we modify it in-place
char[] encoded = new char[input.length * 2]; // upper bound
int outputStart = encoded.length;
for (int inputStart = zeros; inputStart < input.length; ) {
encoded[--outputStart] = ALPHABET[divmod(input, inputStart, 256, 58)];
if (input[inputStart] == 0) {
++inputStart; // optimization - skip leading zeros
}
}
// Preserve exactly as many leading encoded zeros in output as there were leading zeros in input.
while (outputStart < encoded.length && encoded[outputStart] == ENCODED_ZERO) {
++outputStart;
}
while (--zeros >= 0) {
encoded[--outputStart] = ENCODED_ZERO;
}
// Return encoded string (including encoded leading zeros).
return new String(encoded, outputStart, encoded.length - outputStart);
}
/**
* Decodes the given base58 string into the original data bytes.
*
* @param input the base58-encoded string to decode
* @return the decoded data bytes
* @throws AddressFormatException if the given string is not a valid base58 string
*/
public static byte[] decode(String input) throws AddressFormatException {
if (input.length() == 0) {
return new byte[0];
}
// Convert the base58-encoded ASCII chars to a base58 byte sequence (base58 digits).
byte[] input58 = new byte[input.length()];
for (int i = 0; i < input.length(); ++i) {
char c = input.charAt(i);
int digit = c < 128 ? INDEXES[c] : -1;
if (digit < 0) {
throw new AddressFormatException("Illegal character " + c + " at position " + i);
}
input58[i] = (byte) digit;
}
// Count leading zeros.
int zeros = 0;
while (zeros < input58.length && input58[zeros] == 0) {
++zeros;
}
// Convert base-58 digits to base-256 digits.
byte[] decoded = new byte[input.length()];
int outputStart = decoded.length;
for (int inputStart = zeros; inputStart < input58.length; ) {
decoded[--outputStart] = divmod(input58, inputStart, 58, 256);
if (input58[inputStart] == 0) {
++inputStart; // optimization - skip leading zeros
}
}
// Ignore extra leading zeroes that were added during the calculation.
while (outputStart < decoded.length && decoded[outputStart] == 0) {
++outputStart;
}
// Return decoded data (including original number of leading zeros).
return Arrays.copyOfRange(decoded, outputStart - zeros, decoded.length);
}
public static BigInteger decodeToBigInteger(String input) throws AddressFormatException {
return new BigInteger(1, decode(input));
}
/**
* Decodes the given base58 string into the original data bytes, using the checksum in the
* last 4 bytes of the decoded data to verify that the rest are correct. The checksum is
* removed from the returned data.
*
* @param input the base58-encoded string to decode (which should include the checksum)
* @throws AddressFormatException if the input is not base 58 or the checksum does not validate.
*/
public static byte[] decodeChecked(String input) throws AddressFormatException {
byte[] decoded = decode(input);
if (decoded.length < 4)
throw new AddressFormatException("Input too short");
byte[] data = Arrays.copyOfRange(decoded, 0, decoded.length - 4);
byte[] checksum = Arrays.copyOfRange(decoded, decoded.length - 4, decoded.length);
byte[] actualChecksum = Arrays.copyOfRange(SecureHash.Companion.sha256Twice(data).getBits(), 0, 4);
if (!Arrays.equals(checksum, actualChecksum))
throw new AddressFormatException("Checksum does not validate");
return data;
}
/**
* Divides a number, represented as an array of bytes each containing a single digit
* in the specified base, by the given divisor. The given number is modified in-place
* to contain the quotient, and the return value is the remainder.
*
* @param number the number to divide
* @param firstDigit the index within the array of the first non-zero digit
* (this is used for optimization by skipping the leading zeros)
* @param base the base in which the number's digits are represented (up to 256)
* @param divisor the number to divide by (up to 256)
* @return the remainder of the division operation
*/
private static byte divmod(byte[] number, int firstDigit, int base, int divisor) {
// this is just long division which accounts for the base of the input digits
int remainder = 0;
for (int i = firstDigit; i < number.length; i++) {
int digit = (int) number[i] & 0xFF;
int temp = remainder * base + digit;
number[i] = (byte) (temp / divisor);
remainder = temp % divisor;
}
return (byte) remainder;
}
}

View File

@ -9,6 +9,7 @@
package contracts
import core.*
import core.utilities.Emoji
import java.security.PublicKey
import java.security.SecureRandom
import java.util.*
@ -60,7 +61,7 @@ class Cash : Contract {
override val owner: PublicKey
) : OwnableState {
override val programRef = CASH_PROGRAM_ID
override fun toString() = "Cash($amount at $deposit owned by $owner)"
override fun toString() = "${Emoji.bagOfCash}Cash($amount at $deposit owned by ${owner.toStringShort()})"
override fun withNewOwner(newOwner: PublicKey) = Pair(Commands.Move(), copy(owner = newOwner))
}

View File

@ -9,6 +9,7 @@
package contracts
import core.*
import core.utilities.Emoji
import java.security.PublicKey
import java.time.Instant
@ -51,6 +52,7 @@ class CommercialPaper : Contract {
fun withoutOwner() = copy(owner = NullPublicKey)
override fun withNewOwner(newOwner: PublicKey) = Pair(Commands.Move(), copy(owner = newOwner))
override fun toString() = "${Emoji.newspaper}CommercialPaper(of $faceValue redeemable on $maturityDate by '$issuance', owned by ${owner.toStringShort()})"
}
interface Commands : CommandData {

View File

@ -9,9 +9,11 @@
package core
import com.google.common.io.BaseEncoding
import core.crypto.Base58
import core.serialization.OpaqueBytes
import java.math.BigInteger
import java.security.*
import java.security.interfaces.ECPublicKey
// "sealed" here means there can't be any subclasses other than the ones defined here.
sealed class SecureHash(bits: ByteArray) : OpaqueBytes(bits) {
@ -34,6 +36,7 @@ sealed class SecureHash(bits: ByteArray) : OpaqueBytes(bits) {
}
fun sha256(bits: ByteArray) = SHA256(MessageDigest.getInstance("SHA-256").digest(bits))
fun sha256Twice(bits: ByteArray) = sha256(sha256(bits).bits)
fun sha256(str: String) = sha256(str.toByteArray())
fun randomSHA256() = sha256(SecureRandom.getInstanceStrong().generateSeed(32))
@ -110,6 +113,13 @@ fun PublicKey.verifyWithECDSA(content: ByteArray, signature: DigitalSignature) {
throw SignatureException("Signature did not match")
}
/** Render a public key to a string, using a short form if it's an elliptic curve public key */
fun PublicKey.toStringShort(): String {
return (this as? ECPublicKey)?.let { key ->
"R3" + Base58.encode(key.w.affineX.toByteArray())
} ?: toString()
}
// Allow Kotlin destructuring: val (private, public) = keypair
fun KeyPair.component1() = this.private
fun KeyPair.component2() = this.public
operator fun KeyPair.component1() = this.private
operator fun KeyPair.component2() = this.public

View File

@ -44,7 +44,9 @@ fun ContractState.hash(): SecureHash = SecureHash.sha256(serialize().bits)
* A stateref is a pointer to a state, this is an equivalent of an "outpoint" in Bitcoin. It records which transaction
* defined the state and where in that transaction it was.
*/
data class ContractStateRef(val txhash: SecureHash, val index: Int)
data class ContractStateRef(val txhash: SecureHash, val index: Int) {
override fun toString() = "$txhash($index)"
}
/** A StateAndRef is simply a (state, ref) pair. For instance, a wallet (which holds available assets) contains these. */
data class StateAndRef<out T : ContractState>(val state: T, val ref: ContractStateRef)
@ -80,6 +82,9 @@ data class Command(val data: CommandData, val pubkeys: List<PublicKey>) {
require(pubkeys.isNotEmpty())
}
constructor(data: CommandData, key: PublicKey) : this(data, listOf(key))
private fun commandDataToString() = data.toString().let { if (it.contains("@")) it.replace('$', '.').split("@")[0] else it }
override fun toString() = "${commandDataToString()} with pubkeys ${pubkeys.map { it.toStringShort() }}"
}
/** Wraps an object that was signed by a public key, which may be a well known/recognised institutional key. */

View File

@ -13,6 +13,7 @@ import core.node.TimestampingError
import core.serialization.SerializedBytes
import core.serialization.deserialize
import core.serialization.serialize
import core.utilities.Emoji
import java.security.KeyPair
import java.security.PublicKey
import java.security.SignatureException
@ -60,6 +61,15 @@ data class WireTransaction(val inputStates: List<ContractStateRef>,
}
return LedgerTransaction(inputStates, outputStates, authenticatedArgs, originalHash)
}
override fun toString(): String {
val buf = StringBuilder()
buf.appendln("Transaction:")
for (input in inputStates) buf.appendln("${Emoji.rightArrow}INPUT: $input")
for (output in outputStates) buf.appendln("${Emoji.leftArrow}OUTPUT: $output")
for (command in commands) buf.appendln("${Emoji.diamond}COMMAND: $command")
return buf.toString()
}
}
/** Container for a [WireTransaction] and attached signatures. */

View File

@ -31,8 +31,8 @@ val Int.seconds: Duration get() = Duration.ofSeconds(this.toLong())
*/
fun random63BitValue(): Long = Math.abs(SecureRandom.getInstanceStrong().nextLong())
fun <T> ListenableFuture<T>.whenComplete(executor: Executor? = null, body: () -> Unit) {
addListener(Runnable { body() }, executor ?: MoreExecutors.directExecutor())
fun <T> ListenableFuture<T>.whenComplete(executor: Executor? = null, body: (T) -> Unit) {
addListener(Runnable { body(get()) }, executor ?: RunOnCallerThread)
}
/** Executes the given block and sets the future to either the result, or any exception that was thrown. */

View File

@ -18,6 +18,7 @@ import core.messaging.runOnNextMessage
import core.messaging.send
import core.serialization.deserialize
import core.utilities.BriefLogFormatter
import core.utilities.Emoji
import joptsimple.OptionParser
import java.nio.file.Files
import java.nio.file.Path
@ -122,12 +123,19 @@ fun main(args: Array<String>) {
CommercialPaper.State::class.java, buyerSessionID)
future.whenComplete {
println("Purchase complete - we are a happy customer!")
node.stop()
println()
println("Purchase complete - we are a happy customer! Final transaction is:")
println()
println(Emoji.renderIfSupported(it.first))
println()
println("Waiting for another seller to connect. Or press Ctrl-C to shut me down.")
}
node.net.send("test.junktrade.initiate", replyTo, buyerSessionID)
}
println()
println("Waiting for a seller to connect to us (run the other node) ...")
println()
} else {
// Grab a session ID for the fake trade from the other side, then kick off the seller and sell them some junk.
if (!options.has(fakeTradeWithArg)) {
@ -148,11 +156,19 @@ fun main(args: Array<String>) {
otherSide, commercialPaper, 100.DOLLARS, cpOwnerKey, sessionID)
future.whenComplete {
println()
println("Sale completed - we have a happy customer!")
println()
println("Final transaction is")
println()
println(Emoji.renderIfSupported(it.first))
println()
node.stop()
}
}
println("Sending a request to get a session ID to the other side")
println()
println("Sending a message to the listening/buying node ...")
println()
node.net.send("test.junktrade", otherSide, node.net.myAddress, includeClassName = true)
}
}

View File

@ -0,0 +1,49 @@
/*
* Copyright 2015 Distributed Ledger Group LLC. Distributed as Licensed Company IP to DLG Group Members
* pursuant to the August 7, 2015 Advisory Services Agreement and subject to the Company IP License terms
* set forth therein.
*
* All other rights reserved.
*/
package core.utilities
/**
* A simple wrapper class that contains icons and support for printing them only when we're connected to a terminal.
*/
object Emoji {
val hasTerminal by lazy { System.getenv("TERM") != null && System.getenv("LANG").contains("UTF-8") }
const val CODE_DIAMOND = "\ud83d\udd37"
const val CODE_BAG_OF_CASH = "\ud83d\udcb0"
const val CODE_NEWSPAPER = "\ud83d\udcf0"
const val CODE_RIGHT_ARROW = "\u27a1\ufe0f"
const val CODE_LEFT_ARROW = "\u2b05\ufe0f"
/**
* When non-null, toString() methods are allowed to use emoji in the output as we're going to render them to a
* sufficiently capable text surface.
*/
private val emojiMode = ThreadLocal<Any>()
val diamond: String get() = if (emojiMode.get() != null) "$CODE_DIAMOND " else ""
val bagOfCash: String get() = if (emojiMode.get() != null) "$CODE_BAG_OF_CASH " else ""
val newspaper: String get() = if (emojiMode.get() != null) "$CODE_NEWSPAPER " else ""
val rightArrow: String get() = if (emojiMode.get() != null) "$CODE_RIGHT_ARROW " else ""
val leftArrow: String get() = if (emojiMode.get() != null) "$CODE_LEFT_ARROW " else ""
fun renderIfSupported(obj: Any): String {
if (!hasTerminal)
return obj.toString()
if (emojiMode.get() != null)
return obj.toString()
emojiMode.set(this) // Could be any object.
try {
return obj.toString()
} finally {
emojiMode.set(null)
}
}
}

View File

@ -0,0 +1,87 @@
/*
* Copyright 2015 Distributed Ledger Group LLC. Distributed as Licensed Company IP to DLG Group Members
* pursuant to the August 7, 2015 Advisory Services Agreement and subject to the Company IP License terms
* set forth therein.
*
* All other rights reserved.
*/
package core.crypto;
import org.junit.*;
import java.math.*;
import java.util.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/** From the bitcoinj library */
public class Base58Test {
@Test
public void testEncode() throws Exception {
byte[] testbytes = "Hello World".getBytes();
assertEquals("JxF12TrwUP45BMd", Base58.encode(testbytes));
BigInteger bi = BigInteger.valueOf(3471844090L);
assertEquals("16Ho7Hs", Base58.encode(bi.toByteArray()));
byte[] zeroBytes1 = new byte[1];
assertEquals("1", Base58.encode(zeroBytes1));
byte[] zeroBytes7 = new byte[7];
assertEquals("1111111", Base58.encode(zeroBytes7));
// test empty encode
assertEquals("", Base58.encode(new byte[0]));
}
@Test
public void testDecode() throws Exception {
byte[] testbytes = "Hello World".getBytes();
byte[] actualbytes = Base58.decode("JxF12TrwUP45BMd");
assertTrue(new String(actualbytes), Arrays.equals(testbytes, actualbytes));
assertTrue("1", Arrays.equals(Base58.decode("1"), new byte[1]));
assertTrue("1111", Arrays.equals(Base58.decode("1111"), new byte[4]));
try {
Base58.decode("This isn't valid base58");
fail();
} catch (AddressFormatException e) {
// expected
}
Base58.decodeChecked("4stwEBjT6FYyVV");
// Checksum should fail.
try {
Base58.decodeChecked("4stwEBjT6FYyVW");
fail();
} catch (AddressFormatException e) {
// expected
}
// Input is too short.
try {
Base58.decodeChecked("4s");
fail();
} catch (AddressFormatException e) {
// expected
}
// Test decode of empty String.
assertEquals(0, Base58.decode("").length);
// Now check we can correctly decode the case where the high bit of the first byte is not zero, so BigInteger
// sign extends. Fix for a bug that stopped us parsing keys exported using sipas patch.
Base58.decodeChecked("93VYUMzRG9DdbRP72uQXjaWibbQwygnvaCu9DumcqDjGybD864T");
}
@Test
public void testDecodeToBigInteger() {
byte[] input = Base58.decode("129");
assertEquals(new BigInteger(1, input), Base58.decodeToBigInteger("129"));
}
}