Decodes an encoded varint to an integer and returns it. Per protocol v3, the encoded value must be encoded with the minimum amount of data possible or else it is malformed. Returns a tuple: (theEncodedValue, theSizeOfTheVarintInBytes)
(data)
| 74 | pass |
| 75 | |
| 76 | def decodeVarint(data): |
| 77 | """ |
| 78 | Decodes an encoded varint to an integer and returns it. |
| 79 | Per protocol v3, the encoded value must be encoded with |
| 80 | the minimum amount of data possible or else it is malformed. |
| 81 | Returns a tuple: (theEncodedValue, theSizeOfTheVarintInBytes) |
| 82 | """ |
| 83 | |
| 84 | if len(data) == 0: |
| 85 | return (0,0) |
| 86 | firstByte, = unpack('>B',data[0:1]) |
| 87 | if firstByte < 253: |
| 88 | # encodes 0 to 252 |
| 89 | return (firstByte,1) #the 1 is the length of the varint |
| 90 | if firstByte == 253: |
| 91 | # encodes 253 to 65535 |
| 92 | if len(data) < 3: |
| 93 | raise varintDecodeError('The first byte of this varint as an integer is %s but the total length is only %s. It needs to be at least 3.' % (firstByte, len(data))) |
| 94 | encodedValue, = unpack('>H',data[1:3]) |
| 95 | if encodedValue < 253: |
| 96 | raise varintDecodeError('This varint does not encode the value with the lowest possible number of bytes.') |
| 97 | return (encodedValue,3) |
| 98 | if firstByte == 254: |
| 99 | # encodes 65536 to 4294967295 |
| 100 | if len(data) < 5: |
| 101 | raise varintDecodeError('The first byte of this varint as an integer is %s but the total length is only %s. It needs to be at least 5.' % (firstByte, len(data))) |
| 102 | encodedValue, = unpack('>I',data[1:5]) |
| 103 | if encodedValue < 65536: |
| 104 | raise varintDecodeError('This varint does not encode the value with the lowest possible number of bytes.') |
| 105 | return (encodedValue,5) |
| 106 | if firstByte == 255: |
| 107 | # encodes 4294967296 to 18446744073709551615 |
| 108 | if len(data) < 9: |
| 109 | raise varintDecodeError('The first byte of this varint as an integer is %s but the total length is only %s. It needs to be at least 9.' % (firstByte, len(data))) |
| 110 | encodedValue, = unpack('>Q',data[1:9]) |
| 111 | if encodedValue < 4294967296: |
| 112 | raise varintDecodeError('This varint does not encode the value with the lowest possible number of bytes.') |
| 113 | return (encodedValue,9) |
| 114 | |
| 115 | |
| 116 | def calculateInventoryHash(data): |
no test coverage detected