-
Notifications
You must be signed in to change notification settings - Fork 284
Add TLV and TLV stream codec support #1045
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
f8b5fa3
LightningMessageTypes/Codecs: clean-up warnings
t-bast 9960c3d
Add Bitcoin varInt codec
t-bast 8a2a249
Remove unused FixedSizeStrictCodec.
t-bast 7dadd2d
Add generic TLV codec.
t-bast fa8867a
Codecs refactoring.
t-bast 74942ec
Add tlv stream codec.
t-bast beaf0b4
Replace custom attemptFromTry by scodec's built-in Attempt.fromTry()
t-bast 35b0953
Make varint (CompactSize) a Codec[UInt64] instead of Codec[Long]
t-bast 451697c
Move TlvStream errors to companion object.
t-bast f87f924
Rename varlong to varintoverflow for consistency
t-bast 8229a0b
Clean up Tlv stream.
t-bast d63388b
Simplify varint codec (credits to pm47)
t-bast File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
128 changes: 128 additions & 0 deletions
128
eclair-core/src/main/scala/fr/acinq/eclair/wire/CommonCodecs.scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,128 @@ | ||
| /* | ||
| * Copyright 2019 ACINQ SAS | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package fr.acinq.eclair.wire | ||
|
|
||
| import java.net.{Inet4Address, Inet6Address, InetAddress} | ||
|
|
||
| import fr.acinq.bitcoin.{ByteVector32, ByteVector64} | ||
| import fr.acinq.bitcoin.Crypto.{PrivateKey, PublicKey} | ||
| import fr.acinq.eclair.{ShortChannelId, UInt64} | ||
| import org.apache.commons.codec.binary.Base32 | ||
| import scodec.{Attempt, Codec, DecodeResult, Err, SizeBound} | ||
| import scodec.bits.{BitVector, ByteVector} | ||
| import scodec.codecs._ | ||
|
|
||
| import scala.util.Try | ||
|
|
||
| /** | ||
| * Created by t-bast on 20/06/2019. | ||
| */ | ||
|
|
||
| object CommonCodecs { | ||
|
|
||
| /** | ||
| * Discriminator codec with a default fallback codec (of the same type). | ||
| */ | ||
| def discriminatorWithDefault[A](discriminator: Codec[A], fallback: Codec[A]): Codec[A] = new Codec[A] { | ||
| def sizeBound: SizeBound = discriminator.sizeBound | fallback.sizeBound | ||
|
|
||
| def encode(e: A): Attempt[BitVector] = discriminator.encode(e).recoverWith { case _ => fallback.encode(e) } | ||
|
|
||
| def decode(b: BitVector): Attempt[DecodeResult[A]] = discriminator.decode(b).recoverWith { | ||
| case _: KnownDiscriminatorType[_]#UnknownDiscriminator => fallback.decode(b) | ||
| } | ||
| } | ||
|
|
||
| // this codec can be safely used for values < 2^63 and will fail otherwise | ||
| // (for something smarter see https://github.com/yzernik/bitcoin-scodec/blob/master/src/main/scala/io/github/yzernik/bitcoinscodec/structures/UInt64.scala) | ||
| val uint64overflow: Codec[Long] = int64.narrow(l => if (l >= 0) Attempt.Successful(l) else Attempt.failure(Err(s"overflow for value $l")), l => l) | ||
|
|
||
| val uint64: Codec[UInt64] = bytes(8).xmap(b => UInt64(b), a => a.toByteVector.padLeft(8)) | ||
|
|
||
| val uint64L: Codec[UInt64] = bytes(8).xmap(b => UInt64(b.reverse), a => a.toByteVector.padLeft(8).reverse) | ||
|
|
||
| /** | ||
| * We impose a minimal encoding on varint values to ensure that signed hashes can be reproduced easily. | ||
| * If a value could be encoded with less bytes, it's considered invalid and results in a failed decoding attempt. | ||
| * | ||
| * @param codec the integer codec (depends on the value). | ||
| * @param min the minimal value that should be encoded. | ||
| */ | ||
| def uint64min(codec: Codec[UInt64], min: UInt64): Codec[UInt64] = codec.exmap({ | ||
| case i if i < min => Attempt.failure(Err("varint was not minimally encoded")) | ||
| case i => Attempt.successful(i) | ||
| }, Attempt.successful) | ||
|
|
||
| // Bitcoin-style varint codec (CompactSize). | ||
| // See https://bitcoin.org/en/developer-reference#compactsize-unsigned-integers for reference. | ||
| val varint: Codec[UInt64] = discriminatorWithDefault( | ||
| discriminated[UInt64].by(uint8L) | ||
| .\(0xff) { case i if i >= UInt64(0x100000000L) => i }(uint64min(uint64L, UInt64(0x100000000L))) | ||
| .\(0xfe) { case i if i >= UInt64(0x10000) => i }(uint64min(uint32L.xmap(UInt64(_), _.toBigInt.toLong), UInt64(0x10000))) | ||
| .\(0xfd) { case i if i >= UInt64(0xfd) => i }(uint64min(uint16L.xmap(UInt64(_), _.toBigInt.toInt), UInt64(0xfd))), | ||
| uint8L.xmap(UInt64(_), _.toBigInt.toInt) | ||
| ) | ||
|
|
||
| // This codec can be safely used for values < 2^63 and will fail otherwise. | ||
| // It is useful in combination with variableSizeBytesLong to encode/decode TLV lengths because those will always be < 2^63. | ||
| val varintoverflow: Codec[Long] = varint.narrow(l => if (l <= UInt64(Long.MaxValue)) Attempt.successful(l.toBigInt.toLong) else Attempt.failure(Err(s"overflow for value $l")), l => UInt64(l)) | ||
|
|
||
| val bytes32: Codec[ByteVector32] = limitedSizeBytes(32, bytesStrict(32).xmap(d => ByteVector32(d), d => d.bytes)) | ||
|
|
||
| val bytes64: Codec[ByteVector64] = limitedSizeBytes(64, bytesStrict(64).xmap(d => ByteVector64(d), d => d.bytes)) | ||
|
|
||
| val sha256: Codec[ByteVector32] = bytes32 | ||
|
|
||
| val varsizebinarydata: Codec[ByteVector] = variableSizeBytes(uint16, bytes) | ||
|
|
||
| val listofsignatures: Codec[List[ByteVector64]] = listOfN(uint16, bytes64) | ||
|
|
||
| val ipv4address: Codec[Inet4Address] = bytes(4).xmap(b => InetAddress.getByAddress(b.toArray).asInstanceOf[Inet4Address], a => ByteVector(a.getAddress)) | ||
|
|
||
| val ipv6address: Codec[Inet6Address] = bytes(16).exmap(b => Attempt.fromTry(Try(Inet6Address.getByAddress(null, b.toArray, null))), a => Attempt.fromTry(Try(ByteVector(a.getAddress)))) | ||
|
pm47 marked this conversation as resolved.
|
||
|
|
||
| def base32(size: Int): Codec[String] = bytes(size).xmap(b => new Base32().encodeAsString(b.toArray).toLowerCase, a => ByteVector(new Base32().decode(a.toUpperCase()))) | ||
|
|
||
| val nodeaddress: Codec[NodeAddress] = | ||
| discriminated[NodeAddress].by(uint8) | ||
| .typecase(1, (ipv4address :: uint16).as[IPv4]) | ||
| .typecase(2, (ipv6address :: uint16).as[IPv6]) | ||
| .typecase(3, (base32(10) :: uint16).as[Tor2]) | ||
| .typecase(4, (base32(35) :: uint16).as[Tor3]) | ||
|
|
||
| // this one is a bit different from most other codecs: the first 'len' element is *not* the number of items | ||
| // in the list but rather the number of bytes of the encoded list. The rationale is once we've read this | ||
| // number of bytes we can just skip to the next field | ||
| val listofnodeaddresses: Codec[List[NodeAddress]] = variableSizeBytes(uint16, list(nodeaddress)) | ||
|
|
||
| val shortchannelid: Codec[ShortChannelId] = int64.xmap(l => ShortChannelId(l), s => s.toLong) | ||
|
|
||
| val privateKey: Codec[PrivateKey] = Codec[PrivateKey]( | ||
| (priv: PrivateKey) => bytes(32).encode(priv.value), | ||
| (wire: BitVector) => bytes(32).decode(wire).map(_.map(b => PrivateKey(b))) | ||
| ) | ||
|
|
||
| val publicKey: Codec[PublicKey] = Codec[PublicKey]( | ||
| (pub: PublicKey) => bytes(33).encode(pub.value), | ||
| (wire: BitVector) => bytes(33).decode(wire).map(_.map(b => PublicKey(b))) | ||
| ) | ||
|
|
||
| val rgb: Codec[Color] = bytes(3).xmap(buf => Color(buf(0), buf(1), buf(2)), t => ByteVector(t.r, t.g, t.b)) | ||
|
|
||
| def zeropaddedstring(size: Int): Codec[String] = fixedSizeBytes(32, utf8).xmap(s => s.takeWhile(_ != '\u0000'), s => s) | ||
|
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.