add checks as on BIP066
@@ -60,6 +60,31 @@ def get_DER_sig(r, s, sighash = sighash_all):
total_len = len(DER_sig).to_bytes(1, "big")
return DER_follows + total_len + DER_sig + sighash
+def check_DER_sig(DER_sig):
+ # following the instructions on BIP 066 in that order
+ assert type(DER_sig) == bytes, "DER sig must be in bytes"
+ assert 9 <= len(DER_sig) and len(DER_sig) <= 73, \
+ "DER sig must at least 9 bytes and at most 73 bytes"
+ assert DER_sig[0] == 0x30, "DER sig must start with 30"
+ assert DER_sig[1] == len(DER_sig) - 3, "Length must cover the entire sig"
+ lenR = DER_sig[3]
+ assert 5 + lenR <= len(DER_sig), "Length of the s element must be inside the signature"
+ lenS = DER_sig[5 + lenR]
+ assert lenR + lenS + 7 == len(DER_sig), \
+ "Length of the sig must match the sum of the length of the elements"
+ assert DER_sig[2] == 0x02, "r element must be an int"
+ assert lenR != 0, "Zero-length integers are not allowed for r"
+ assert DER_sig[4] < 0x80, "Negative numbers are not allowed for r"
+ if lenR > 1 and DER_sig[4] == 0x00: assert DER_sig[5] >= 0x80, \
+ "Null bytes at the start of r are not allowed, unless r would" + \
+ "otherwise be interpreted as a negative number"
+ assert DER_sig[lenR + 4] == 0x02, "s element must be an int"
+ assert lenS != 0, "Zero-length integers are not allowed for s"
+ assert DER_sig[lenR + 6] < 0x80, "Negative numbers are not allowed for s"
+ if lenS > 1 and DER_sig[lenR + 6] == 0x00: assert DER_sig[lenR + 7] >= 0x80, \
+ "Null bytes at the start of s are not allowed, unless s would" + \
+ "otherwise be interpreted as a negative number"
+
def test_DER():
DER73 = get_DER_sig(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff,\
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff,\
@@ -82,15 +107,21 @@ def test_DER():
print("\nSig 73 bytes")
print(DER73.hex(), " -- len:", len(DER73))
+ check_DER_sig(DER73)
print("\nSig 72 bytes")
print(DER72.hex(), " -- len:", len(DER72))
+ check_DER_sig(DER72)
print("\nSig 71 bytes")
print(DER71.hex(), " -- len:", len(DER71))
+ check_DER_sig(DER71)
print("\nSig 71b bytes")
print(DER71b.hex(), " -- len:", len(DER71b))
+ check_DER_sig(DER71b)
print("\nSig 70 bytes")
print(DER70.hex(), " -- len:", len(DER70))
+ check_DER_sig(DER70)
print("\nSig 69 bytes")
print(DER69.hex(), " -- len:", len(DER69))
+ check_DER_sig(DER69)
test_DER()
\ No newline at end of file
