fix cbor exception exposure and improve crypto-psbt type handling

This commit is contained in:
Craig Raw 2020-10-15 08:46:52 +02:00
parent d56dae6980
commit 4b012d1dce
3 changed files with 28 additions and 13 deletions

View file

@ -39,8 +39,9 @@ Encoding a UR:
```java
final int MIN_FRAGMENT_LENGTH = 10;
final int MAX_FRAGMENT_LENGTH = 100;
String type = UR.BYTES_TYPE;
UR ur = UR.fromBytes(data);
UR ur = UR.fromBytes(type, data);
UREncoder encoder = new UREncoder(ur, MAX_FRAGMENT_LENGTH, MIN_FRAGMENT_LENGTH, 0);
while(true) {
String fragment = encoder.nextPart();

View file

@ -16,7 +16,7 @@ apply plugin: 'com.bmuschko.nexus'
archivesBaseName = 'hummingbird'
group 'com.sparrowwallet'
version '1.1'
version '1.2'
repositories {
mavenCentral()

View file

@ -41,14 +41,18 @@ public class UR {
return data;
}
public byte[] toBytes() throws InvalidTypeException, CborException {
if(!BYTES_TYPE.equals(getType())) {
throw new InvalidTypeException("Not a " + BYTES_TYPE + " type");
}
public byte[] toBytes() throws InvalidCBORException {
try {
ByteArrayInputStream bais = new ByteArrayInputStream(getCbor());
List<DataItem> dataItems = new CborDecoder(bais).decode();
if(!(dataItems.get(0) instanceof ByteString)) {
throw new IllegalArgumentException("First element of CBOR is not a byte string");
}
ByteArrayInputStream bais = new ByteArrayInputStream(getCbor());
List<DataItem> dataItems = new CborDecoder(bais).decode();
return ((ByteString)dataItems.get(0)).getBytes();
return ((ByteString)dataItems.get(0)).getBytes();
} catch(CborException e) {
throw new InvalidCBORException(e.getMessage());
}
}
public static boolean isURType(String type) {
@ -67,7 +71,11 @@ public class UR {
return false;
}
public static UR fromBytes(byte[] data) {
public static UR fromBytes(byte[] data) throws InvalidTypeException, InvalidCBORException {
return fromBytes(BYTES_TYPE, data);
}
public static UR fromBytes(String type, byte[] data) throws InvalidTypeException, InvalidCBORException {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
new CborEncoder(baos).encode(new CborBuilder()
@ -75,9 +83,9 @@ public class UR {
.build());
byte[] cbor = baos.toByteArray();
return new UR("bytes", cbor);
} catch(InvalidTypeException | CborException e) {
return null;
return new UR(type, cbor);
} catch(CborException e) {
throw new InvalidCBORException(e.getMessage());
}
}
@ -134,4 +142,10 @@ public class UR {
super(message);
}
}
public static class InvalidCBORException extends URException {
public InvalidCBORException(String message) {
super(message);
}
}
}