From 2d21475936ddca22bd7f5d19f3e57e847bae3a93 Mon Sep 17 00:00:00 2001 From: Dario Anongba Varela Date: Thu, 26 Nov 2026 23:52:37 +0100 Subject: [PATCH 01/15] multi: define SendAssetOOR RPC and TreePath batch_asset_root Add the daemon-only SendAssetOOR RPC (plus REST gateway mapping) to waverpc so waved can submit out-of-round Taproot Asset transfers without exposing a CLI surface yet, and add optional batch_asset_root (field 5) on arkrpc.TreePath so clients can authenticate composed asset batch output expiry against confirmed commitment transactions. --- arkrpc/indexer.proto | 5 ++++ waverpc/daemon.proto | 71 ++++++++++++++++++++++++++++++++++++++++++++ waverpc/daemon.yaml | 3 ++ 3 files changed, 79 insertions(+) diff --git a/arkrpc/indexer.proto b/arkrpc/indexer.proto index 7575c028c..8334ca86f 100644 --- a/arkrpc/indexer.proto +++ b/arkrpc/indexer.proto @@ -308,6 +308,11 @@ message TreePath { // sweep_tapscript_root is the tapscript root hash for tweaking branch // outputs. Empty for connector trees. bytes sweep_tapscript_root = 4; + + // batch_asset_root is the optional 32-byte Taproot Asset commitment leaf + // hash composed beside sweep_tapscript_root in batch_output. Empty for + // Bitcoin-only trees. + bytes batch_asset_root = 5; } // AncestryPath describes one rooted VTXO tree fragment that contributes diff --git a/waverpc/daemon.proto b/waverpc/daemon.proto index 2921fedab..531c35c94 100644 --- a/waverpc/daemon.proto +++ b/waverpc/daemon.proto @@ -99,6 +99,11 @@ service DaemonService { // client and operator, without waiting for a round. rpc SendOOR (SendOORRequest) returns (SendOORResponse); + // SendAssetOOR initiates an out-of-round Taproot Asset transfer directly + // between the client and operator, merging up to eight live asset VTXOs + // and leasing an operator carrier float for the new asset leaves. + rpc SendAssetOOR (SendAssetOORRequest) returns (SendAssetOORResponse); + // PrepareOOR builds the deterministic OOR package without submitting it. // This lets callers collect signatures from external custom-input // participants before calling SendOOR with the same parameters. @@ -1317,6 +1322,72 @@ message SendOORResponse { bool failed_before_ponr = 4; } +message SendAssetOORRequest { + // asset_ref is the canonical SDK asset reference (asset ID or group key) + // of the Taproot Asset to send. + string asset_ref = 1; + + // amount is the number of asset units to send to the recipient. + uint64 amount = 2; + + // destination selects the recipient's uncomposed Ark VTXO policy. A raw + // address is omitted because asset outputs must commit to an explicit + // uncomposed Ark policy before composing the Taproot Asset root. + oneof destination { + // pubkey is the 32-byte x-only (Schnorr) public key of the recipient. + // The daemon derives the standard Ark VTXO policy using the + // operator's key and exit delay. + bytes pubkey = 3; + + // policy_template is the serialized uncomposed arkscript policy for + // the recipient VTXO. + bytes policy_template = 4; + } + + // dry_run validates the request, operator terms, and asset input + // availability without leasing a carrier float or submitting a transfer. + bool dry_run = 5; + + // idempotency_key is an optional caller-provided key that identifies + // this send intent across crashes and retries. + string idempotency_key = 6; + + // admission_deadline_unix_nanos is the latest wall-clock time at which + // the daemon may admit a new transfer for this request. Zero leaves + // admission unbounded. + int64 admission_deadline_unix_nanos = 7; +} + +message SendAssetOORResponse { + // status is the result: "submitted" on success, "failed" when replay + // finds a known terminal failure, or "preview" on dry_run. + string status = 1; + + // session_id is the OOR session identifier (Ark txid). Empty on dry_run. + string session_id = 2; + + // recipient_outpoint is the Ark transaction outpoint created for the + // recipient asset output. Empty on dry_run or when unavailable. + string recipient_outpoint = 3; + + // selected_input_count is the number of live asset VTXOs merged by this + // transfer. + uint32 selected_input_count = 4; + + // asset_change_amount is the surplus asset units returned to the sender + // as a new asset VTXO. Zero when the selected inputs match amount + // exactly. + uint64 asset_change_amount = 5; + + // sender_btc_change_sat is the round-originated Bitcoin carrier returned + // to the sender as a plain Bitcoin VTXO. + int64 sender_btc_change_sat = 6; + + // failed_before_ponr is set only on a replay with status "failed" when + // the session provably failed before the point of no return. + bool failed_before_ponr = 7; +} + message PrepareOORRequest { // recipient is the output to create via the out-of-round transfer. Output recipient = 1; diff --git a/waverpc/daemon.yaml b/waverpc/daemon.yaml index 913bb5eea..94a51999d 100644 --- a/waverpc/daemon.yaml +++ b/waverpc/daemon.yaml @@ -71,6 +71,9 @@ http: - selector: waverpc.DaemonService.SendOOR post: /v1/daemon/send-oor body: "*" + - selector: waverpc.DaemonService.SendAssetOOR + post: /v1/daemon/send-asset-oor + body: "*" - selector: waverpc.DaemonService.PrepareOOR post: /v1/daemon/prepare-oor body: "*" From 7fea060e868f6ed8e12e4f34f00e0007530b98f6 Mon Sep 17 00:00:00 2001 From: Dario Anongba Varela Date: Thu, 26 Nov 2026 23:52:38 +0100 Subject: [PATCH 02/15] multi: regenerate protobuf and devrpc stubs Regenerate waverpc, arkrpc, and devrpc registry artifacts after adding SendAssetOOR and TreePath.batch_asset_root. --- arkrpc/indexer.pb.go | 20 +- .../devrpc/registry_generated.go | 7 + rpc/restclient/clients.go | 11 + waverpc/daemon.pb.go | 1530 ++++++++++------- waverpc/daemon.pb.gw.go | 66 + waverpc/daemon_grpc.pb.go | 44 + waverpc/daemon_mailboxrpc.pb.go | 35 + 7 files changed, 1081 insertions(+), 632 deletions(-) diff --git a/arkrpc/indexer.pb.go b/arkrpc/indexer.pb.go index d093be746..7256afc43 100644 --- a/arkrpc/indexer.pb.go +++ b/arkrpc/indexer.pb.go @@ -1462,8 +1462,12 @@ type TreePath struct { // sweep_tapscript_root is the tapscript root hash for tweaking branch // outputs. Empty for connector trees. SweepTapscriptRoot []byte `protobuf:"bytes,4,opt,name=sweep_tapscript_root,json=sweepTapscriptRoot,proto3" json:"sweep_tapscript_root,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // batch_asset_root is the optional 32-byte Taproot Asset commitment leaf + // hash composed beside sweep_tapscript_root in batch_output. Empty for + // Bitcoin-only trees. + BatchAssetRoot []byte `protobuf:"bytes,5,opt,name=batch_asset_root,json=batchAssetRoot,proto3" json:"batch_asset_root,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *TreePath) Reset() { @@ -1524,6 +1528,13 @@ func (x *TreePath) GetSweepTapscriptRoot() []byte { return nil } +func (x *TreePath) GetBatchAssetRoot() []byte { + if x != nil { + return x.BatchAssetRoot + } + return nil +} + // AncestryPath describes one rooted VTXO tree fragment that contributes // ancestry to a VTXO. A round-direct VTXO has exactly one AncestryPath. An // OOR VTXO whose ancestry spans multiple commitment txs (cross-round @@ -2987,12 +2998,13 @@ const file_indexer_proto_rawDesc = "" + "\tsignature\x18\x06 \x01(\fR\tsignature\x1a;\n" + "\rChildrenEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\rR\x03key\x12\x14\n" + - "\x05value\x18\x02 \x01(\rR\x05value:\x028\x01\"\xd3\x01\n" + + "\x05value\x18\x02 \x01(\rR\x05value:\x028\x01\"\xfd\x01\n" + "\bTreePath\x12*\n" + "\x05nodes\x18\x01 \x03(\v2\x14.arkrpc.TreePathNodeR\x05nodes\x127\n" + "\x0ebatch_outpoint\x18\x02 \x01(\v2\x10.arkrpc.OutPointR\rbatchOutpoint\x120\n" + "\fbatch_output\x18\x03 \x01(\v2\r.arkrpc.TxOutR\vbatchOutput\x120\n" + - "\x14sweep_tapscript_root\x18\x04 \x01(\fR\x12sweepTapscriptRoot\"\xbf\x02\n" + + "\x14sweep_tapscript_root\x18\x04 \x01(\fR\x12sweepTapscriptRoot\x12(\n" + + "\x10batch_asset_root\x18\x05 \x01(\fR\x0ebatchAssetRoot\"\xbf\x02\n" + "\fAncestryPath\x12-\n" + "\ttree_path\x18\x01 \x01(\v2\x10.arkrpc.TreePathR\btreePath\x12'\n" + "\x0fcommitment_txid\x18\x02 \x01(\fR\x0ecommitmentTxid\x12#\n" + diff --git a/cmd/wavecli/waveclicommands/devrpc/registry_generated.go b/cmd/wavecli/waveclicommands/devrpc/registry_generated.go index d30ef739b..d3be4e03a 100644 --- a/cmd/wavecli/waveclicommands/devrpc/registry_generated.go +++ b/cmd/wavecli/waveclicommands/devrpc/registry_generated.go @@ -149,6 +149,13 @@ func generatedRegistry() []serviceSpec { Output: "waverpc.SendOORResponse", Comments: "SendOOR initiates an out-of-round transfer directly between the\nclient and operator, without waiting for a round.", }, + { + Name: "SendAssetOOR", + Aliases: []string{"send-asset-oor"}, + Input: "waverpc.SendAssetOORRequest", + Output: "waverpc.SendAssetOORResponse", + Comments: "SendAssetOOR initiates an out-of-round Taproot Asset transfer directly\nbetween the client and operator, merging up to eight live asset VTXOs\nand leasing an operator carrier float for the new asset leaves.", + }, { Name: "PrepareOOR", Aliases: []string{"prepare-oor"}, diff --git a/rpc/restclient/clients.go b/rpc/restclient/clients.go index 049f0663f..f9024ce82 100644 --- a/rpc/restclient/clients.go +++ b/rpc/restclient/clients.go @@ -581,6 +581,17 @@ func (c *DaemonServiceClient) SendOOR(ctx context.Context, return out, err } +// SendAssetOOR initiates an out-of-round Taproot Asset VTXO transfer. +func (c *DaemonServiceClient) SendAssetOOR(ctx context.Context, + in *waverpc.SendAssetOORRequest, _ ...grpc.CallOption) ( + *waverpc.SendAssetOORResponse, error) { + + out := new(waverpc.SendAssetOORResponse) + err := c.client.Post(ctx, "/v1/daemon/send-asset-oor", in, out) + + return out, err +} + // PrepareOOR builds an out-of-round transfer package without submitting it. func (c *DaemonServiceClient) PrepareOOR(ctx context.Context, in *waverpc.PrepareOORRequest, _ ...grpc.CallOption) ( diff --git a/waverpc/daemon.pb.go b/waverpc/daemon.pb.go index b5d132dbe..bae92cf2c 100644 --- a/waverpc/daemon.pb.go +++ b/waverpc/daemon.pb.go @@ -4387,6 +4387,253 @@ func (x *SendOORResponse) GetFailedBeforePonr() bool { return false } +type SendAssetOORRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + // asset_ref is the canonical SDK asset reference (asset ID or group key) + // of the Taproot Asset to send. + AssetRef string `protobuf:"bytes,1,opt,name=asset_ref,json=assetRef,proto3" json:"asset_ref,omitempty"` + // amount is the number of asset units to send to the recipient. + Amount uint64 `protobuf:"varint,2,opt,name=amount,proto3" json:"amount,omitempty"` + // destination selects the recipient's uncomposed Ark VTXO policy. A raw + // address is omitted because asset outputs must commit to an explicit + // uncomposed Ark policy before composing the Taproot Asset root. + // + // Types that are valid to be assigned to Destination: + // + // *SendAssetOORRequest_Pubkey + // *SendAssetOORRequest_PolicyTemplate + Destination isSendAssetOORRequest_Destination `protobuf_oneof:"destination"` + // dry_run validates the request, operator terms, and asset input + // availability without leasing a carrier float or submitting a transfer. + DryRun bool `protobuf:"varint,5,opt,name=dry_run,json=dryRun,proto3" json:"dry_run,omitempty"` + // idempotency_key is an optional caller-provided key that identifies + // this send intent across crashes and retries. + IdempotencyKey string `protobuf:"bytes,6,opt,name=idempotency_key,json=idempotencyKey,proto3" json:"idempotency_key,omitempty"` + // admission_deadline_unix_nanos is the latest wall-clock time at which + // the daemon may admit a new transfer for this request. Zero leaves + // admission unbounded. + AdmissionDeadlineUnixNanos int64 `protobuf:"varint,7,opt,name=admission_deadline_unix_nanos,json=admissionDeadlineUnixNanos,proto3" json:"admission_deadline_unix_nanos,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SendAssetOORRequest) Reset() { + *x = SendAssetOORRequest{} + mi := &file_daemon_proto_msgTypes[44] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SendAssetOORRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SendAssetOORRequest) ProtoMessage() {} + +func (x *SendAssetOORRequest) ProtoReflect() protoreflect.Message { + mi := &file_daemon_proto_msgTypes[44] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SendAssetOORRequest.ProtoReflect.Descriptor instead. +func (*SendAssetOORRequest) Descriptor() ([]byte, []int) { + return file_daemon_proto_rawDescGZIP(), []int{44} +} + +func (x *SendAssetOORRequest) GetAssetRef() string { + if x != nil { + return x.AssetRef + } + return "" +} + +func (x *SendAssetOORRequest) GetAmount() uint64 { + if x != nil { + return x.Amount + } + return 0 +} + +func (x *SendAssetOORRequest) GetDestination() isSendAssetOORRequest_Destination { + if x != nil { + return x.Destination + } + return nil +} + +func (x *SendAssetOORRequest) GetPubkey() []byte { + if x != nil { + if x, ok := x.Destination.(*SendAssetOORRequest_Pubkey); ok { + return x.Pubkey + } + } + return nil +} + +func (x *SendAssetOORRequest) GetPolicyTemplate() []byte { + if x != nil { + if x, ok := x.Destination.(*SendAssetOORRequest_PolicyTemplate); ok { + return x.PolicyTemplate + } + } + return nil +} + +func (x *SendAssetOORRequest) GetDryRun() bool { + if x != nil { + return x.DryRun + } + return false +} + +func (x *SendAssetOORRequest) GetIdempotencyKey() string { + if x != nil { + return x.IdempotencyKey + } + return "" +} + +func (x *SendAssetOORRequest) GetAdmissionDeadlineUnixNanos() int64 { + if x != nil { + return x.AdmissionDeadlineUnixNanos + } + return 0 +} + +type isSendAssetOORRequest_Destination interface { + isSendAssetOORRequest_Destination() +} + +type SendAssetOORRequest_Pubkey struct { + // pubkey is the 32-byte x-only (Schnorr) public key of the recipient. + // The daemon derives the standard Ark VTXO policy using the + // operator's key and exit delay. + Pubkey []byte `protobuf:"bytes,3,opt,name=pubkey,proto3,oneof"` +} + +type SendAssetOORRequest_PolicyTemplate struct { + // policy_template is the serialized uncomposed arkscript policy for + // the recipient VTXO. + PolicyTemplate []byte `protobuf:"bytes,4,opt,name=policy_template,json=policyTemplate,proto3,oneof"` +} + +func (*SendAssetOORRequest_Pubkey) isSendAssetOORRequest_Destination() {} + +func (*SendAssetOORRequest_PolicyTemplate) isSendAssetOORRequest_Destination() {} + +type SendAssetOORResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + // status is the result: "submitted" on success, "failed" when replay + // finds a known terminal failure, or "preview" on dry_run. + Status string `protobuf:"bytes,1,opt,name=status,proto3" json:"status,omitempty"` + // session_id is the OOR session identifier (Ark txid). Empty on dry_run. + SessionId string `protobuf:"bytes,2,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"` + // recipient_outpoint is the Ark transaction outpoint created for the + // recipient asset output. Empty on dry_run or when unavailable. + RecipientOutpoint string `protobuf:"bytes,3,opt,name=recipient_outpoint,json=recipientOutpoint,proto3" json:"recipient_outpoint,omitempty"` + // selected_input_count is the number of live asset VTXOs merged by this + // transfer. + SelectedInputCount uint32 `protobuf:"varint,4,opt,name=selected_input_count,json=selectedInputCount,proto3" json:"selected_input_count,omitempty"` + // asset_change_amount is the surplus asset units returned to the sender + // as a new asset VTXO. Zero when the selected inputs match amount + // exactly. + AssetChangeAmount uint64 `protobuf:"varint,5,opt,name=asset_change_amount,json=assetChangeAmount,proto3" json:"asset_change_amount,omitempty"` + // sender_btc_change_sat is the round-originated Bitcoin carrier returned + // to the sender as a plain Bitcoin VTXO. + SenderBtcChangeSat int64 `protobuf:"varint,6,opt,name=sender_btc_change_sat,json=senderBtcChangeSat,proto3" json:"sender_btc_change_sat,omitempty"` + // failed_before_ponr is set only on a replay with status "failed" when + // the session provably failed before the point of no return. + FailedBeforePonr bool `protobuf:"varint,7,opt,name=failed_before_ponr,json=failedBeforePonr,proto3" json:"failed_before_ponr,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SendAssetOORResponse) Reset() { + *x = SendAssetOORResponse{} + mi := &file_daemon_proto_msgTypes[45] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SendAssetOORResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SendAssetOORResponse) ProtoMessage() {} + +func (x *SendAssetOORResponse) ProtoReflect() protoreflect.Message { + mi := &file_daemon_proto_msgTypes[45] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SendAssetOORResponse.ProtoReflect.Descriptor instead. +func (*SendAssetOORResponse) Descriptor() ([]byte, []int) { + return file_daemon_proto_rawDescGZIP(), []int{45} +} + +func (x *SendAssetOORResponse) GetStatus() string { + if x != nil { + return x.Status + } + return "" +} + +func (x *SendAssetOORResponse) GetSessionId() string { + if x != nil { + return x.SessionId + } + return "" +} + +func (x *SendAssetOORResponse) GetRecipientOutpoint() string { + if x != nil { + return x.RecipientOutpoint + } + return "" +} + +func (x *SendAssetOORResponse) GetSelectedInputCount() uint32 { + if x != nil { + return x.SelectedInputCount + } + return 0 +} + +func (x *SendAssetOORResponse) GetAssetChangeAmount() uint64 { + if x != nil { + return x.AssetChangeAmount + } + return 0 +} + +func (x *SendAssetOORResponse) GetSenderBtcChangeSat() int64 { + if x != nil { + return x.SenderBtcChangeSat + } + return 0 +} + +func (x *SendAssetOORResponse) GetFailedBeforePonr() bool { + if x != nil { + return x.FailedBeforePonr + } + return false +} + type PrepareOORRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // recipient is the output to create via the out-of-round transfer. @@ -4401,7 +4648,7 @@ type PrepareOORRequest struct { func (x *PrepareOORRequest) Reset() { *x = PrepareOORRequest{} - mi := &file_daemon_proto_msgTypes[44] + mi := &file_daemon_proto_msgTypes[46] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4413,7 +4660,7 @@ func (x *PrepareOORRequest) String() string { func (*PrepareOORRequest) ProtoMessage() {} func (x *PrepareOORRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[44] + mi := &file_daemon_proto_msgTypes[46] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4426,7 +4673,7 @@ func (x *PrepareOORRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use PrepareOORRequest.ProtoReflect.Descriptor instead. func (*PrepareOORRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{44} + return file_daemon_proto_rawDescGZIP(), []int{46} } func (x *PrepareOORRequest) GetRecipient() *Output { @@ -4461,7 +4708,7 @@ type PreparedOORCustomInput struct { func (x *PreparedOORCustomInput) Reset() { *x = PreparedOORCustomInput{} - mi := &file_daemon_proto_msgTypes[45] + mi := &file_daemon_proto_msgTypes[47] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4473,7 +4720,7 @@ func (x *PreparedOORCustomInput) String() string { func (*PreparedOORCustomInput) ProtoMessage() {} func (x *PreparedOORCustomInput) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[45] + mi := &file_daemon_proto_msgTypes[47] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4486,7 +4733,7 @@ func (x *PreparedOORCustomInput) ProtoReflect() protoreflect.Message { // Deprecated: Use PreparedOORCustomInput.ProtoReflect.Descriptor instead. func (*PreparedOORCustomInput) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{45} + return file_daemon_proto_rawDescGZIP(), []int{47} } func (x *PreparedOORCustomInput) GetOutpoint() string { @@ -4534,7 +4781,7 @@ type PrepareOORResponse struct { func (x *PrepareOORResponse) Reset() { *x = PrepareOORResponse{} - mi := &file_daemon_proto_msgTypes[46] + mi := &file_daemon_proto_msgTypes[48] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4546,7 +4793,7 @@ func (x *PrepareOORResponse) String() string { func (*PrepareOORResponse) ProtoMessage() {} func (x *PrepareOORResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[46] + mi := &file_daemon_proto_msgTypes[48] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4559,7 +4806,7 @@ func (x *PrepareOORResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use PrepareOORResponse.ProtoReflect.Descriptor instead. func (*PrepareOORResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{46} + return file_daemon_proto_rawDescGZIP(), []int{48} } func (x *PrepareOORResponse) GetArkPsbt() []byte { @@ -4604,7 +4851,7 @@ type SignOORCustomInputRequest struct { func (x *SignOORCustomInputRequest) Reset() { *x = SignOORCustomInputRequest{} - mi := &file_daemon_proto_msgTypes[47] + mi := &file_daemon_proto_msgTypes[49] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4616,7 +4863,7 @@ func (x *SignOORCustomInputRequest) String() string { func (*SignOORCustomInputRequest) ProtoMessage() {} func (x *SignOORCustomInputRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[47] + mi := &file_daemon_proto_msgTypes[49] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4629,7 +4876,7 @@ func (x *SignOORCustomInputRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use SignOORCustomInputRequest.ProtoReflect.Descriptor instead. func (*SignOORCustomInputRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{47} + return file_daemon_proto_rawDescGZIP(), []int{49} } func (x *SignOORCustomInputRequest) GetCustomInput() *CustomOORInput { @@ -4665,7 +4912,7 @@ type SignOORCustomInputResponse struct { func (x *SignOORCustomInputResponse) Reset() { *x = SignOORCustomInputResponse{} - mi := &file_daemon_proto_msgTypes[48] + mi := &file_daemon_proto_msgTypes[50] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4677,7 +4924,7 @@ func (x *SignOORCustomInputResponse) String() string { func (*SignOORCustomInputResponse) ProtoMessage() {} func (x *SignOORCustomInputResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[48] + mi := &file_daemon_proto_msgTypes[50] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4690,7 +4937,7 @@ func (x *SignOORCustomInputResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use SignOORCustomInputResponse.ProtoReflect.Descriptor instead. func (*SignOORCustomInputResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{48} + return file_daemon_proto_rawDescGZIP(), []int{50} } func (x *SignOORCustomInputResponse) GetSignature() *TaprootScriptSignature { @@ -4738,7 +4985,7 @@ type SignVTXOForfeitRequest struct { func (x *SignVTXOForfeitRequest) Reset() { *x = SignVTXOForfeitRequest{} - mi := &file_daemon_proto_msgTypes[49] + mi := &file_daemon_proto_msgTypes[51] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4750,7 +4997,7 @@ func (x *SignVTXOForfeitRequest) String() string { func (*SignVTXOForfeitRequest) ProtoMessage() {} func (x *SignVTXOForfeitRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[49] + mi := &file_daemon_proto_msgTypes[51] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4763,7 +5010,7 @@ func (x *SignVTXOForfeitRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use SignVTXOForfeitRequest.ProtoReflect.Descriptor instead. func (*SignVTXOForfeitRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{49} + return file_daemon_proto_rawDescGZIP(), []int{51} } func (x *SignVTXOForfeitRequest) GetVtxoOutpoint() string { @@ -4848,7 +5095,7 @@ type SignVTXOForfeitResponse struct { func (x *SignVTXOForfeitResponse) Reset() { *x = SignVTXOForfeitResponse{} - mi := &file_daemon_proto_msgTypes[50] + mi := &file_daemon_proto_msgTypes[52] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4860,7 +5107,7 @@ func (x *SignVTXOForfeitResponse) String() string { func (*SignVTXOForfeitResponse) ProtoMessage() {} func (x *SignVTXOForfeitResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[50] + mi := &file_daemon_proto_msgTypes[52] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4873,7 +5120,7 @@ func (x *SignVTXOForfeitResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use SignVTXOForfeitResponse.ProtoReflect.Descriptor instead. func (*SignVTXOForfeitResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{50} + return file_daemon_proto_rawDescGZIP(), []int{52} } func (x *SignVTXOForfeitResponse) GetPubkey() []byte { @@ -4911,7 +5158,7 @@ type ForfeitSigningContext struct { func (x *ForfeitSigningContext) Reset() { *x = ForfeitSigningContext{} - mi := &file_daemon_proto_msgTypes[51] + mi := &file_daemon_proto_msgTypes[53] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4923,7 +5170,7 @@ func (x *ForfeitSigningContext) String() string { func (*ForfeitSigningContext) ProtoMessage() {} func (x *ForfeitSigningContext) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[51] + mi := &file_daemon_proto_msgTypes[53] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4936,7 +5183,7 @@ func (x *ForfeitSigningContext) ProtoReflect() protoreflect.Message { // Deprecated: Use ForfeitSigningContext.ProtoReflect.Descriptor instead. func (*ForfeitSigningContext) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{51} + return file_daemon_proto_rawDescGZIP(), []int{53} } func (x *ForfeitSigningContext) GetPaymentHash() []byte { @@ -4966,7 +5213,7 @@ type OutpointSelection struct { func (x *OutpointSelection) Reset() { *x = OutpointSelection{} - mi := &file_daemon_proto_msgTypes[52] + mi := &file_daemon_proto_msgTypes[54] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4978,7 +5225,7 @@ func (x *OutpointSelection) String() string { func (*OutpointSelection) ProtoMessage() {} func (x *OutpointSelection) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[52] + mi := &file_daemon_proto_msgTypes[54] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4991,7 +5238,7 @@ func (x *OutpointSelection) ProtoReflect() protoreflect.Message { // Deprecated: Use OutpointSelection.ProtoReflect.Descriptor instead. func (*OutpointSelection) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{52} + return file_daemon_proto_rawDescGZIP(), []int{54} } func (x *OutpointSelection) GetOutpoints() []string { @@ -5016,7 +5263,7 @@ type RefreshVTXOsRequest struct { func (x *RefreshVTXOsRequest) Reset() { *x = RefreshVTXOsRequest{} - mi := &file_daemon_proto_msgTypes[53] + mi := &file_daemon_proto_msgTypes[55] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5028,7 +5275,7 @@ func (x *RefreshVTXOsRequest) String() string { func (*RefreshVTXOsRequest) ProtoMessage() {} func (x *RefreshVTXOsRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[53] + mi := &file_daemon_proto_msgTypes[55] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5041,7 +5288,7 @@ func (x *RefreshVTXOsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use RefreshVTXOsRequest.ProtoReflect.Descriptor instead. func (*RefreshVTXOsRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{53} + return file_daemon_proto_rawDescGZIP(), []int{55} } func (x *RefreshVTXOsRequest) GetSelection() isRefreshVTXOsRequest_Selection { @@ -5113,7 +5360,7 @@ type RefreshVTXOsResponse struct { func (x *RefreshVTXOsResponse) Reset() { *x = RefreshVTXOsResponse{} - mi := &file_daemon_proto_msgTypes[54] + mi := &file_daemon_proto_msgTypes[56] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5125,7 +5372,7 @@ func (x *RefreshVTXOsResponse) String() string { func (*RefreshVTXOsResponse) ProtoMessage() {} func (x *RefreshVTXOsResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[54] + mi := &file_daemon_proto_msgTypes[56] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5138,7 +5385,7 @@ func (x *RefreshVTXOsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use RefreshVTXOsResponse.ProtoReflect.Descriptor instead. func (*RefreshVTXOsResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{54} + return file_daemon_proto_rawDescGZIP(), []int{56} } func (x *RefreshVTXOsResponse) GetQueuedOutpoints() []string { @@ -5204,7 +5451,7 @@ type RefreshFeeEstimate struct { func (x *RefreshFeeEstimate) Reset() { *x = RefreshFeeEstimate{} - mi := &file_daemon_proto_msgTypes[55] + mi := &file_daemon_proto_msgTypes[57] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5216,7 +5463,7 @@ func (x *RefreshFeeEstimate) String() string { func (*RefreshFeeEstimate) ProtoMessage() {} func (x *RefreshFeeEstimate) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[55] + mi := &file_daemon_proto_msgTypes[57] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5229,7 +5476,7 @@ func (x *RefreshFeeEstimate) ProtoReflect() protoreflect.Message { // Deprecated: Use RefreshFeeEstimate.ProtoReflect.Descriptor instead. func (*RefreshFeeEstimate) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{55} + return file_daemon_proto_rawDescGZIP(), []int{57} } func (x *RefreshFeeEstimate) GetEstimatedTotalFeeSat() int64 { @@ -5297,7 +5544,7 @@ type OutpointFeeEstimate struct { func (x *OutpointFeeEstimate) Reset() { *x = OutpointFeeEstimate{} - mi := &file_daemon_proto_msgTypes[56] + mi := &file_daemon_proto_msgTypes[58] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5309,7 +5556,7 @@ func (x *OutpointFeeEstimate) String() string { func (*OutpointFeeEstimate) ProtoMessage() {} func (x *OutpointFeeEstimate) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[56] + mi := &file_daemon_proto_msgTypes[58] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5322,7 +5569,7 @@ func (x *OutpointFeeEstimate) ProtoReflect() protoreflect.Message { // Deprecated: Use OutpointFeeEstimate.ProtoReflect.Descriptor instead. func (*OutpointFeeEstimate) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{56} + return file_daemon_proto_rawDescGZIP(), []int{58} } func (x *OutpointFeeEstimate) GetOutpoint() string { @@ -5422,7 +5669,7 @@ type CustomRefreshVTXOInput struct { func (x *CustomRefreshVTXOInput) Reset() { *x = CustomRefreshVTXOInput{} - mi := &file_daemon_proto_msgTypes[57] + mi := &file_daemon_proto_msgTypes[59] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5434,7 +5681,7 @@ func (x *CustomRefreshVTXOInput) String() string { func (*CustomRefreshVTXOInput) ProtoMessage() {} func (x *CustomRefreshVTXOInput) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[57] + mi := &file_daemon_proto_msgTypes[59] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5447,7 +5694,7 @@ func (x *CustomRefreshVTXOInput) ProtoReflect() protoreflect.Message { // Deprecated: Use CustomRefreshVTXOInput.ProtoReflect.Descriptor instead. func (*CustomRefreshVTXOInput) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{57} + return file_daemon_proto_rawDescGZIP(), []int{59} } func (x *CustomRefreshVTXOInput) GetOutpoint() string { @@ -5521,7 +5768,7 @@ type CustomRefreshVTXOOutput struct { func (x *CustomRefreshVTXOOutput) Reset() { *x = CustomRefreshVTXOOutput{} - mi := &file_daemon_proto_msgTypes[58] + mi := &file_daemon_proto_msgTypes[60] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5533,7 +5780,7 @@ func (x *CustomRefreshVTXOOutput) String() string { func (*CustomRefreshVTXOOutput) ProtoMessage() {} func (x *CustomRefreshVTXOOutput) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[58] + mi := &file_daemon_proto_msgTypes[60] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5546,7 +5793,7 @@ func (x *CustomRefreshVTXOOutput) ProtoReflect() protoreflect.Message { // Deprecated: Use CustomRefreshVTXOOutput.ProtoReflect.Descriptor instead. func (*CustomRefreshVTXOOutput) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{58} + return file_daemon_proto_rawDescGZIP(), []int{60} } func (x *CustomRefreshVTXOOutput) GetAmountSat() int64 { @@ -5593,7 +5840,7 @@ type RefreshCustomVTXOsRequest struct { func (x *RefreshCustomVTXOsRequest) Reset() { *x = RefreshCustomVTXOsRequest{} - mi := &file_daemon_proto_msgTypes[59] + mi := &file_daemon_proto_msgTypes[61] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5605,7 +5852,7 @@ func (x *RefreshCustomVTXOsRequest) String() string { func (*RefreshCustomVTXOsRequest) ProtoMessage() {} func (x *RefreshCustomVTXOsRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[59] + mi := &file_daemon_proto_msgTypes[61] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5618,7 +5865,7 @@ func (x *RefreshCustomVTXOsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use RefreshCustomVTXOsRequest.ProtoReflect.Descriptor instead. func (*RefreshCustomVTXOsRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{59} + return file_daemon_proto_rawDescGZIP(), []int{61} } func (x *RefreshCustomVTXOsRequest) GetInputs() []*CustomRefreshVTXOInput { @@ -5654,7 +5901,7 @@ type RefreshCustomVTXOsResponse struct { func (x *RefreshCustomVTXOsResponse) Reset() { *x = RefreshCustomVTXOsResponse{} - mi := &file_daemon_proto_msgTypes[60] + mi := &file_daemon_proto_msgTypes[62] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5666,7 +5913,7 @@ func (x *RefreshCustomVTXOsResponse) String() string { func (*RefreshCustomVTXOsResponse) ProtoMessage() {} func (x *RefreshCustomVTXOsResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[60] + mi := &file_daemon_proto_msgTypes[62] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5679,7 +5926,7 @@ func (x *RefreshCustomVTXOsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use RefreshCustomVTXOsResponse.ProtoReflect.Descriptor instead. func (*RefreshCustomVTXOsResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{60} + return file_daemon_proto_rawDescGZIP(), []int{62} } func (x *RefreshCustomVTXOsResponse) GetQueuedOutpoints() []string { @@ -5748,7 +5995,7 @@ type PendingForfeitParticipantSignatureRequest struct { func (x *PendingForfeitParticipantSignatureRequest) Reset() { *x = PendingForfeitParticipantSignatureRequest{} - mi := &file_daemon_proto_msgTypes[61] + mi := &file_daemon_proto_msgTypes[63] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5760,7 +6007,7 @@ func (x *PendingForfeitParticipantSignatureRequest) String() string { func (*PendingForfeitParticipantSignatureRequest) ProtoMessage() {} func (x *PendingForfeitParticipantSignatureRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[61] + mi := &file_daemon_proto_msgTypes[63] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5773,7 +6020,7 @@ func (x *PendingForfeitParticipantSignatureRequest) ProtoReflect() protoreflect. // Deprecated: Use PendingForfeitParticipantSignatureRequest.ProtoReflect.Descriptor instead. func (*PendingForfeitParticipantSignatureRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{61} + return file_daemon_proto_rawDescGZIP(), []int{63} } func (x *PendingForfeitParticipantSignatureRequest) GetRequestId() []byte { @@ -5887,7 +6134,7 @@ type ListPendingForfeitParticipantSignatureRequestsRequest struct { func (x *ListPendingForfeitParticipantSignatureRequestsRequest) Reset() { *x = ListPendingForfeitParticipantSignatureRequestsRequest{} - mi := &file_daemon_proto_msgTypes[62] + mi := &file_daemon_proto_msgTypes[64] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5899,7 +6146,7 @@ func (x *ListPendingForfeitParticipantSignatureRequestsRequest) String() string func (*ListPendingForfeitParticipantSignatureRequestsRequest) ProtoMessage() {} func (x *ListPendingForfeitParticipantSignatureRequestsRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[62] + mi := &file_daemon_proto_msgTypes[64] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5912,7 +6159,7 @@ func (x *ListPendingForfeitParticipantSignatureRequestsRequest) ProtoReflect() p // Deprecated: Use ListPendingForfeitParticipantSignatureRequestsRequest.ProtoReflect.Descriptor instead. func (*ListPendingForfeitParticipantSignatureRequestsRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{62} + return file_daemon_proto_rawDescGZIP(), []int{64} } func (x *ListPendingForfeitParticipantSignatureRequestsRequest) GetAfterSequence() uint64 { @@ -5939,7 +6186,7 @@ type ListPendingForfeitParticipantSignatureRequestsResponse struct { func (x *ListPendingForfeitParticipantSignatureRequestsResponse) Reset() { *x = ListPendingForfeitParticipantSignatureRequestsResponse{} - mi := &file_daemon_proto_msgTypes[63] + mi := &file_daemon_proto_msgTypes[65] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5951,7 +6198,7 @@ func (x *ListPendingForfeitParticipantSignatureRequestsResponse) String() string func (*ListPendingForfeitParticipantSignatureRequestsResponse) ProtoMessage() {} func (x *ListPendingForfeitParticipantSignatureRequestsResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[63] + mi := &file_daemon_proto_msgTypes[65] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5964,7 +6211,7 @@ func (x *ListPendingForfeitParticipantSignatureRequestsResponse) ProtoReflect() // Deprecated: Use ListPendingForfeitParticipantSignatureRequestsResponse.ProtoReflect.Descriptor instead. func (*ListPendingForfeitParticipantSignatureRequestsResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{63} + return file_daemon_proto_rawDescGZIP(), []int{65} } func (x *ListPendingForfeitParticipantSignatureRequestsResponse) GetRequests() []*PendingForfeitParticipantSignatureRequest { @@ -5996,7 +6243,7 @@ type ForfeitParticipantSignature struct { func (x *ForfeitParticipantSignature) Reset() { *x = ForfeitParticipantSignature{} - mi := &file_daemon_proto_msgTypes[64] + mi := &file_daemon_proto_msgTypes[66] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6008,7 +6255,7 @@ func (x *ForfeitParticipantSignature) String() string { func (*ForfeitParticipantSignature) ProtoMessage() {} func (x *ForfeitParticipantSignature) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[64] + mi := &file_daemon_proto_msgTypes[66] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6021,7 +6268,7 @@ func (x *ForfeitParticipantSignature) ProtoReflect() protoreflect.Message { // Deprecated: Use ForfeitParticipantSignature.ProtoReflect.Descriptor instead. func (*ForfeitParticipantSignature) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{64} + return file_daemon_proto_rawDescGZIP(), []int{66} } func (x *ForfeitParticipantSignature) GetPubkey() []byte { @@ -6055,7 +6302,7 @@ type SubmitForfeitParticipantSignaturesRequest struct { func (x *SubmitForfeitParticipantSignaturesRequest) Reset() { *x = SubmitForfeitParticipantSignaturesRequest{} - mi := &file_daemon_proto_msgTypes[65] + mi := &file_daemon_proto_msgTypes[67] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6067,7 +6314,7 @@ func (x *SubmitForfeitParticipantSignaturesRequest) String() string { func (*SubmitForfeitParticipantSignaturesRequest) ProtoMessage() {} func (x *SubmitForfeitParticipantSignaturesRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[65] + mi := &file_daemon_proto_msgTypes[67] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6080,7 +6327,7 @@ func (x *SubmitForfeitParticipantSignaturesRequest) ProtoReflect() protoreflect. // Deprecated: Use SubmitForfeitParticipantSignaturesRequest.ProtoReflect.Descriptor instead. func (*SubmitForfeitParticipantSignaturesRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{65} + return file_daemon_proto_rawDescGZIP(), []int{67} } func (x *SubmitForfeitParticipantSignaturesRequest) GetRequestId() []byte { @@ -6105,7 +6352,7 @@ type SubmitForfeitParticipantSignaturesResponse struct { func (x *SubmitForfeitParticipantSignaturesResponse) Reset() { *x = SubmitForfeitParticipantSignaturesResponse{} - mi := &file_daemon_proto_msgTypes[66] + mi := &file_daemon_proto_msgTypes[68] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6117,7 +6364,7 @@ func (x *SubmitForfeitParticipantSignaturesResponse) String() string { func (*SubmitForfeitParticipantSignaturesResponse) ProtoMessage() {} func (x *SubmitForfeitParticipantSignaturesResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[66] + mi := &file_daemon_proto_msgTypes[68] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6130,7 +6377,7 @@ func (x *SubmitForfeitParticipantSignaturesResponse) ProtoReflect() protoreflect // Deprecated: Use SubmitForfeitParticipantSignaturesResponse.ProtoReflect.Descriptor instead. func (*SubmitForfeitParticipantSignaturesResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{66} + return file_daemon_proto_rawDescGZIP(), []int{68} } // LeaveDestination describes where a single leave output should land. @@ -6150,7 +6397,7 @@ type LeaveDestination struct { func (x *LeaveDestination) Reset() { *x = LeaveDestination{} - mi := &file_daemon_proto_msgTypes[67] + mi := &file_daemon_proto_msgTypes[69] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6162,7 +6409,7 @@ func (x *LeaveDestination) String() string { func (*LeaveDestination) ProtoMessage() {} func (x *LeaveDestination) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[67] + mi := &file_daemon_proto_msgTypes[69] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6175,7 +6422,7 @@ func (x *LeaveDestination) ProtoReflect() protoreflect.Message { // Deprecated: Use LeaveDestination.ProtoReflect.Descriptor instead. func (*LeaveDestination) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{67} + return file_daemon_proto_rawDescGZIP(), []int{69} } func (x *LeaveDestination) GetTarget() isLeaveDestination_Target { @@ -6256,7 +6503,7 @@ type LeaveVTXOsRequest struct { func (x *LeaveVTXOsRequest) Reset() { *x = LeaveVTXOsRequest{} - mi := &file_daemon_proto_msgTypes[68] + mi := &file_daemon_proto_msgTypes[70] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6268,7 +6515,7 @@ func (x *LeaveVTXOsRequest) String() string { func (*LeaveVTXOsRequest) ProtoMessage() {} func (x *LeaveVTXOsRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[68] + mi := &file_daemon_proto_msgTypes[70] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6281,7 +6528,7 @@ func (x *LeaveVTXOsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use LeaveVTXOsRequest.ProtoReflect.Descriptor instead. func (*LeaveVTXOsRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{68} + return file_daemon_proto_rawDescGZIP(), []int{70} } func (x *LeaveVTXOsRequest) GetSelection() isLeaveVTXOsRequest_Selection { @@ -6367,7 +6614,7 @@ type LeaveVTXOsResponse struct { func (x *LeaveVTXOsResponse) Reset() { *x = LeaveVTXOsResponse{} - mi := &file_daemon_proto_msgTypes[69] + mi := &file_daemon_proto_msgTypes[71] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6379,7 +6626,7 @@ func (x *LeaveVTXOsResponse) String() string { func (*LeaveVTXOsResponse) ProtoMessage() {} func (x *LeaveVTXOsResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[69] + mi := &file_daemon_proto_msgTypes[71] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6392,7 +6639,7 @@ func (x *LeaveVTXOsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use LeaveVTXOsResponse.ProtoReflect.Descriptor instead. func (*LeaveVTXOsResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{69} + return file_daemon_proto_rawDescGZIP(), []int{71} } func (x *LeaveVTXOsResponse) GetQueuedOutpoints() []string { @@ -6437,7 +6684,7 @@ type SendOnChainRequest struct { func (x *SendOnChainRequest) Reset() { *x = SendOnChainRequest{} - mi := &file_daemon_proto_msgTypes[70] + mi := &file_daemon_proto_msgTypes[72] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6449,7 +6696,7 @@ func (x *SendOnChainRequest) String() string { func (*SendOnChainRequest) ProtoMessage() {} func (x *SendOnChainRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[70] + mi := &file_daemon_proto_msgTypes[72] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6462,7 +6709,7 @@ func (x *SendOnChainRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use SendOnChainRequest.ProtoReflect.Descriptor instead. func (*SendOnChainRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{70} + return file_daemon_proto_rawDescGZIP(), []int{72} } func (x *SendOnChainRequest) GetDestination() *LeaveDestination { @@ -6570,7 +6817,7 @@ type SendOnChainResponse struct { func (x *SendOnChainResponse) Reset() { *x = SendOnChainResponse{} - mi := &file_daemon_proto_msgTypes[71] + mi := &file_daemon_proto_msgTypes[73] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6582,7 +6829,7 @@ func (x *SendOnChainResponse) String() string { func (*SendOnChainResponse) ProtoMessage() {} func (x *SendOnChainResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[71] + mi := &file_daemon_proto_msgTypes[73] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6595,7 +6842,7 @@ func (x *SendOnChainResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use SendOnChainResponse.ProtoReflect.Descriptor instead. func (*SendOnChainResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{71} + return file_daemon_proto_rawDescGZIP(), []int{73} } func (x *SendOnChainResponse) GetActualAmountSat() int64 { @@ -6661,7 +6908,7 @@ type BoardRequest struct { func (x *BoardRequest) Reset() { *x = BoardRequest{} - mi := &file_daemon_proto_msgTypes[72] + mi := &file_daemon_proto_msgTypes[74] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6673,7 +6920,7 @@ func (x *BoardRequest) String() string { func (*BoardRequest) ProtoMessage() {} func (x *BoardRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[72] + mi := &file_daemon_proto_msgTypes[74] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6686,7 +6933,7 @@ func (x *BoardRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use BoardRequest.ProtoReflect.Descriptor instead. func (*BoardRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{72} + return file_daemon_proto_rawDescGZIP(), []int{74} } func (x *BoardRequest) GetTargetVtxoCount() uint32 { @@ -6717,7 +6964,7 @@ type BoardResponse struct { func (x *BoardResponse) Reset() { *x = BoardResponse{} - mi := &file_daemon_proto_msgTypes[73] + mi := &file_daemon_proto_msgTypes[75] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6729,7 +6976,7 @@ func (x *BoardResponse) String() string { func (*BoardResponse) ProtoMessage() {} func (x *BoardResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[73] + mi := &file_daemon_proto_msgTypes[75] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6742,7 +6989,7 @@ func (x *BoardResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use BoardResponse.ProtoReflect.Descriptor instead. func (*BoardResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{73} + return file_daemon_proto_rawDescGZIP(), []int{75} } func (x *BoardResponse) GetStatus() string { @@ -6783,7 +7030,7 @@ type DepositAssetRequest struct { func (x *DepositAssetRequest) Reset() { *x = DepositAssetRequest{} - mi := &file_daemon_proto_msgTypes[74] + mi := &file_daemon_proto_msgTypes[76] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6795,7 +7042,7 @@ func (x *DepositAssetRequest) String() string { func (*DepositAssetRequest) ProtoMessage() {} func (x *DepositAssetRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[74] + mi := &file_daemon_proto_msgTypes[76] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6808,7 +7055,7 @@ func (x *DepositAssetRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DepositAssetRequest.ProtoReflect.Descriptor instead. func (*DepositAssetRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{74} + return file_daemon_proto_rawDescGZIP(), []int{76} } func (x *DepositAssetRequest) GetRequestId() string { @@ -6861,7 +7108,7 @@ type ListAssetDepositsRequest struct { func (x *ListAssetDepositsRequest) Reset() { *x = ListAssetDepositsRequest{} - mi := &file_daemon_proto_msgTypes[75] + mi := &file_daemon_proto_msgTypes[77] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6873,7 +7120,7 @@ func (x *ListAssetDepositsRequest) String() string { func (*ListAssetDepositsRequest) ProtoMessage() {} func (x *ListAssetDepositsRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[75] + mi := &file_daemon_proto_msgTypes[77] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6886,7 +7133,7 @@ func (x *ListAssetDepositsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListAssetDepositsRequest.ProtoReflect.Descriptor instead. func (*ListAssetDepositsRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{75} + return file_daemon_proto_rawDescGZIP(), []int{77} } type BoardAssetDepositRequest struct { @@ -6899,7 +7146,7 @@ type BoardAssetDepositRequest struct { func (x *BoardAssetDepositRequest) Reset() { *x = BoardAssetDepositRequest{} - mi := &file_daemon_proto_msgTypes[76] + mi := &file_daemon_proto_msgTypes[78] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6911,7 +7158,7 @@ func (x *BoardAssetDepositRequest) String() string { func (*BoardAssetDepositRequest) ProtoMessage() {} func (x *BoardAssetDepositRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[76] + mi := &file_daemon_proto_msgTypes[78] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6924,7 +7171,7 @@ func (x *BoardAssetDepositRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use BoardAssetDepositRequest.ProtoReflect.Descriptor instead. func (*BoardAssetDepositRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{76} + return file_daemon_proto_rawDescGZIP(), []int{78} } func (x *BoardAssetDepositRequest) GetRequestId() string { @@ -6944,7 +7191,7 @@ type ClaimAssetDepositRequest struct { func (x *ClaimAssetDepositRequest) Reset() { *x = ClaimAssetDepositRequest{} - mi := &file_daemon_proto_msgTypes[77] + mi := &file_daemon_proto_msgTypes[79] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6956,7 +7203,7 @@ func (x *ClaimAssetDepositRequest) String() string { func (*ClaimAssetDepositRequest) ProtoMessage() {} func (x *ClaimAssetDepositRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[77] + mi := &file_daemon_proto_msgTypes[79] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6969,7 +7216,7 @@ func (x *ClaimAssetDepositRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ClaimAssetDepositRequest.ProtoReflect.Descriptor instead. func (*ClaimAssetDepositRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{77} + return file_daemon_proto_rawDescGZIP(), []int{79} } func (x *ClaimAssetDepositRequest) GetRequestId() string { @@ -6988,7 +7235,7 @@ type ListAssetDepositsResponse struct { func (x *ListAssetDepositsResponse) Reset() { *x = ListAssetDepositsResponse{} - mi := &file_daemon_proto_msgTypes[78] + mi := &file_daemon_proto_msgTypes[80] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7000,7 +7247,7 @@ func (x *ListAssetDepositsResponse) String() string { func (*ListAssetDepositsResponse) ProtoMessage() {} func (x *ListAssetDepositsResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[78] + mi := &file_daemon_proto_msgTypes[80] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7013,7 +7260,7 @@ func (x *ListAssetDepositsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListAssetDepositsResponse.ProtoReflect.Descriptor instead. func (*ListAssetDepositsResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{78} + return file_daemon_proto_rawDescGZIP(), []int{80} } func (x *ListAssetDepositsResponse) GetDeposits() []*AssetDeposit { @@ -7057,7 +7304,7 @@ type AssetDeposit struct { func (x *AssetDeposit) Reset() { *x = AssetDeposit{} - mi := &file_daemon_proto_msgTypes[79] + mi := &file_daemon_proto_msgTypes[81] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7069,7 +7316,7 @@ func (x *AssetDeposit) String() string { func (*AssetDeposit) ProtoMessage() {} func (x *AssetDeposit) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[79] + mi := &file_daemon_proto_msgTypes[81] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7082,7 +7329,7 @@ func (x *AssetDeposit) ProtoReflect() protoreflect.Message { // Deprecated: Use AssetDeposit.ProtoReflect.Descriptor instead. func (*AssetDeposit) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{79} + return file_daemon_proto_rawDescGZIP(), []int{81} } func (x *AssetDeposit) GetRequestId() string { @@ -7177,7 +7424,7 @@ type NewAssetReceiveKeysRequest struct { func (x *NewAssetReceiveKeysRequest) Reset() { *x = NewAssetReceiveKeysRequest{} - mi := &file_daemon_proto_msgTypes[80] + mi := &file_daemon_proto_msgTypes[82] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7189,7 +7436,7 @@ func (x *NewAssetReceiveKeysRequest) String() string { func (*NewAssetReceiveKeysRequest) ProtoMessage() {} func (x *NewAssetReceiveKeysRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[80] + mi := &file_daemon_proto_msgTypes[82] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7202,7 +7449,7 @@ func (x *NewAssetReceiveKeysRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use NewAssetReceiveKeysRequest.ProtoReflect.Descriptor instead. func (*NewAssetReceiveKeysRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{80} + return file_daemon_proto_rawDescGZIP(), []int{82} } type AssetReceiveKeys struct { @@ -7222,7 +7469,7 @@ type AssetReceiveKeys struct { func (x *AssetReceiveKeys) Reset() { *x = AssetReceiveKeys{} - mi := &file_daemon_proto_msgTypes[81] + mi := &file_daemon_proto_msgTypes[83] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7234,7 +7481,7 @@ func (x *AssetReceiveKeys) String() string { func (*AssetReceiveKeys) ProtoMessage() {} func (x *AssetReceiveKeys) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[81] + mi := &file_daemon_proto_msgTypes[83] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7247,7 +7494,7 @@ func (x *AssetReceiveKeys) ProtoReflect() protoreflect.Message { // Deprecated: Use AssetReceiveKeys.ProtoReflect.Descriptor instead. func (*AssetReceiveKeys) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{81} + return file_daemon_proto_rawDescGZIP(), []int{83} } func (x *AssetReceiveKeys) GetScriptKey() []byte { @@ -7286,7 +7533,7 @@ type ImportAssetProofRequest struct { func (x *ImportAssetProofRequest) Reset() { *x = ImportAssetProofRequest{} - mi := &file_daemon_proto_msgTypes[82] + mi := &file_daemon_proto_msgTypes[84] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7298,7 +7545,7 @@ func (x *ImportAssetProofRequest) String() string { func (*ImportAssetProofRequest) ProtoMessage() {} func (x *ImportAssetProofRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[82] + mi := &file_daemon_proto_msgTypes[84] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7311,7 +7558,7 @@ func (x *ImportAssetProofRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ImportAssetProofRequest.ProtoReflect.Descriptor instead. func (*ImportAssetProofRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{82} + return file_daemon_proto_rawDescGZIP(), []int{84} } func (x *ImportAssetProofRequest) GetProofFile() []byte { @@ -7336,7 +7583,7 @@ type NewAssetFundingAddressRequest struct { func (x *NewAssetFundingAddressRequest) Reset() { *x = NewAssetFundingAddressRequest{} - mi := &file_daemon_proto_msgTypes[83] + mi := &file_daemon_proto_msgTypes[85] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7348,7 +7595,7 @@ func (x *NewAssetFundingAddressRequest) String() string { func (*NewAssetFundingAddressRequest) ProtoMessage() {} func (x *NewAssetFundingAddressRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[83] + mi := &file_daemon_proto_msgTypes[85] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7361,7 +7608,7 @@ func (x *NewAssetFundingAddressRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use NewAssetFundingAddressRequest.ProtoReflect.Descriptor instead. func (*NewAssetFundingAddressRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{83} + return file_daemon_proto_rawDescGZIP(), []int{85} } type AssetFundingAddress struct { @@ -7374,7 +7621,7 @@ type AssetFundingAddress struct { func (x *AssetFundingAddress) Reset() { *x = AssetFundingAddress{} - mi := &file_daemon_proto_msgTypes[84] + mi := &file_daemon_proto_msgTypes[86] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7386,7 +7633,7 @@ func (x *AssetFundingAddress) String() string { func (*AssetFundingAddress) ProtoMessage() {} func (x *AssetFundingAddress) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[84] + mi := &file_daemon_proto_msgTypes[86] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7399,7 +7646,7 @@ func (x *AssetFundingAddress) ProtoReflect() protoreflect.Message { // Deprecated: Use AssetFundingAddress.ProtoReflect.Descriptor instead. func (*AssetFundingAddress) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{84} + return file_daemon_proto_rawDescGZIP(), []int{86} } func (x *AssetFundingAddress) GetAddress() string { @@ -7417,7 +7664,7 @@ type ListOwnedAssetsRequest struct { func (x *ListOwnedAssetsRequest) Reset() { *x = ListOwnedAssetsRequest{} - mi := &file_daemon_proto_msgTypes[85] + mi := &file_daemon_proto_msgTypes[87] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7429,7 +7676,7 @@ func (x *ListOwnedAssetsRequest) String() string { func (*ListOwnedAssetsRequest) ProtoMessage() {} func (x *ListOwnedAssetsRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[85] + mi := &file_daemon_proto_msgTypes[87] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7442,7 +7689,7 @@ func (x *ListOwnedAssetsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListOwnedAssetsRequest.ProtoReflect.Descriptor instead. func (*ListOwnedAssetsRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{85} + return file_daemon_proto_rawDescGZIP(), []int{87} } type ListOwnedAssetsResponse struct { @@ -7454,7 +7701,7 @@ type ListOwnedAssetsResponse struct { func (x *ListOwnedAssetsResponse) Reset() { *x = ListOwnedAssetsResponse{} - mi := &file_daemon_proto_msgTypes[86] + mi := &file_daemon_proto_msgTypes[88] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7466,7 +7713,7 @@ func (x *ListOwnedAssetsResponse) String() string { func (*ListOwnedAssetsResponse) ProtoMessage() {} func (x *ListOwnedAssetsResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[86] + mi := &file_daemon_proto_msgTypes[88] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7479,7 +7726,7 @@ func (x *ListOwnedAssetsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListOwnedAssetsResponse.ProtoReflect.Descriptor instead. func (*ListOwnedAssetsResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{86} + return file_daemon_proto_rawDescGZIP(), []int{88} } func (x *ListOwnedAssetsResponse) GetAssets() []*OwnedAsset { @@ -7510,7 +7757,7 @@ type OwnedAsset struct { func (x *OwnedAsset) Reset() { *x = OwnedAsset{} - mi := &file_daemon_proto_msgTypes[87] + mi := &file_daemon_proto_msgTypes[89] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7522,7 +7769,7 @@ func (x *OwnedAsset) String() string { func (*OwnedAsset) ProtoMessage() {} func (x *OwnedAsset) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[87] + mi := &file_daemon_proto_msgTypes[89] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7535,7 +7782,7 @@ func (x *OwnedAsset) ProtoReflect() protoreflect.Message { // Deprecated: Use OwnedAsset.ProtoReflect.Descriptor instead. func (*OwnedAsset) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{87} + return file_daemon_proto_rawDescGZIP(), []int{89} } func (x *OwnedAsset) GetAssetRef() string { @@ -7591,7 +7838,7 @@ type NewAssetAddressRequest struct { func (x *NewAssetAddressRequest) Reset() { *x = NewAssetAddressRequest{} - mi := &file_daemon_proto_msgTypes[88] + mi := &file_daemon_proto_msgTypes[90] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7603,7 +7850,7 @@ func (x *NewAssetAddressRequest) String() string { func (*NewAssetAddressRequest) ProtoMessage() {} func (x *NewAssetAddressRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[88] + mi := &file_daemon_proto_msgTypes[90] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7616,7 +7863,7 @@ func (x *NewAssetAddressRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use NewAssetAddressRequest.ProtoReflect.Descriptor instead. func (*NewAssetAddressRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{88} + return file_daemon_proto_rawDescGZIP(), []int{90} } func (x *NewAssetAddressRequest) GetAssetRef() string { @@ -7643,7 +7890,7 @@ type AssetAddress struct { func (x *AssetAddress) Reset() { *x = AssetAddress{} - mi := &file_daemon_proto_msgTypes[89] + mi := &file_daemon_proto_msgTypes[91] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7655,7 +7902,7 @@ func (x *AssetAddress) String() string { func (*AssetAddress) ProtoMessage() {} func (x *AssetAddress) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[89] + mi := &file_daemon_proto_msgTypes[91] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7668,7 +7915,7 @@ func (x *AssetAddress) ProtoReflect() protoreflect.Message { // Deprecated: Use AssetAddress.ProtoReflect.Descriptor instead. func (*AssetAddress) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{89} + return file_daemon_proto_rawDescGZIP(), []int{91} } func (x *AssetAddress) GetAddress() string { @@ -7700,7 +7947,7 @@ type ListAssetAddressesRequest struct { func (x *ListAssetAddressesRequest) Reset() { *x = ListAssetAddressesRequest{} - mi := &file_daemon_proto_msgTypes[90] + mi := &file_daemon_proto_msgTypes[92] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7712,7 +7959,7 @@ func (x *ListAssetAddressesRequest) String() string { func (*ListAssetAddressesRequest) ProtoMessage() {} func (x *ListAssetAddressesRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[90] + mi := &file_daemon_proto_msgTypes[92] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7725,7 +7972,7 @@ func (x *ListAssetAddressesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListAssetAddressesRequest.ProtoReflect.Descriptor instead. func (*ListAssetAddressesRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{90} + return file_daemon_proto_rawDescGZIP(), []int{92} } type ListAssetAddressesResponse struct { @@ -7737,7 +7984,7 @@ type ListAssetAddressesResponse struct { func (x *ListAssetAddressesResponse) Reset() { *x = ListAssetAddressesResponse{} - mi := &file_daemon_proto_msgTypes[91] + mi := &file_daemon_proto_msgTypes[93] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7749,7 +7996,7 @@ func (x *ListAssetAddressesResponse) String() string { func (*ListAssetAddressesResponse) ProtoMessage() {} func (x *ListAssetAddressesResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[91] + mi := &file_daemon_proto_msgTypes[93] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7762,7 +8009,7 @@ func (x *ListAssetAddressesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListAssetAddressesResponse.ProtoReflect.Descriptor instead. func (*ListAssetAddressesResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{91} + return file_daemon_proto_rawDescGZIP(), []int{93} } func (x *ListAssetAddressesResponse) GetAddresses() []*AssetAddress { @@ -7780,7 +8027,7 @@ type ListAssetReceivesRequest struct { func (x *ListAssetReceivesRequest) Reset() { *x = ListAssetReceivesRequest{} - mi := &file_daemon_proto_msgTypes[92] + mi := &file_daemon_proto_msgTypes[94] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7792,7 +8039,7 @@ func (x *ListAssetReceivesRequest) String() string { func (*ListAssetReceivesRequest) ProtoMessage() {} func (x *ListAssetReceivesRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[92] + mi := &file_daemon_proto_msgTypes[94] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7805,7 +8052,7 @@ func (x *ListAssetReceivesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListAssetReceivesRequest.ProtoReflect.Descriptor instead. func (*ListAssetReceivesRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{92} + return file_daemon_proto_rawDescGZIP(), []int{94} } type ListAssetReceivesResponse struct { @@ -7817,7 +8064,7 @@ type ListAssetReceivesResponse struct { func (x *ListAssetReceivesResponse) Reset() { *x = ListAssetReceivesResponse{} - mi := &file_daemon_proto_msgTypes[93] + mi := &file_daemon_proto_msgTypes[95] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7829,7 +8076,7 @@ func (x *ListAssetReceivesResponse) String() string { func (*ListAssetReceivesResponse) ProtoMessage() {} func (x *ListAssetReceivesResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[93] + mi := &file_daemon_proto_msgTypes[95] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7842,7 +8089,7 @@ func (x *ListAssetReceivesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListAssetReceivesResponse.ProtoReflect.Descriptor instead. func (*ListAssetReceivesResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{93} + return file_daemon_proto_rawDescGZIP(), []int{95} } func (x *ListAssetReceivesResponse) GetReceives() []*AssetReceive { @@ -7882,7 +8129,7 @@ type AssetReceive struct { func (x *AssetReceive) Reset() { *x = AssetReceive{} - mi := &file_daemon_proto_msgTypes[94] + mi := &file_daemon_proto_msgTypes[96] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7894,7 +8141,7 @@ func (x *AssetReceive) String() string { func (*AssetReceive) ProtoMessage() {} func (x *AssetReceive) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[94] + mi := &file_daemon_proto_msgTypes[96] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7907,7 +8154,7 @@ func (x *AssetReceive) ProtoReflect() protoreflect.Message { // Deprecated: Use AssetReceive.ProtoReflect.Descriptor instead. func (*AssetReceive) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{94} + return file_daemon_proto_rawDescGZIP(), []int{96} } func (x *AssetReceive) GetOutpoint() string { @@ -7967,7 +8214,7 @@ type SyncAssetReceivesRequest struct { func (x *SyncAssetReceivesRequest) Reset() { *x = SyncAssetReceivesRequest{} - mi := &file_daemon_proto_msgTypes[95] + mi := &file_daemon_proto_msgTypes[97] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7979,7 +8226,7 @@ func (x *SyncAssetReceivesRequest) String() string { func (*SyncAssetReceivesRequest) ProtoMessage() {} func (x *SyncAssetReceivesRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[95] + mi := &file_daemon_proto_msgTypes[97] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7992,7 +8239,7 @@ func (x *SyncAssetReceivesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use SyncAssetReceivesRequest.ProtoReflect.Descriptor instead. func (*SyncAssetReceivesRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{95} + return file_daemon_proto_rawDescGZIP(), []int{97} } type SyncAssetReceivesResponse struct { @@ -8003,7 +8250,7 @@ type SyncAssetReceivesResponse struct { func (x *SyncAssetReceivesResponse) Reset() { *x = SyncAssetReceivesResponse{} - mi := &file_daemon_proto_msgTypes[96] + mi := &file_daemon_proto_msgTypes[98] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8015,7 +8262,7 @@ func (x *SyncAssetReceivesResponse) String() string { func (*SyncAssetReceivesResponse) ProtoMessage() {} func (x *SyncAssetReceivesResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[96] + mi := &file_daemon_proto_msgTypes[98] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8028,7 +8275,7 @@ func (x *SyncAssetReceivesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use SyncAssetReceivesResponse.ProtoReflect.Descriptor instead. func (*SyncAssetReceivesResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{96} + return file_daemon_proto_rawDescGZIP(), []int{98} } type JoinNextRoundRequest struct { @@ -8039,7 +8286,7 @@ type JoinNextRoundRequest struct { func (x *JoinNextRoundRequest) Reset() { *x = JoinNextRoundRequest{} - mi := &file_daemon_proto_msgTypes[97] + mi := &file_daemon_proto_msgTypes[99] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8051,7 +8298,7 @@ func (x *JoinNextRoundRequest) String() string { func (*JoinNextRoundRequest) ProtoMessage() {} func (x *JoinNextRoundRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[97] + mi := &file_daemon_proto_msgTypes[99] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8064,7 +8311,7 @@ func (x *JoinNextRoundRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use JoinNextRoundRequest.ProtoReflect.Descriptor instead. func (*JoinNextRoundRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{97} + return file_daemon_proto_rawDescGZIP(), []int{99} } type JoinNextRoundResponse struct { @@ -8079,7 +8326,7 @@ type JoinNextRoundResponse struct { func (x *JoinNextRoundResponse) Reset() { *x = JoinNextRoundResponse{} - mi := &file_daemon_proto_msgTypes[98] + mi := &file_daemon_proto_msgTypes[100] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8091,7 +8338,7 @@ func (x *JoinNextRoundResponse) String() string { func (*JoinNextRoundResponse) ProtoMessage() {} func (x *JoinNextRoundResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[98] + mi := &file_daemon_proto_msgTypes[100] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8104,7 +8351,7 @@ func (x *JoinNextRoundResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use JoinNextRoundResponse.ProtoReflect.Descriptor instead. func (*JoinNextRoundResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{98} + return file_daemon_proto_rawDescGZIP(), []int{100} } func (x *JoinNextRoundResponse) GetStatus() string { @@ -8140,7 +8387,7 @@ type SweepBoardingUTXOsRequest struct { func (x *SweepBoardingUTXOsRequest) Reset() { *x = SweepBoardingUTXOsRequest{} - mi := &file_daemon_proto_msgTypes[99] + mi := &file_daemon_proto_msgTypes[101] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8152,7 +8399,7 @@ func (x *SweepBoardingUTXOsRequest) String() string { func (*SweepBoardingUTXOsRequest) ProtoMessage() {} func (x *SweepBoardingUTXOsRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[99] + mi := &file_daemon_proto_msgTypes[101] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8165,7 +8412,7 @@ func (x *SweepBoardingUTXOsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use SweepBoardingUTXOsRequest.ProtoReflect.Descriptor instead. func (*SweepBoardingUTXOsRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{99} + return file_daemon_proto_rawDescGZIP(), []int{101} } func (x *SweepBoardingUTXOsRequest) GetOutpoints() []string { @@ -8218,7 +8465,7 @@ type BoardingSweepOutput struct { func (x *BoardingSweepOutput) Reset() { *x = BoardingSweepOutput{} - mi := &file_daemon_proto_msgTypes[100] + mi := &file_daemon_proto_msgTypes[102] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8230,7 +8477,7 @@ func (x *BoardingSweepOutput) String() string { func (*BoardingSweepOutput) ProtoMessage() {} func (x *BoardingSweepOutput) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[100] + mi := &file_daemon_proto_msgTypes[102] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8243,7 +8490,7 @@ func (x *BoardingSweepOutput) ProtoReflect() protoreflect.Message { // Deprecated: Use BoardingSweepOutput.ProtoReflect.Descriptor instead. func (*BoardingSweepOutput) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{100} + return file_daemon_proto_rawDescGZIP(), []int{102} } func (x *BoardingSweepOutput) GetOutpoint() string { @@ -8315,7 +8562,7 @@ type SweepBoardingUTXOsResponse struct { func (x *SweepBoardingUTXOsResponse) Reset() { *x = SweepBoardingUTXOsResponse{} - mi := &file_daemon_proto_msgTypes[101] + mi := &file_daemon_proto_msgTypes[103] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8327,7 +8574,7 @@ func (x *SweepBoardingUTXOsResponse) String() string { func (*SweepBoardingUTXOsResponse) ProtoMessage() {} func (x *SweepBoardingUTXOsResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[101] + mi := &file_daemon_proto_msgTypes[103] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8340,7 +8587,7 @@ func (x *SweepBoardingUTXOsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use SweepBoardingUTXOsResponse.ProtoReflect.Descriptor instead. func (*SweepBoardingUTXOsResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{101} + return file_daemon_proto_rawDescGZIP(), []int{103} } func (x *SweepBoardingUTXOsResponse) GetStatus() string { @@ -8451,7 +8698,7 @@ type ListBoardingSweepsRequest struct { func (x *ListBoardingSweepsRequest) Reset() { *x = ListBoardingSweepsRequest{} - mi := &file_daemon_proto_msgTypes[102] + mi := &file_daemon_proto_msgTypes[104] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8463,7 +8710,7 @@ func (x *ListBoardingSweepsRequest) String() string { func (*ListBoardingSweepsRequest) ProtoMessage() {} func (x *ListBoardingSweepsRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[102] + mi := &file_daemon_proto_msgTypes[104] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8476,7 +8723,7 @@ func (x *ListBoardingSweepsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListBoardingSweepsRequest.ProtoReflect.Descriptor instead. func (*ListBoardingSweepsRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{102} + return file_daemon_proto_rawDescGZIP(), []int{104} } func (x *ListBoardingSweepsRequest) GetStatus() string { @@ -8519,7 +8766,7 @@ type BoardingSweepInput struct { func (x *BoardingSweepInput) Reset() { *x = BoardingSweepInput{} - mi := &file_daemon_proto_msgTypes[103] + mi := &file_daemon_proto_msgTypes[105] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8531,7 +8778,7 @@ func (x *BoardingSweepInput) String() string { func (*BoardingSweepInput) ProtoMessage() {} func (x *BoardingSweepInput) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[103] + mi := &file_daemon_proto_msgTypes[105] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8544,7 +8791,7 @@ func (x *BoardingSweepInput) ProtoReflect() protoreflect.Message { // Deprecated: Use BoardingSweepInput.ProtoReflect.Descriptor instead. func (*BoardingSweepInput) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{103} + return file_daemon_proto_rawDescGZIP(), []int{105} } func (x *BoardingSweepInput) GetOutpoint() string { @@ -8614,7 +8861,7 @@ type BoardingSweep struct { func (x *BoardingSweep) Reset() { *x = BoardingSweep{} - mi := &file_daemon_proto_msgTypes[104] + mi := &file_daemon_proto_msgTypes[106] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8626,7 +8873,7 @@ func (x *BoardingSweep) String() string { func (*BoardingSweep) ProtoMessage() {} func (x *BoardingSweep) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[104] + mi := &file_daemon_proto_msgTypes[106] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8639,7 +8886,7 @@ func (x *BoardingSweep) ProtoReflect() protoreflect.Message { // Deprecated: Use BoardingSweep.ProtoReflect.Descriptor instead. func (*BoardingSweep) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{104} + return file_daemon_proto_rawDescGZIP(), []int{106} } func (x *BoardingSweep) GetTxid() string { @@ -8731,7 +8978,7 @@ type ListBoardingSweepsResponse struct { func (x *ListBoardingSweepsResponse) Reset() { *x = ListBoardingSweepsResponse{} - mi := &file_daemon_proto_msgTypes[105] + mi := &file_daemon_proto_msgTypes[107] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8743,7 +8990,7 @@ func (x *ListBoardingSweepsResponse) String() string { func (*ListBoardingSweepsResponse) ProtoMessage() {} func (x *ListBoardingSweepsResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[105] + mi := &file_daemon_proto_msgTypes[107] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8756,7 +9003,7 @@ func (x *ListBoardingSweepsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListBoardingSweepsResponse.ProtoReflect.Descriptor instead. func (*ListBoardingSweepsResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{105} + return file_daemon_proto_rawDescGZIP(), []int{107} } func (x *ListBoardingSweepsResponse) GetSweeps() []*BoardingSweep { @@ -8789,7 +9036,7 @@ type RoundVTXOInfo struct { func (x *RoundVTXOInfo) Reset() { *x = RoundVTXOInfo{} - mi := &file_daemon_proto_msgTypes[106] + mi := &file_daemon_proto_msgTypes[108] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8801,7 +9048,7 @@ func (x *RoundVTXOInfo) String() string { func (*RoundVTXOInfo) ProtoMessage() {} func (x *RoundVTXOInfo) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[106] + mi := &file_daemon_proto_msgTypes[108] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8814,7 +9061,7 @@ func (x *RoundVTXOInfo) ProtoReflect() protoreflect.Message { // Deprecated: Use RoundVTXOInfo.ProtoReflect.Descriptor instead. func (*RoundVTXOInfo) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{106} + return file_daemon_proto_rawDescGZIP(), []int{108} } func (x *RoundVTXOInfo) GetOutpoint() string { @@ -8862,7 +9109,7 @@ type ScheduledBatchWindow struct { func (x *ScheduledBatchWindow) Reset() { *x = ScheduledBatchWindow{} - mi := &file_daemon_proto_msgTypes[107] + mi := &file_daemon_proto_msgTypes[109] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8874,7 +9121,7 @@ func (x *ScheduledBatchWindow) String() string { func (*ScheduledBatchWindow) ProtoMessage() {} func (x *ScheduledBatchWindow) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[107] + mi := &file_daemon_proto_msgTypes[109] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8887,7 +9134,7 @@ func (x *ScheduledBatchWindow) ProtoReflect() protoreflect.Message { // Deprecated: Use ScheduledBatchWindow.ProtoReflect.Descriptor instead. func (*ScheduledBatchWindow) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{107} + return file_daemon_proto_rawDescGZIP(), []int{109} } func (x *ScheduledBatchWindow) GetRegistrationOpensUnix() int64 { @@ -8972,7 +9219,7 @@ type RoundInfo struct { func (x *RoundInfo) Reset() { *x = RoundInfo{} - mi := &file_daemon_proto_msgTypes[108] + mi := &file_daemon_proto_msgTypes[110] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8984,7 +9231,7 @@ func (x *RoundInfo) String() string { func (*RoundInfo) ProtoMessage() {} func (x *RoundInfo) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[108] + mi := &file_daemon_proto_msgTypes[110] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8997,7 +9244,7 @@ func (x *RoundInfo) ProtoReflect() protoreflect.Message { // Deprecated: Use RoundInfo.ProtoReflect.Descriptor instead. func (*RoundInfo) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{108} + return file_daemon_proto_rawDescGZIP(), []int{110} } func (x *RoundInfo) GetRoundId() string { @@ -9137,7 +9384,7 @@ type ListRoundsRequest struct { func (x *ListRoundsRequest) Reset() { *x = ListRoundsRequest{} - mi := &file_daemon_proto_msgTypes[109] + mi := &file_daemon_proto_msgTypes[111] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9149,7 +9396,7 @@ func (x *ListRoundsRequest) String() string { func (*ListRoundsRequest) ProtoMessage() {} func (x *ListRoundsRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[109] + mi := &file_daemon_proto_msgTypes[111] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9162,7 +9409,7 @@ func (x *ListRoundsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListRoundsRequest.ProtoReflect.Descriptor instead. func (*ListRoundsRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{109} + return file_daemon_proto_rawDescGZIP(), []int{111} } func (x *ListRoundsRequest) GetPageSize() int32 { @@ -9217,7 +9464,7 @@ type GetRoundRequest struct { func (x *GetRoundRequest) Reset() { *x = GetRoundRequest{} - mi := &file_daemon_proto_msgTypes[110] + mi := &file_daemon_proto_msgTypes[112] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9229,7 +9476,7 @@ func (x *GetRoundRequest) String() string { func (*GetRoundRequest) ProtoMessage() {} func (x *GetRoundRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[110] + mi := &file_daemon_proto_msgTypes[112] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9242,7 +9489,7 @@ func (x *GetRoundRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetRoundRequest.ProtoReflect.Descriptor instead. func (*GetRoundRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{110} + return file_daemon_proto_rawDescGZIP(), []int{112} } func (x *GetRoundRequest) GetRoundId() string { @@ -9262,7 +9509,7 @@ type GetRoundResponse struct { func (x *GetRoundResponse) Reset() { *x = GetRoundResponse{} - mi := &file_daemon_proto_msgTypes[111] + mi := &file_daemon_proto_msgTypes[113] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9274,7 +9521,7 @@ func (x *GetRoundResponse) String() string { func (*GetRoundResponse) ProtoMessage() {} func (x *GetRoundResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[111] + mi := &file_daemon_proto_msgTypes[113] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9287,7 +9534,7 @@ func (x *GetRoundResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetRoundResponse.ProtoReflect.Descriptor instead. func (*GetRoundResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{111} + return file_daemon_proto_rawDescGZIP(), []int{113} } func (x *GetRoundResponse) GetRound() *RoundInfo { @@ -9310,7 +9557,7 @@ type ListRoundsResponse struct { func (x *ListRoundsResponse) Reset() { *x = ListRoundsResponse{} - mi := &file_daemon_proto_msgTypes[112] + mi := &file_daemon_proto_msgTypes[114] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9322,7 +9569,7 @@ func (x *ListRoundsResponse) String() string { func (*ListRoundsResponse) ProtoMessage() {} func (x *ListRoundsResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[112] + mi := &file_daemon_proto_msgTypes[114] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9335,7 +9582,7 @@ func (x *ListRoundsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListRoundsResponse.ProtoReflect.Descriptor instead. func (*ListRoundsResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{112} + return file_daemon_proto_rawDescGZIP(), []int{114} } func (x *ListRoundsResponse) GetRounds() []*RoundInfo { @@ -9360,7 +9607,7 @@ type WatchRoundsRequest struct { func (x *WatchRoundsRequest) Reset() { *x = WatchRoundsRequest{} - mi := &file_daemon_proto_msgTypes[113] + mi := &file_daemon_proto_msgTypes[115] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9372,7 +9619,7 @@ func (x *WatchRoundsRequest) String() string { func (*WatchRoundsRequest) ProtoMessage() {} func (x *WatchRoundsRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[113] + mi := &file_daemon_proto_msgTypes[115] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9385,7 +9632,7 @@ func (x *WatchRoundsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use WatchRoundsRequest.ProtoReflect.Descriptor instead. func (*WatchRoundsRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{113} + return file_daemon_proto_rawDescGZIP(), []int{115} } type WatchRoundsResponse struct { @@ -9399,7 +9646,7 @@ type WatchRoundsResponse struct { func (x *WatchRoundsResponse) Reset() { *x = WatchRoundsResponse{} - mi := &file_daemon_proto_msgTypes[114] + mi := &file_daemon_proto_msgTypes[116] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9411,7 +9658,7 @@ func (x *WatchRoundsResponse) String() string { func (*WatchRoundsResponse) ProtoMessage() {} func (x *WatchRoundsResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[114] + mi := &file_daemon_proto_msgTypes[116] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9424,7 +9671,7 @@ func (x *WatchRoundsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use WatchRoundsResponse.ProtoReflect.Descriptor instead. func (*WatchRoundsResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{114} + return file_daemon_proto_rawDescGZIP(), []int{116} } func (x *WatchRoundsResponse) GetRound() *RoundInfo { @@ -9469,7 +9716,7 @@ type OORSessionInfo struct { func (x *OORSessionInfo) Reset() { *x = OORSessionInfo{} - mi := &file_daemon_proto_msgTypes[115] + mi := &file_daemon_proto_msgTypes[117] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9481,7 +9728,7 @@ func (x *OORSessionInfo) String() string { func (*OORSessionInfo) ProtoMessage() {} func (x *OORSessionInfo) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[115] + mi := &file_daemon_proto_msgTypes[117] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9494,7 +9741,7 @@ func (x *OORSessionInfo) ProtoReflect() protoreflect.Message { // Deprecated: Use OORSessionInfo.ProtoReflect.Descriptor instead. func (*OORSessionInfo) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{115} + return file_daemon_proto_rawDescGZIP(), []int{117} } func (x *OORSessionInfo) GetSessionId() string { @@ -9586,7 +9833,7 @@ type ListOORSessionsRequest struct { func (x *ListOORSessionsRequest) Reset() { *x = ListOORSessionsRequest{} - mi := &file_daemon_proto_msgTypes[116] + mi := &file_daemon_proto_msgTypes[118] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9598,7 +9845,7 @@ func (x *ListOORSessionsRequest) String() string { func (*ListOORSessionsRequest) ProtoMessage() {} func (x *ListOORSessionsRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[116] + mi := &file_daemon_proto_msgTypes[118] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9611,7 +9858,7 @@ func (x *ListOORSessionsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListOORSessionsRequest.ProtoReflect.Descriptor instead. func (*ListOORSessionsRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{116} + return file_daemon_proto_rawDescGZIP(), []int{118} } func (x *ListOORSessionsRequest) GetPageSize() int32 { @@ -9655,7 +9902,7 @@ type ListOORSessionsResponse struct { func (x *ListOORSessionsResponse) Reset() { *x = ListOORSessionsResponse{} - mi := &file_daemon_proto_msgTypes[117] + mi := &file_daemon_proto_msgTypes[119] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9667,7 +9914,7 @@ func (x *ListOORSessionsResponse) String() string { func (*ListOORSessionsResponse) ProtoMessage() {} func (x *ListOORSessionsResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[117] + mi := &file_daemon_proto_msgTypes[119] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9680,7 +9927,7 @@ func (x *ListOORSessionsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListOORSessionsResponse.ProtoReflect.Descriptor instead. func (*ListOORSessionsResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{117} + return file_daemon_proto_rawDescGZIP(), []int{119} } func (x *ListOORSessionsResponse) GetSessions() []*OORSessionInfo { @@ -9711,7 +9958,7 @@ type GetOORSessionRequest struct { func (x *GetOORSessionRequest) Reset() { *x = GetOORSessionRequest{} - mi := &file_daemon_proto_msgTypes[118] + mi := &file_daemon_proto_msgTypes[120] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9723,7 +9970,7 @@ func (x *GetOORSessionRequest) String() string { func (*GetOORSessionRequest) ProtoMessage() {} func (x *GetOORSessionRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[118] + mi := &file_daemon_proto_msgTypes[120] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9736,7 +9983,7 @@ func (x *GetOORSessionRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetOORSessionRequest.ProtoReflect.Descriptor instead. func (*GetOORSessionRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{118} + return file_daemon_proto_rawDescGZIP(), []int{120} } func (x *GetOORSessionRequest) GetSessionId() string { @@ -9766,7 +10013,7 @@ type GetOORSessionResponse struct { func (x *GetOORSessionResponse) Reset() { *x = GetOORSessionResponse{} - mi := &file_daemon_proto_msgTypes[119] + mi := &file_daemon_proto_msgTypes[121] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9778,7 +10025,7 @@ func (x *GetOORSessionResponse) String() string { func (*GetOORSessionResponse) ProtoMessage() {} func (x *GetOORSessionResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[119] + mi := &file_daemon_proto_msgTypes[121] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9791,7 +10038,7 @@ func (x *GetOORSessionResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetOORSessionResponse.ProtoReflect.Descriptor instead. func (*GetOORSessionResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{119} + return file_daemon_proto_rawDescGZIP(), []int{121} } func (x *GetOORSessionResponse) GetSession() *OORSessionInfo { @@ -9826,7 +10073,7 @@ type EstimateFeeRequest struct { func (x *EstimateFeeRequest) Reset() { *x = EstimateFeeRequest{} - mi := &file_daemon_proto_msgTypes[120] + mi := &file_daemon_proto_msgTypes[122] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9838,7 +10085,7 @@ func (x *EstimateFeeRequest) String() string { func (*EstimateFeeRequest) ProtoMessage() {} func (x *EstimateFeeRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[120] + mi := &file_daemon_proto_msgTypes[122] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9851,7 +10098,7 @@ func (x *EstimateFeeRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use EstimateFeeRequest.ProtoReflect.Descriptor instead. func (*EstimateFeeRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{120} + return file_daemon_proto_rawDescGZIP(), []int{122} } func (x *EstimateFeeRequest) GetAmountSat() int64 { @@ -9905,7 +10152,7 @@ type EstimateFeeResponse struct { func (x *EstimateFeeResponse) Reset() { *x = EstimateFeeResponse{} - mi := &file_daemon_proto_msgTypes[121] + mi := &file_daemon_proto_msgTypes[123] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9917,7 +10164,7 @@ func (x *EstimateFeeResponse) String() string { func (*EstimateFeeResponse) ProtoMessage() {} func (x *EstimateFeeResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[121] + mi := &file_daemon_proto_msgTypes[123] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9930,7 +10177,7 @@ func (x *EstimateFeeResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use EstimateFeeResponse.ProtoReflect.Descriptor instead. func (*EstimateFeeResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{121} + return file_daemon_proto_rawDescGZIP(), []int{123} } func (x *EstimateFeeResponse) GetLiquidityFeeSat() int64 { @@ -10026,7 +10273,7 @@ type GetFeeHistoryRequest struct { func (x *GetFeeHistoryRequest) Reset() { *x = GetFeeHistoryRequest{} - mi := &file_daemon_proto_msgTypes[122] + mi := &file_daemon_proto_msgTypes[124] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10038,7 +10285,7 @@ func (x *GetFeeHistoryRequest) String() string { func (*GetFeeHistoryRequest) ProtoMessage() {} func (x *GetFeeHistoryRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[122] + mi := &file_daemon_proto_msgTypes[124] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10051,7 +10298,7 @@ func (x *GetFeeHistoryRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetFeeHistoryRequest.ProtoReflect.Descriptor instead. func (*GetFeeHistoryRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{122} + return file_daemon_proto_rawDescGZIP(), []int{124} } func (x *GetFeeHistoryRequest) GetLimit() uint32 { @@ -10159,7 +10406,7 @@ type FeeHistoryEntry struct { func (x *FeeHistoryEntry) Reset() { *x = FeeHistoryEntry{} - mi := &file_daemon_proto_msgTypes[123] + mi := &file_daemon_proto_msgTypes[125] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10171,7 +10418,7 @@ func (x *FeeHistoryEntry) String() string { func (*FeeHistoryEntry) ProtoMessage() {} func (x *FeeHistoryEntry) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[123] + mi := &file_daemon_proto_msgTypes[125] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10184,7 +10431,7 @@ func (x *FeeHistoryEntry) ProtoReflect() protoreflect.Message { // Deprecated: Use FeeHistoryEntry.ProtoReflect.Descriptor instead. func (*FeeHistoryEntry) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{123} + return file_daemon_proto_rawDescGZIP(), []int{125} } func (x *FeeHistoryEntry) GetEntryId() int64 { @@ -10278,7 +10525,7 @@ type GetFeeHistoryResponse struct { func (x *GetFeeHistoryResponse) Reset() { *x = GetFeeHistoryResponse{} - mi := &file_daemon_proto_msgTypes[124] + mi := &file_daemon_proto_msgTypes[126] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10290,7 +10537,7 @@ func (x *GetFeeHistoryResponse) String() string { func (*GetFeeHistoryResponse) ProtoMessage() {} func (x *GetFeeHistoryResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[124] + mi := &file_daemon_proto_msgTypes[126] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10303,7 +10550,7 @@ func (x *GetFeeHistoryResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetFeeHistoryResponse.ProtoReflect.Descriptor instead. func (*GetFeeHistoryResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{124} + return file_daemon_proto_rawDescGZIP(), []int{126} } func (x *GetFeeHistoryResponse) GetEntries() []*FeeHistoryEntry { @@ -10344,7 +10591,7 @@ type ListTransactionsRequest struct { func (x *ListTransactionsRequest) Reset() { *x = ListTransactionsRequest{} - mi := &file_daemon_proto_msgTypes[125] + mi := &file_daemon_proto_msgTypes[127] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10356,7 +10603,7 @@ func (x *ListTransactionsRequest) String() string { func (*ListTransactionsRequest) ProtoMessage() {} func (x *ListTransactionsRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[125] + mi := &file_daemon_proto_msgTypes[127] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10369,7 +10616,7 @@ func (x *ListTransactionsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListTransactionsRequest.ProtoReflect.Descriptor instead. func (*ListTransactionsRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{125} + return file_daemon_proto_rawDescGZIP(), []int{127} } func (x *ListTransactionsRequest) GetFromUnixS() int64 { @@ -10460,7 +10707,7 @@ type TransactionHistoryEntry struct { func (x *TransactionHistoryEntry) Reset() { *x = TransactionHistoryEntry{} - mi := &file_daemon_proto_msgTypes[126] + mi := &file_daemon_proto_msgTypes[128] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10472,7 +10719,7 @@ func (x *TransactionHistoryEntry) String() string { func (*TransactionHistoryEntry) ProtoMessage() {} func (x *TransactionHistoryEntry) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[126] + mi := &file_daemon_proto_msgTypes[128] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10485,7 +10732,7 @@ func (x *TransactionHistoryEntry) ProtoReflect() protoreflect.Message { // Deprecated: Use TransactionHistoryEntry.ProtoReflect.Descriptor instead. func (*TransactionHistoryEntry) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{126} + return file_daemon_proto_rawDescGZIP(), []int{128} } func (x *TransactionHistoryEntry) GetSource() string { @@ -10622,7 +10869,7 @@ type ListTransactionsResponse struct { func (x *ListTransactionsResponse) Reset() { *x = ListTransactionsResponse{} - mi := &file_daemon_proto_msgTypes[127] + mi := &file_daemon_proto_msgTypes[129] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10634,7 +10881,7 @@ func (x *ListTransactionsResponse) String() string { func (*ListTransactionsResponse) ProtoMessage() {} func (x *ListTransactionsResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[127] + mi := &file_daemon_proto_msgTypes[129] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10647,7 +10894,7 @@ func (x *ListTransactionsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListTransactionsResponse.ProtoReflect.Descriptor instead. func (*ListTransactionsResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{127} + return file_daemon_proto_rawDescGZIP(), []int{129} } func (x *ListTransactionsResponse) GetTransactions() []*TransactionHistoryEntry { @@ -10682,7 +10929,7 @@ type UnrollRequest struct { func (x *UnrollRequest) Reset() { *x = UnrollRequest{} - mi := &file_daemon_proto_msgTypes[128] + mi := &file_daemon_proto_msgTypes[130] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10694,7 +10941,7 @@ func (x *UnrollRequest) String() string { func (*UnrollRequest) ProtoMessage() {} func (x *UnrollRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[128] + mi := &file_daemon_proto_msgTypes[130] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10707,7 +10954,7 @@ func (x *UnrollRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use UnrollRequest.ProtoReflect.Descriptor instead. func (*UnrollRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{128} + return file_daemon_proto_rawDescGZIP(), []int{130} } func (x *UnrollRequest) GetOutpoint() string { @@ -10730,7 +10977,7 @@ type UnrollResponse struct { func (x *UnrollResponse) Reset() { *x = UnrollResponse{} - mi := &file_daemon_proto_msgTypes[129] + mi := &file_daemon_proto_msgTypes[131] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10742,7 +10989,7 @@ func (x *UnrollResponse) String() string { func (*UnrollResponse) ProtoMessage() {} func (x *UnrollResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[129] + mi := &file_daemon_proto_msgTypes[131] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10755,7 +11002,7 @@ func (x *UnrollResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use UnrollResponse.ProtoReflect.Descriptor instead. func (*UnrollResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{129} + return file_daemon_proto_rawDescGZIP(), []int{131} } func (x *UnrollResponse) GetCreated() bool { @@ -10787,7 +11034,7 @@ type GetUnrollStatusRequest struct { func (x *GetUnrollStatusRequest) Reset() { *x = GetUnrollStatusRequest{} - mi := &file_daemon_proto_msgTypes[130] + mi := &file_daemon_proto_msgTypes[132] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10799,7 +11046,7 @@ func (x *GetUnrollStatusRequest) String() string { func (*GetUnrollStatusRequest) ProtoMessage() {} func (x *GetUnrollStatusRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[130] + mi := &file_daemon_proto_msgTypes[132] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10812,7 +11059,7 @@ func (x *GetUnrollStatusRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetUnrollStatusRequest.ProtoReflect.Descriptor instead. func (*GetUnrollStatusRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{130} + return file_daemon_proto_rawDescGZIP(), []int{132} } func (x *GetUnrollStatusRequest) GetOutpoint() string { @@ -10864,7 +11111,7 @@ type UnrollProgress struct { func (x *UnrollProgress) Reset() { *x = UnrollProgress{} - mi := &file_daemon_proto_msgTypes[131] + mi := &file_daemon_proto_msgTypes[133] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10876,7 +11123,7 @@ func (x *UnrollProgress) String() string { func (*UnrollProgress) ProtoMessage() {} func (x *UnrollProgress) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[131] + mi := &file_daemon_proto_msgTypes[133] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10889,7 +11136,7 @@ func (x *UnrollProgress) ProtoReflect() protoreflect.Message { // Deprecated: Use UnrollProgress.ProtoReflect.Descriptor instead. func (*UnrollProgress) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{131} + return file_daemon_proto_rawDescGZIP(), []int{133} } func (x *UnrollProgress) GetConfirmedTxs() uint32 { @@ -10974,7 +11221,7 @@ type UnrollCSV struct { func (x *UnrollCSV) Reset() { *x = UnrollCSV{} - mi := &file_daemon_proto_msgTypes[132] + mi := &file_daemon_proto_msgTypes[134] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10986,7 +11233,7 @@ func (x *UnrollCSV) String() string { func (*UnrollCSV) ProtoMessage() {} func (x *UnrollCSV) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[132] + mi := &file_daemon_proto_msgTypes[134] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10999,7 +11246,7 @@ func (x *UnrollCSV) ProtoReflect() protoreflect.Message { // Deprecated: Use UnrollCSV.ProtoReflect.Descriptor instead. func (*UnrollCSV) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{132} + return file_daemon_proto_rawDescGZIP(), []int{134} } func (x *UnrollCSV) GetTargetConfirmHeight() int32 { @@ -11065,7 +11312,7 @@ type UnrollFees struct { func (x *UnrollFees) Reset() { *x = UnrollFees{} - mi := &file_daemon_proto_msgTypes[133] + mi := &file_daemon_proto_msgTypes[135] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11077,7 +11324,7 @@ func (x *UnrollFees) String() string { func (*UnrollFees) ProtoMessage() {} func (x *UnrollFees) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[133] + mi := &file_daemon_proto_msgTypes[135] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11090,7 +11337,7 @@ func (x *UnrollFees) ProtoReflect() protoreflect.Message { // Deprecated: Use UnrollFees.ProtoReflect.Descriptor instead. func (*UnrollFees) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{133} + return file_daemon_proto_rawDescGZIP(), []int{135} } func (x *UnrollFees) GetCpfpFeeSat() int64 { @@ -11192,7 +11439,7 @@ type GetUnrollStatusResponse struct { func (x *GetUnrollStatusResponse) Reset() { *x = GetUnrollStatusResponse{} - mi := &file_daemon_proto_msgTypes[134] + mi := &file_daemon_proto_msgTypes[136] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11204,7 +11451,7 @@ func (x *GetUnrollStatusResponse) String() string { func (*GetUnrollStatusResponse) ProtoMessage() {} func (x *GetUnrollStatusResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[134] + mi := &file_daemon_proto_msgTypes[136] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11217,7 +11464,7 @@ func (x *GetUnrollStatusResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetUnrollStatusResponse.ProtoReflect.Descriptor instead. func (*GetUnrollStatusResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{134} + return file_daemon_proto_rawDescGZIP(), []int{136} } func (x *GetUnrollStatusResponse) GetFound() bool { @@ -11348,7 +11595,7 @@ type ArmVHTLCRecoveryRequest struct { func (x *ArmVHTLCRecoveryRequest) Reset() { *x = ArmVHTLCRecoveryRequest{} - mi := &file_daemon_proto_msgTypes[135] + mi := &file_daemon_proto_msgTypes[137] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11360,7 +11607,7 @@ func (x *ArmVHTLCRecoveryRequest) String() string { func (*ArmVHTLCRecoveryRequest) ProtoMessage() {} func (x *ArmVHTLCRecoveryRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[135] + mi := &file_daemon_proto_msgTypes[137] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11373,7 +11620,7 @@ func (x *ArmVHTLCRecoveryRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ArmVHTLCRecoveryRequest.ProtoReflect.Descriptor instead. func (*ArmVHTLCRecoveryRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{135} + return file_daemon_proto_rawDescGZIP(), []int{137} } func (x *ArmVHTLCRecoveryRequest) GetRequestId() string { @@ -11516,7 +11763,7 @@ type ArmVHTLCRecoveryResponse struct { func (x *ArmVHTLCRecoveryResponse) Reset() { *x = ArmVHTLCRecoveryResponse{} - mi := &file_daemon_proto_msgTypes[136] + mi := &file_daemon_proto_msgTypes[138] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11528,7 +11775,7 @@ func (x *ArmVHTLCRecoveryResponse) String() string { func (*ArmVHTLCRecoveryResponse) ProtoMessage() {} func (x *ArmVHTLCRecoveryResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[136] + mi := &file_daemon_proto_msgTypes[138] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11541,7 +11788,7 @@ func (x *ArmVHTLCRecoveryResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ArmVHTLCRecoveryResponse.ProtoReflect.Descriptor instead. func (*ArmVHTLCRecoveryResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{136} + return file_daemon_proto_rawDescGZIP(), []int{138} } func (x *ArmVHTLCRecoveryResponse) GetRecoveryId() string { @@ -11581,7 +11828,7 @@ type EscalateVHTLCRecoveryRequest struct { func (x *EscalateVHTLCRecoveryRequest) Reset() { *x = EscalateVHTLCRecoveryRequest{} - mi := &file_daemon_proto_msgTypes[137] + mi := &file_daemon_proto_msgTypes[139] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11593,7 +11840,7 @@ func (x *EscalateVHTLCRecoveryRequest) String() string { func (*EscalateVHTLCRecoveryRequest) ProtoMessage() {} func (x *EscalateVHTLCRecoveryRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[137] + mi := &file_daemon_proto_msgTypes[139] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11606,7 +11853,7 @@ func (x *EscalateVHTLCRecoveryRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use EscalateVHTLCRecoveryRequest.ProtoReflect.Descriptor instead. func (*EscalateVHTLCRecoveryRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{137} + return file_daemon_proto_rawDescGZIP(), []int{139} } func (x *EscalateVHTLCRecoveryRequest) GetRecoveryId() string { @@ -11640,7 +11887,7 @@ type EscalateVHTLCRecoveryResponse struct { func (x *EscalateVHTLCRecoveryResponse) Reset() { *x = EscalateVHTLCRecoveryResponse{} - mi := &file_daemon_proto_msgTypes[138] + mi := &file_daemon_proto_msgTypes[140] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11652,7 +11899,7 @@ func (x *EscalateVHTLCRecoveryResponse) String() string { func (*EscalateVHTLCRecoveryResponse) ProtoMessage() {} func (x *EscalateVHTLCRecoveryResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[138] + mi := &file_daemon_proto_msgTypes[140] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11665,7 +11912,7 @@ func (x *EscalateVHTLCRecoveryResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use EscalateVHTLCRecoveryResponse.ProtoReflect.Descriptor instead. func (*EscalateVHTLCRecoveryResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{138} + return file_daemon_proto_rawDescGZIP(), []int{140} } func (x *EscalateVHTLCRecoveryResponse) GetStatus() *VHTLCRecoveryStatus { @@ -11689,7 +11936,7 @@ type CancelVHTLCRecoveryRequest struct { func (x *CancelVHTLCRecoveryRequest) Reset() { *x = CancelVHTLCRecoveryRequest{} - mi := &file_daemon_proto_msgTypes[139] + mi := &file_daemon_proto_msgTypes[141] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11701,7 +11948,7 @@ func (x *CancelVHTLCRecoveryRequest) String() string { func (*CancelVHTLCRecoveryRequest) ProtoMessage() {} func (x *CancelVHTLCRecoveryRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[139] + mi := &file_daemon_proto_msgTypes[141] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11714,7 +11961,7 @@ func (x *CancelVHTLCRecoveryRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use CancelVHTLCRecoveryRequest.ProtoReflect.Descriptor instead. func (*CancelVHTLCRecoveryRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{139} + return file_daemon_proto_rawDescGZIP(), []int{141} } func (x *CancelVHTLCRecoveryRequest) GetRecoveryId() string { @@ -11748,7 +11995,7 @@ type CancelVHTLCRecoveryResponse struct { func (x *CancelVHTLCRecoveryResponse) Reset() { *x = CancelVHTLCRecoveryResponse{} - mi := &file_daemon_proto_msgTypes[140] + mi := &file_daemon_proto_msgTypes[142] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11760,7 +12007,7 @@ func (x *CancelVHTLCRecoveryResponse) String() string { func (*CancelVHTLCRecoveryResponse) ProtoMessage() {} func (x *CancelVHTLCRecoveryResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[140] + mi := &file_daemon_proto_msgTypes[142] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11773,7 +12020,7 @@ func (x *CancelVHTLCRecoveryResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use CancelVHTLCRecoveryResponse.ProtoReflect.Descriptor instead. func (*CancelVHTLCRecoveryResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{140} + return file_daemon_proto_rawDescGZIP(), []int{142} } func (x *CancelVHTLCRecoveryResponse) GetStatus() *VHTLCRecoveryStatus { @@ -11797,7 +12044,7 @@ type GetVHTLCRecoveryStatusRequest struct { func (x *GetVHTLCRecoveryStatusRequest) Reset() { *x = GetVHTLCRecoveryStatusRequest{} - mi := &file_daemon_proto_msgTypes[141] + mi := &file_daemon_proto_msgTypes[143] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11809,7 +12056,7 @@ func (x *GetVHTLCRecoveryStatusRequest) String() string { func (*GetVHTLCRecoveryStatusRequest) ProtoMessage() {} func (x *GetVHTLCRecoveryStatusRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[141] + mi := &file_daemon_proto_msgTypes[143] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11822,7 +12069,7 @@ func (x *GetVHTLCRecoveryStatusRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetVHTLCRecoveryStatusRequest.ProtoReflect.Descriptor instead. func (*GetVHTLCRecoveryStatusRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{141} + return file_daemon_proto_rawDescGZIP(), []int{143} } func (x *GetVHTLCRecoveryStatusRequest) GetRecoveryId() string { @@ -11851,7 +12098,7 @@ type GetVHTLCRecoveryStatusResponse struct { func (x *GetVHTLCRecoveryStatusResponse) Reset() { *x = GetVHTLCRecoveryStatusResponse{} - mi := &file_daemon_proto_msgTypes[142] + mi := &file_daemon_proto_msgTypes[144] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11863,7 +12110,7 @@ func (x *GetVHTLCRecoveryStatusResponse) String() string { func (*GetVHTLCRecoveryStatusResponse) ProtoMessage() {} func (x *GetVHTLCRecoveryStatusResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[142] + mi := &file_daemon_proto_msgTypes[144] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11876,7 +12123,7 @@ func (x *GetVHTLCRecoveryStatusResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetVHTLCRecoveryStatusResponse.ProtoReflect.Descriptor instead. func (*GetVHTLCRecoveryStatusResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{142} + return file_daemon_proto_rawDescGZIP(), []int{144} } func (x *GetVHTLCRecoveryStatusResponse) GetFound() bool { @@ -11903,7 +12150,7 @@ type ListVHTLCRecoveriesRequest struct { func (x *ListVHTLCRecoveriesRequest) Reset() { *x = ListVHTLCRecoveriesRequest{} - mi := &file_daemon_proto_msgTypes[143] + mi := &file_daemon_proto_msgTypes[145] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11915,7 +12162,7 @@ func (x *ListVHTLCRecoveriesRequest) String() string { func (*ListVHTLCRecoveriesRequest) ProtoMessage() {} func (x *ListVHTLCRecoveriesRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[143] + mi := &file_daemon_proto_msgTypes[145] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11928,7 +12175,7 @@ func (x *ListVHTLCRecoveriesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListVHTLCRecoveriesRequest.ProtoReflect.Descriptor instead. func (*ListVHTLCRecoveriesRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{143} + return file_daemon_proto_rawDescGZIP(), []int{145} } func (x *ListVHTLCRecoveriesRequest) GetIncludeTerminal() bool { @@ -11948,7 +12195,7 @@ type ListVHTLCRecoveriesResponse struct { func (x *ListVHTLCRecoveriesResponse) Reset() { *x = ListVHTLCRecoveriesResponse{} - mi := &file_daemon_proto_msgTypes[144] + mi := &file_daemon_proto_msgTypes[146] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11960,7 +12207,7 @@ func (x *ListVHTLCRecoveriesResponse) String() string { func (*ListVHTLCRecoveriesResponse) ProtoMessage() {} func (x *ListVHTLCRecoveriesResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[144] + mi := &file_daemon_proto_msgTypes[146] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11973,7 +12220,7 @@ func (x *ListVHTLCRecoveriesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListVHTLCRecoveriesResponse.ProtoReflect.Descriptor instead. func (*ListVHTLCRecoveriesResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{144} + return file_daemon_proto_rawDescGZIP(), []int{146} } func (x *ListVHTLCRecoveriesResponse) GetStatuses() []*VHTLCRecoveryStatus { @@ -12048,7 +12295,7 @@ type VHTLCRecoveryStatus struct { func (x *VHTLCRecoveryStatus) Reset() { *x = VHTLCRecoveryStatus{} - mi := &file_daemon_proto_msgTypes[145] + mi := &file_daemon_proto_msgTypes[147] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12060,7 +12307,7 @@ func (x *VHTLCRecoveryStatus) String() string { func (*VHTLCRecoveryStatus) ProtoMessage() {} func (x *VHTLCRecoveryStatus) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[145] + mi := &file_daemon_proto_msgTypes[147] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12073,7 +12320,7 @@ func (x *VHTLCRecoveryStatus) ProtoReflect() protoreflect.Message { // Deprecated: Use VHTLCRecoveryStatus.ProtoReflect.Descriptor instead. func (*VHTLCRecoveryStatus) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{145} + return file_daemon_proto_rawDescGZIP(), []int{147} } func (x *VHTLCRecoveryStatus) GetRecoveryId() string { @@ -12265,7 +12512,7 @@ type SignOutSwapHtlcAckRequest struct { func (x *SignOutSwapHtlcAckRequest) Reset() { *x = SignOutSwapHtlcAckRequest{} - mi := &file_daemon_proto_msgTypes[146] + mi := &file_daemon_proto_msgTypes[148] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12277,7 +12524,7 @@ func (x *SignOutSwapHtlcAckRequest) String() string { func (*SignOutSwapHtlcAckRequest) ProtoMessage() {} func (x *SignOutSwapHtlcAckRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[146] + mi := &file_daemon_proto_msgTypes[148] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12290,7 +12537,7 @@ func (x *SignOutSwapHtlcAckRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use SignOutSwapHtlcAckRequest.ProtoReflect.Descriptor instead. func (*SignOutSwapHtlcAckRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{146} + return file_daemon_proto_rawDescGZIP(), []int{148} } func (x *SignOutSwapHtlcAckRequest) GetPaymentHash() []byte { @@ -12324,7 +12571,7 @@ type SignOutSwapHtlcAckResponse struct { func (x *SignOutSwapHtlcAckResponse) Reset() { *x = SignOutSwapHtlcAckResponse{} - mi := &file_daemon_proto_msgTypes[147] + mi := &file_daemon_proto_msgTypes[149] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12336,7 +12583,7 @@ func (x *SignOutSwapHtlcAckResponse) String() string { func (*SignOutSwapHtlcAckResponse) ProtoMessage() {} func (x *SignOutSwapHtlcAckResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[147] + mi := &file_daemon_proto_msgTypes[149] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12349,7 +12596,7 @@ func (x *SignOutSwapHtlcAckResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use SignOutSwapHtlcAckResponse.ProtoReflect.Descriptor instead. func (*SignOutSwapHtlcAckResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{147} + return file_daemon_proto_rawDescGZIP(), []int{149} } func (x *SignOutSwapHtlcAckResponse) GetSignature() []byte { @@ -12377,7 +12624,7 @@ type SignCreditAccountAuthorizationRequest struct { func (x *SignCreditAccountAuthorizationRequest) Reset() { *x = SignCreditAccountAuthorizationRequest{} - mi := &file_daemon_proto_msgTypes[148] + mi := &file_daemon_proto_msgTypes[150] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12389,7 +12636,7 @@ func (x *SignCreditAccountAuthorizationRequest) String() string { func (*SignCreditAccountAuthorizationRequest) ProtoMessage() {} func (x *SignCreditAccountAuthorizationRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[148] + mi := &file_daemon_proto_msgTypes[150] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12402,7 +12649,7 @@ func (x *SignCreditAccountAuthorizationRequest) ProtoReflect() protoreflect.Mess // Deprecated: Use SignCreditAccountAuthorizationRequest.ProtoReflect.Descriptor instead. func (*SignCreditAccountAuthorizationRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{148} + return file_daemon_proto_rawDescGZIP(), []int{150} } func (x *SignCreditAccountAuthorizationRequest) GetRequestDigest() []byte { @@ -12443,7 +12690,7 @@ type SignCreditAccountAuthorizationResponse struct { func (x *SignCreditAccountAuthorizationResponse) Reset() { *x = SignCreditAccountAuthorizationResponse{} - mi := &file_daemon_proto_msgTypes[149] + mi := &file_daemon_proto_msgTypes[151] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12455,7 +12702,7 @@ func (x *SignCreditAccountAuthorizationResponse) String() string { func (*SignCreditAccountAuthorizationResponse) ProtoMessage() {} func (x *SignCreditAccountAuthorizationResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[149] + mi := &file_daemon_proto_msgTypes[151] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12468,7 +12715,7 @@ func (x *SignCreditAccountAuthorizationResponse) ProtoReflect() protoreflect.Mes // Deprecated: Use SignCreditAccountAuthorizationResponse.ProtoReflect.Descriptor instead. func (*SignCreditAccountAuthorizationResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{149} + return file_daemon_proto_rawDescGZIP(), []int{151} } func (x *SignCreditAccountAuthorizationResponse) GetSignature() []byte { @@ -12492,7 +12739,7 @@ type MacaroonPermission struct { func (x *MacaroonPermission) Reset() { *x = MacaroonPermission{} - mi := &file_daemon_proto_msgTypes[150] + mi := &file_daemon_proto_msgTypes[152] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12504,7 +12751,7 @@ func (x *MacaroonPermission) String() string { func (*MacaroonPermission) ProtoMessage() {} func (x *MacaroonPermission) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[150] + mi := &file_daemon_proto_msgTypes[152] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12517,7 +12764,7 @@ func (x *MacaroonPermission) ProtoReflect() protoreflect.Message { // Deprecated: Use MacaroonPermission.ProtoReflect.Descriptor instead. func (*MacaroonPermission) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{150} + return file_daemon_proto_rawDescGZIP(), []int{152} } func (x *MacaroonPermission) GetEntity() string { @@ -12547,7 +12794,7 @@ type BakeMacaroonRequest struct { func (x *BakeMacaroonRequest) Reset() { *x = BakeMacaroonRequest{} - mi := &file_daemon_proto_msgTypes[151] + mi := &file_daemon_proto_msgTypes[153] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12559,7 +12806,7 @@ func (x *BakeMacaroonRequest) String() string { func (*BakeMacaroonRequest) ProtoMessage() {} func (x *BakeMacaroonRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[151] + mi := &file_daemon_proto_msgTypes[153] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12572,7 +12819,7 @@ func (x *BakeMacaroonRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use BakeMacaroonRequest.ProtoReflect.Descriptor instead. func (*BakeMacaroonRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{151} + return file_daemon_proto_rawDescGZIP(), []int{153} } func (x *BakeMacaroonRequest) GetPermissions() []*MacaroonPermission { @@ -12599,7 +12846,7 @@ type BakeMacaroonResponse struct { func (x *BakeMacaroonResponse) Reset() { *x = BakeMacaroonResponse{} - mi := &file_daemon_proto_msgTypes[152] + mi := &file_daemon_proto_msgTypes[154] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12611,7 +12858,7 @@ func (x *BakeMacaroonResponse) String() string { func (*BakeMacaroonResponse) ProtoMessage() {} func (x *BakeMacaroonResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[152] + mi := &file_daemon_proto_msgTypes[154] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12624,7 +12871,7 @@ func (x *BakeMacaroonResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use BakeMacaroonResponse.ProtoReflect.Descriptor instead. func (*BakeMacaroonResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{152} + return file_daemon_proto_rawDescGZIP(), []int{154} } func (x *BakeMacaroonResponse) GetMacaroon() string { @@ -12643,7 +12890,7 @@ type MacaroonPermissionList struct { func (x *MacaroonPermissionList) Reset() { *x = MacaroonPermissionList{} - mi := &file_daemon_proto_msgTypes[153] + mi := &file_daemon_proto_msgTypes[155] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12655,7 +12902,7 @@ func (x *MacaroonPermissionList) String() string { func (*MacaroonPermissionList) ProtoMessage() {} func (x *MacaroonPermissionList) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[153] + mi := &file_daemon_proto_msgTypes[155] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12668,7 +12915,7 @@ func (x *MacaroonPermissionList) ProtoReflect() protoreflect.Message { // Deprecated: Use MacaroonPermissionList.ProtoReflect.Descriptor instead. func (*MacaroonPermissionList) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{153} + return file_daemon_proto_rawDescGZIP(), []int{155} } func (x *MacaroonPermissionList) GetPermissions() []*MacaroonPermission { @@ -12686,7 +12933,7 @@ type ListPermissionsRequest struct { func (x *ListPermissionsRequest) Reset() { *x = ListPermissionsRequest{} - mi := &file_daemon_proto_msgTypes[154] + mi := &file_daemon_proto_msgTypes[156] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12698,7 +12945,7 @@ func (x *ListPermissionsRequest) String() string { func (*ListPermissionsRequest) ProtoMessage() {} func (x *ListPermissionsRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[154] + mi := &file_daemon_proto_msgTypes[156] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12711,7 +12958,7 @@ func (x *ListPermissionsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListPermissionsRequest.ProtoReflect.Descriptor instead. func (*ListPermissionsRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{154} + return file_daemon_proto_rawDescGZIP(), []int{156} } type ListPermissionsResponse struct { @@ -12725,7 +12972,7 @@ type ListPermissionsResponse struct { func (x *ListPermissionsResponse) Reset() { *x = ListPermissionsResponse{} - mi := &file_daemon_proto_msgTypes[155] + mi := &file_daemon_proto_msgTypes[157] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12737,7 +12984,7 @@ func (x *ListPermissionsResponse) String() string { func (*ListPermissionsResponse) ProtoMessage() {} func (x *ListPermissionsResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[155] + mi := &file_daemon_proto_msgTypes[157] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12750,7 +12997,7 @@ func (x *ListPermissionsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListPermissionsResponse.ProtoReflect.Descriptor instead. func (*ListPermissionsResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{155} + return file_daemon_proto_rawDescGZIP(), []int{157} } func (x *ListPermissionsResponse) GetMethodPermissions() map[string]*MacaroonPermissionList { @@ -12770,7 +13017,7 @@ type DeriveSwapPreimageRequest struct { func (x *DeriveSwapPreimageRequest) Reset() { *x = DeriveSwapPreimageRequest{} - mi := &file_daemon_proto_msgTypes[156] + mi := &file_daemon_proto_msgTypes[158] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12782,7 +13029,7 @@ func (x *DeriveSwapPreimageRequest) String() string { func (*DeriveSwapPreimageRequest) ProtoMessage() {} func (x *DeriveSwapPreimageRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[156] + mi := &file_daemon_proto_msgTypes[158] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12795,7 +13042,7 @@ func (x *DeriveSwapPreimageRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DeriveSwapPreimageRequest.ProtoReflect.Descriptor instead. func (*DeriveSwapPreimageRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{156} + return file_daemon_proto_rawDescGZIP(), []int{158} } func (x *DeriveSwapPreimageRequest) GetRecoveryParams() []byte { @@ -12815,7 +13062,7 @@ type DeriveSwapPreimageResponse struct { func (x *DeriveSwapPreimageResponse) Reset() { *x = DeriveSwapPreimageResponse{} - mi := &file_daemon_proto_msgTypes[157] + mi := &file_daemon_proto_msgTypes[159] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12827,7 +13074,7 @@ func (x *DeriveSwapPreimageResponse) String() string { func (*DeriveSwapPreimageResponse) ProtoMessage() {} func (x *DeriveSwapPreimageResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[157] + mi := &file_daemon_proto_msgTypes[159] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12840,7 +13087,7 @@ func (x *DeriveSwapPreimageResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use DeriveSwapPreimageResponse.ProtoReflect.Descriptor instead. func (*DeriveSwapPreimageResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{157} + return file_daemon_proto_rawDescGZIP(), []int{159} } func (x *DeriveSwapPreimageResponse) GetPreimage() []byte { @@ -12864,7 +13111,7 @@ type CooperativeOORPackage struct { func (x *CooperativeOORPackage) Reset() { *x = CooperativeOORPackage{} - mi := &file_daemon_proto_msgTypes[158] + mi := &file_daemon_proto_msgTypes[160] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12876,7 +13123,7 @@ func (x *CooperativeOORPackage) String() string { func (*CooperativeOORPackage) ProtoMessage() {} func (x *CooperativeOORPackage) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[158] + mi := &file_daemon_proto_msgTypes[160] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12889,7 +13136,7 @@ func (x *CooperativeOORPackage) ProtoReflect() protoreflect.Message { // Deprecated: Use CooperativeOORPackage.ProtoReflect.Descriptor instead. func (*CooperativeOORPackage) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{158} + return file_daemon_proto_rawDescGZIP(), []int{160} } func (x *CooperativeOORPackage) GetCustomInput() *CustomOORInput { @@ -13171,7 +13418,25 @@ const file_daemon_proto_rawDesc = "" + "\n" + "session_id\x18\x02 \x01(\tR\tsessionId\x12/\n" + "\x13recipient_outpoints\x18\x03 \x03(\tR\x12recipientOutpoints\x12,\n" + - "\x12failed_before_ponr\x18\x04 \x01(\bR\x10failedBeforePonr\"\x80\x01\n" + + "\x12failed_before_ponr\x18\x04 \x01(\bR\x10failedBeforePonr\"\xa3\x02\n" + + "\x13SendAssetOORRequest\x12\x1b\n" + + "\tasset_ref\x18\x01 \x01(\tR\bassetRef\x12\x16\n" + + "\x06amount\x18\x02 \x01(\x04R\x06amount\x12\x18\n" + + "\x06pubkey\x18\x03 \x01(\fH\x00R\x06pubkey\x12)\n" + + "\x0fpolicy_template\x18\x04 \x01(\fH\x00R\x0epolicyTemplate\x12\x17\n" + + "\adry_run\x18\x05 \x01(\bR\x06dryRun\x12'\n" + + "\x0fidempotency_key\x18\x06 \x01(\tR\x0eidempotencyKey\x12A\n" + + "\x1dadmission_deadline_unix_nanos\x18\a \x01(\x03R\x1aadmissionDeadlineUnixNanosB\r\n" + + "\vdestination\"\xbf\x02\n" + + "\x14SendAssetOORResponse\x12\x16\n" + + "\x06status\x18\x01 \x01(\tR\x06status\x12\x1d\n" + + "\n" + + "session_id\x18\x02 \x01(\tR\tsessionId\x12-\n" + + "\x12recipient_outpoint\x18\x03 \x01(\tR\x11recipientOutpoint\x120\n" + + "\x14selected_input_count\x18\x04 \x01(\rR\x12selectedInputCount\x12.\n" + + "\x13asset_change_amount\x18\x05 \x01(\x04R\x11assetChangeAmount\x121\n" + + "\x15sender_btc_change_sat\x18\x06 \x01(\x03R\x12senderBtcChangeSat\x12,\n" + + "\x12failed_before_ponr\x18\a \x01(\bR\x10failedBeforePonr\"\x80\x01\n" + "\x11PrepareOORRequest\x12-\n" + "\trecipient\x18\x01 \x01(\v2\x0f.waverpc.OutputR\trecipient\x12<\n" + "\rcustom_inputs\x18\x02 \x03(\v2\x17.waverpc.CustomOORInputR\fcustomInputs\"\xad\x01\n" + @@ -13905,7 +14170,7 @@ const file_daemon_proto_rawDesc = "" + "\x1eVHTLC_RECOVERY_STATE_COMPLETED\x10\t\x12\"\n" + "\x1eVHTLC_RECOVERY_STATE_CANCELLED\x10\n" + "\x12\x1f\n" + - "\x1bVHTLC_RECOVERY_STATE_FAILED\x10\v2\xef)\n" + + "\x1bVHTLC_RECOVERY_STATE_FAILED\x10\v2\xbc*\n" + "\rDaemonService\x12<\n" + "\aGetInfo\x12\x17.waverpc.GetInfoRequest\x1a\x18.waverpc.GetInfoResponse\x12<\n" + "\aGenSeed\x12\x17.waverpc.GenSeedRequest\x1a\x18.waverpc.GenSeedResponse\x12E\n" + @@ -13928,7 +14193,8 @@ const file_daemon_proto_rawDesc = "" + "\x11GetVTXOExpiryInfo\x12!.waverpc.GetVTXOExpiryInfoRequest\x1a\".waverpc.GetVTXOExpiryInfoResponse\x12u\n" + "\x1aGetIndexedOORSessionByTxid\x12*.waverpc.GetIndexedOORSessionByTxidRequest\x1a+.waverpc.GetIndexedOORSessionByTxidResponse\x12?\n" + "\bSendVTXO\x12\x18.waverpc.SendVTXORequest\x1a\x19.waverpc.SendVTXOResponse\x12<\n" + - "\aSendOOR\x12\x17.waverpc.SendOORRequest\x1a\x18.waverpc.SendOORResponse\x12E\n" + + "\aSendOOR\x12\x17.waverpc.SendOORRequest\x1a\x18.waverpc.SendOORResponse\x12K\n" + + "\fSendAssetOOR\x12\x1c.waverpc.SendAssetOORRequest\x1a\x1d.waverpc.SendAssetOORResponse\x12E\n" + "\n" + "PrepareOOR\x12\x1a.waverpc.PrepareOORRequest\x1a\x1b.waverpc.PrepareOORResponse\x12]\n" + "\x12SignOORCustomInput\x12\".waverpc.SignOORCustomInputRequest\x1a#.waverpc.SignOORCustomInputResponse\x12T\n" + @@ -13991,7 +14257,7 @@ func file_daemon_proto_rawDescGZIP() []byte { } var file_daemon_proto_enumTypes = make([]protoimpl.EnumInfo, 13) -var file_daemon_proto_msgTypes = make([]protoimpl.MessageInfo, 162) +var file_daemon_proto_msgTypes = make([]protoimpl.MessageInfo, 164) var file_daemon_proto_goTypes = []any{ (WalletState)(0), // 0: waverpc.WalletState (VTXOStatus)(0), // 1: waverpc.VTXOStatus @@ -14050,124 +14316,126 @@ var file_daemon_proto_goTypes = []any{ (*CustomOORInput)(nil), // 54: waverpc.CustomOORInput (*TaprootScriptSignature)(nil), // 55: waverpc.TaprootScriptSignature (*SendOORResponse)(nil), // 56: waverpc.SendOORResponse - (*PrepareOORRequest)(nil), // 57: waverpc.PrepareOORRequest - (*PreparedOORCustomInput)(nil), // 58: waverpc.PreparedOORCustomInput - (*PrepareOORResponse)(nil), // 59: waverpc.PrepareOORResponse - (*SignOORCustomInputRequest)(nil), // 60: waverpc.SignOORCustomInputRequest - (*SignOORCustomInputResponse)(nil), // 61: waverpc.SignOORCustomInputResponse - (*SignVTXOForfeitRequest)(nil), // 62: waverpc.SignVTXOForfeitRequest - (*SignVTXOForfeitResponse)(nil), // 63: waverpc.SignVTXOForfeitResponse - (*ForfeitSigningContext)(nil), // 64: waverpc.ForfeitSigningContext - (*OutpointSelection)(nil), // 65: waverpc.OutpointSelection - (*RefreshVTXOsRequest)(nil), // 66: waverpc.RefreshVTXOsRequest - (*RefreshVTXOsResponse)(nil), // 67: waverpc.RefreshVTXOsResponse - (*RefreshFeeEstimate)(nil), // 68: waverpc.RefreshFeeEstimate - (*OutpointFeeEstimate)(nil), // 69: waverpc.OutpointFeeEstimate - (*CustomRefreshVTXOInput)(nil), // 70: waverpc.CustomRefreshVTXOInput - (*CustomRefreshVTXOOutput)(nil), // 71: waverpc.CustomRefreshVTXOOutput - (*RefreshCustomVTXOsRequest)(nil), // 72: waverpc.RefreshCustomVTXOsRequest - (*RefreshCustomVTXOsResponse)(nil), // 73: waverpc.RefreshCustomVTXOsResponse - (*PendingForfeitParticipantSignatureRequest)(nil), // 74: waverpc.PendingForfeitParticipantSignatureRequest - (*ListPendingForfeitParticipantSignatureRequestsRequest)(nil), // 75: waverpc.ListPendingForfeitParticipantSignatureRequestsRequest - (*ListPendingForfeitParticipantSignatureRequestsResponse)(nil), // 76: waverpc.ListPendingForfeitParticipantSignatureRequestsResponse - (*ForfeitParticipantSignature)(nil), // 77: waverpc.ForfeitParticipantSignature - (*SubmitForfeitParticipantSignaturesRequest)(nil), // 78: waverpc.SubmitForfeitParticipantSignaturesRequest - (*SubmitForfeitParticipantSignaturesResponse)(nil), // 79: waverpc.SubmitForfeitParticipantSignaturesResponse - (*LeaveDestination)(nil), // 80: waverpc.LeaveDestination - (*LeaveVTXOsRequest)(nil), // 81: waverpc.LeaveVTXOsRequest - (*LeaveVTXOsResponse)(nil), // 82: waverpc.LeaveVTXOsResponse - (*SendOnChainRequest)(nil), // 83: waverpc.SendOnChainRequest - (*SendOnChainResponse)(nil), // 84: waverpc.SendOnChainResponse - (*BoardRequest)(nil), // 85: waverpc.BoardRequest - (*BoardResponse)(nil), // 86: waverpc.BoardResponse - (*DepositAssetRequest)(nil), // 87: waverpc.DepositAssetRequest - (*ListAssetDepositsRequest)(nil), // 88: waverpc.ListAssetDepositsRequest - (*BoardAssetDepositRequest)(nil), // 89: waverpc.BoardAssetDepositRequest - (*ClaimAssetDepositRequest)(nil), // 90: waverpc.ClaimAssetDepositRequest - (*ListAssetDepositsResponse)(nil), // 91: waverpc.ListAssetDepositsResponse - (*AssetDeposit)(nil), // 92: waverpc.AssetDeposit - (*NewAssetReceiveKeysRequest)(nil), // 93: waverpc.NewAssetReceiveKeysRequest - (*AssetReceiveKeys)(nil), // 94: waverpc.AssetReceiveKeys - (*ImportAssetProofRequest)(nil), // 95: waverpc.ImportAssetProofRequest - (*NewAssetFundingAddressRequest)(nil), // 96: waverpc.NewAssetFundingAddressRequest - (*AssetFundingAddress)(nil), // 97: waverpc.AssetFundingAddress - (*ListOwnedAssetsRequest)(nil), // 98: waverpc.ListOwnedAssetsRequest - (*ListOwnedAssetsResponse)(nil), // 99: waverpc.ListOwnedAssetsResponse - (*OwnedAsset)(nil), // 100: waverpc.OwnedAsset - (*NewAssetAddressRequest)(nil), // 101: waverpc.NewAssetAddressRequest - (*AssetAddress)(nil), // 102: waverpc.AssetAddress - (*ListAssetAddressesRequest)(nil), // 103: waverpc.ListAssetAddressesRequest - (*ListAssetAddressesResponse)(nil), // 104: waverpc.ListAssetAddressesResponse - (*ListAssetReceivesRequest)(nil), // 105: waverpc.ListAssetReceivesRequest - (*ListAssetReceivesResponse)(nil), // 106: waverpc.ListAssetReceivesResponse - (*AssetReceive)(nil), // 107: waverpc.AssetReceive - (*SyncAssetReceivesRequest)(nil), // 108: waverpc.SyncAssetReceivesRequest - (*SyncAssetReceivesResponse)(nil), // 109: waverpc.SyncAssetReceivesResponse - (*JoinNextRoundRequest)(nil), // 110: waverpc.JoinNextRoundRequest - (*JoinNextRoundResponse)(nil), // 111: waverpc.JoinNextRoundResponse - (*SweepBoardingUTXOsRequest)(nil), // 112: waverpc.SweepBoardingUTXOsRequest - (*BoardingSweepOutput)(nil), // 113: waverpc.BoardingSweepOutput - (*SweepBoardingUTXOsResponse)(nil), // 114: waverpc.SweepBoardingUTXOsResponse - (*ListBoardingSweepsRequest)(nil), // 115: waverpc.ListBoardingSweepsRequest - (*BoardingSweepInput)(nil), // 116: waverpc.BoardingSweepInput - (*BoardingSweep)(nil), // 117: waverpc.BoardingSweep - (*ListBoardingSweepsResponse)(nil), // 118: waverpc.ListBoardingSweepsResponse - (*RoundVTXOInfo)(nil), // 119: waverpc.RoundVTXOInfo - (*ScheduledBatchWindow)(nil), // 120: waverpc.ScheduledBatchWindow - (*RoundInfo)(nil), // 121: waverpc.RoundInfo - (*ListRoundsRequest)(nil), // 122: waverpc.ListRoundsRequest - (*GetRoundRequest)(nil), // 123: waverpc.GetRoundRequest - (*GetRoundResponse)(nil), // 124: waverpc.GetRoundResponse - (*ListRoundsResponse)(nil), // 125: waverpc.ListRoundsResponse - (*WatchRoundsRequest)(nil), // 126: waverpc.WatchRoundsRequest - (*WatchRoundsResponse)(nil), // 127: waverpc.WatchRoundsResponse - (*OORSessionInfo)(nil), // 128: waverpc.OORSessionInfo - (*ListOORSessionsRequest)(nil), // 129: waverpc.ListOORSessionsRequest - (*ListOORSessionsResponse)(nil), // 130: waverpc.ListOORSessionsResponse - (*GetOORSessionRequest)(nil), // 131: waverpc.GetOORSessionRequest - (*GetOORSessionResponse)(nil), // 132: waverpc.GetOORSessionResponse - (*EstimateFeeRequest)(nil), // 133: waverpc.EstimateFeeRequest - (*EstimateFeeResponse)(nil), // 134: waverpc.EstimateFeeResponse - (*GetFeeHistoryRequest)(nil), // 135: waverpc.GetFeeHistoryRequest - (*FeeHistoryEntry)(nil), // 136: waverpc.FeeHistoryEntry - (*GetFeeHistoryResponse)(nil), // 137: waverpc.GetFeeHistoryResponse - (*ListTransactionsRequest)(nil), // 138: waverpc.ListTransactionsRequest - (*TransactionHistoryEntry)(nil), // 139: waverpc.TransactionHistoryEntry - (*ListTransactionsResponse)(nil), // 140: waverpc.ListTransactionsResponse - (*UnrollRequest)(nil), // 141: waverpc.UnrollRequest - (*UnrollResponse)(nil), // 142: waverpc.UnrollResponse - (*GetUnrollStatusRequest)(nil), // 143: waverpc.GetUnrollStatusRequest - (*UnrollProgress)(nil), // 144: waverpc.UnrollProgress - (*UnrollCSV)(nil), // 145: waverpc.UnrollCSV - (*UnrollFees)(nil), // 146: waverpc.UnrollFees - (*GetUnrollStatusResponse)(nil), // 147: waverpc.GetUnrollStatusResponse - (*ArmVHTLCRecoveryRequest)(nil), // 148: waverpc.ArmVHTLCRecoveryRequest - (*ArmVHTLCRecoveryResponse)(nil), // 149: waverpc.ArmVHTLCRecoveryResponse - (*EscalateVHTLCRecoveryRequest)(nil), // 150: waverpc.EscalateVHTLCRecoveryRequest - (*EscalateVHTLCRecoveryResponse)(nil), // 151: waverpc.EscalateVHTLCRecoveryResponse - (*CancelVHTLCRecoveryRequest)(nil), // 152: waverpc.CancelVHTLCRecoveryRequest - (*CancelVHTLCRecoveryResponse)(nil), // 153: waverpc.CancelVHTLCRecoveryResponse - (*GetVHTLCRecoveryStatusRequest)(nil), // 154: waverpc.GetVHTLCRecoveryStatusRequest - (*GetVHTLCRecoveryStatusResponse)(nil), // 155: waverpc.GetVHTLCRecoveryStatusResponse - (*ListVHTLCRecoveriesRequest)(nil), // 156: waverpc.ListVHTLCRecoveriesRequest - (*ListVHTLCRecoveriesResponse)(nil), // 157: waverpc.ListVHTLCRecoveriesResponse - (*VHTLCRecoveryStatus)(nil), // 158: waverpc.VHTLCRecoveryStatus - (*SignOutSwapHtlcAckRequest)(nil), // 159: waverpc.SignOutSwapHtlcAckRequest - (*SignOutSwapHtlcAckResponse)(nil), // 160: waverpc.SignOutSwapHtlcAckResponse - (*SignCreditAccountAuthorizationRequest)(nil), // 161: waverpc.SignCreditAccountAuthorizationRequest - (*SignCreditAccountAuthorizationResponse)(nil), // 162: waverpc.SignCreditAccountAuthorizationResponse - (*MacaroonPermission)(nil), // 163: waverpc.MacaroonPermission - (*BakeMacaroonRequest)(nil), // 164: waverpc.BakeMacaroonRequest - (*BakeMacaroonResponse)(nil), // 165: waverpc.BakeMacaroonResponse - (*MacaroonPermissionList)(nil), // 166: waverpc.MacaroonPermissionList - (*ListPermissionsRequest)(nil), // 167: waverpc.ListPermissionsRequest - (*ListPermissionsResponse)(nil), // 168: waverpc.ListPermissionsResponse - (*DeriveSwapPreimageRequest)(nil), // 169: waverpc.DeriveSwapPreimageRequest - (*DeriveSwapPreimageResponse)(nil), // 170: waverpc.DeriveSwapPreimageResponse - (*CooperativeOORPackage)(nil), // 171: waverpc.CooperativeOORPackage - nil, // 172: waverpc.LeaveVTXOsRequest.DestinationsEntry - nil, // 173: waverpc.LeaveVTXOsResponse.ErrorsEntry - nil, // 174: waverpc.ListPermissionsResponse.MethodPermissionsEntry + (*SendAssetOORRequest)(nil), // 57: waverpc.SendAssetOORRequest + (*SendAssetOORResponse)(nil), // 58: waverpc.SendAssetOORResponse + (*PrepareOORRequest)(nil), // 59: waverpc.PrepareOORRequest + (*PreparedOORCustomInput)(nil), // 60: waverpc.PreparedOORCustomInput + (*PrepareOORResponse)(nil), // 61: waverpc.PrepareOORResponse + (*SignOORCustomInputRequest)(nil), // 62: waverpc.SignOORCustomInputRequest + (*SignOORCustomInputResponse)(nil), // 63: waverpc.SignOORCustomInputResponse + (*SignVTXOForfeitRequest)(nil), // 64: waverpc.SignVTXOForfeitRequest + (*SignVTXOForfeitResponse)(nil), // 65: waverpc.SignVTXOForfeitResponse + (*ForfeitSigningContext)(nil), // 66: waverpc.ForfeitSigningContext + (*OutpointSelection)(nil), // 67: waverpc.OutpointSelection + (*RefreshVTXOsRequest)(nil), // 68: waverpc.RefreshVTXOsRequest + (*RefreshVTXOsResponse)(nil), // 69: waverpc.RefreshVTXOsResponse + (*RefreshFeeEstimate)(nil), // 70: waverpc.RefreshFeeEstimate + (*OutpointFeeEstimate)(nil), // 71: waverpc.OutpointFeeEstimate + (*CustomRefreshVTXOInput)(nil), // 72: waverpc.CustomRefreshVTXOInput + (*CustomRefreshVTXOOutput)(nil), // 73: waverpc.CustomRefreshVTXOOutput + (*RefreshCustomVTXOsRequest)(nil), // 74: waverpc.RefreshCustomVTXOsRequest + (*RefreshCustomVTXOsResponse)(nil), // 75: waverpc.RefreshCustomVTXOsResponse + (*PendingForfeitParticipantSignatureRequest)(nil), // 76: waverpc.PendingForfeitParticipantSignatureRequest + (*ListPendingForfeitParticipantSignatureRequestsRequest)(nil), // 77: waverpc.ListPendingForfeitParticipantSignatureRequestsRequest + (*ListPendingForfeitParticipantSignatureRequestsResponse)(nil), // 78: waverpc.ListPendingForfeitParticipantSignatureRequestsResponse + (*ForfeitParticipantSignature)(nil), // 79: waverpc.ForfeitParticipantSignature + (*SubmitForfeitParticipantSignaturesRequest)(nil), // 80: waverpc.SubmitForfeitParticipantSignaturesRequest + (*SubmitForfeitParticipantSignaturesResponse)(nil), // 81: waverpc.SubmitForfeitParticipantSignaturesResponse + (*LeaveDestination)(nil), // 82: waverpc.LeaveDestination + (*LeaveVTXOsRequest)(nil), // 83: waverpc.LeaveVTXOsRequest + (*LeaveVTXOsResponse)(nil), // 84: waverpc.LeaveVTXOsResponse + (*SendOnChainRequest)(nil), // 85: waverpc.SendOnChainRequest + (*SendOnChainResponse)(nil), // 86: waverpc.SendOnChainResponse + (*BoardRequest)(nil), // 87: waverpc.BoardRequest + (*BoardResponse)(nil), // 88: waverpc.BoardResponse + (*DepositAssetRequest)(nil), // 89: waverpc.DepositAssetRequest + (*ListAssetDepositsRequest)(nil), // 90: waverpc.ListAssetDepositsRequest + (*BoardAssetDepositRequest)(nil), // 91: waverpc.BoardAssetDepositRequest + (*ClaimAssetDepositRequest)(nil), // 92: waverpc.ClaimAssetDepositRequest + (*ListAssetDepositsResponse)(nil), // 93: waverpc.ListAssetDepositsResponse + (*AssetDeposit)(nil), // 94: waverpc.AssetDeposit + (*NewAssetReceiveKeysRequest)(nil), // 95: waverpc.NewAssetReceiveKeysRequest + (*AssetReceiveKeys)(nil), // 96: waverpc.AssetReceiveKeys + (*ImportAssetProofRequest)(nil), // 97: waverpc.ImportAssetProofRequest + (*NewAssetFundingAddressRequest)(nil), // 98: waverpc.NewAssetFundingAddressRequest + (*AssetFundingAddress)(nil), // 99: waverpc.AssetFundingAddress + (*ListOwnedAssetsRequest)(nil), // 100: waverpc.ListOwnedAssetsRequest + (*ListOwnedAssetsResponse)(nil), // 101: waverpc.ListOwnedAssetsResponse + (*OwnedAsset)(nil), // 102: waverpc.OwnedAsset + (*NewAssetAddressRequest)(nil), // 103: waverpc.NewAssetAddressRequest + (*AssetAddress)(nil), // 104: waverpc.AssetAddress + (*ListAssetAddressesRequest)(nil), // 105: waverpc.ListAssetAddressesRequest + (*ListAssetAddressesResponse)(nil), // 106: waverpc.ListAssetAddressesResponse + (*ListAssetReceivesRequest)(nil), // 107: waverpc.ListAssetReceivesRequest + (*ListAssetReceivesResponse)(nil), // 108: waverpc.ListAssetReceivesResponse + (*AssetReceive)(nil), // 109: waverpc.AssetReceive + (*SyncAssetReceivesRequest)(nil), // 110: waverpc.SyncAssetReceivesRequest + (*SyncAssetReceivesResponse)(nil), // 111: waverpc.SyncAssetReceivesResponse + (*JoinNextRoundRequest)(nil), // 112: waverpc.JoinNextRoundRequest + (*JoinNextRoundResponse)(nil), // 113: waverpc.JoinNextRoundResponse + (*SweepBoardingUTXOsRequest)(nil), // 114: waverpc.SweepBoardingUTXOsRequest + (*BoardingSweepOutput)(nil), // 115: waverpc.BoardingSweepOutput + (*SweepBoardingUTXOsResponse)(nil), // 116: waverpc.SweepBoardingUTXOsResponse + (*ListBoardingSweepsRequest)(nil), // 117: waverpc.ListBoardingSweepsRequest + (*BoardingSweepInput)(nil), // 118: waverpc.BoardingSweepInput + (*BoardingSweep)(nil), // 119: waverpc.BoardingSweep + (*ListBoardingSweepsResponse)(nil), // 120: waverpc.ListBoardingSweepsResponse + (*RoundVTXOInfo)(nil), // 121: waverpc.RoundVTXOInfo + (*ScheduledBatchWindow)(nil), // 122: waverpc.ScheduledBatchWindow + (*RoundInfo)(nil), // 123: waverpc.RoundInfo + (*ListRoundsRequest)(nil), // 124: waverpc.ListRoundsRequest + (*GetRoundRequest)(nil), // 125: waverpc.GetRoundRequest + (*GetRoundResponse)(nil), // 126: waverpc.GetRoundResponse + (*ListRoundsResponse)(nil), // 127: waverpc.ListRoundsResponse + (*WatchRoundsRequest)(nil), // 128: waverpc.WatchRoundsRequest + (*WatchRoundsResponse)(nil), // 129: waverpc.WatchRoundsResponse + (*OORSessionInfo)(nil), // 130: waverpc.OORSessionInfo + (*ListOORSessionsRequest)(nil), // 131: waverpc.ListOORSessionsRequest + (*ListOORSessionsResponse)(nil), // 132: waverpc.ListOORSessionsResponse + (*GetOORSessionRequest)(nil), // 133: waverpc.GetOORSessionRequest + (*GetOORSessionResponse)(nil), // 134: waverpc.GetOORSessionResponse + (*EstimateFeeRequest)(nil), // 135: waverpc.EstimateFeeRequest + (*EstimateFeeResponse)(nil), // 136: waverpc.EstimateFeeResponse + (*GetFeeHistoryRequest)(nil), // 137: waverpc.GetFeeHistoryRequest + (*FeeHistoryEntry)(nil), // 138: waverpc.FeeHistoryEntry + (*GetFeeHistoryResponse)(nil), // 139: waverpc.GetFeeHistoryResponse + (*ListTransactionsRequest)(nil), // 140: waverpc.ListTransactionsRequest + (*TransactionHistoryEntry)(nil), // 141: waverpc.TransactionHistoryEntry + (*ListTransactionsResponse)(nil), // 142: waverpc.ListTransactionsResponse + (*UnrollRequest)(nil), // 143: waverpc.UnrollRequest + (*UnrollResponse)(nil), // 144: waverpc.UnrollResponse + (*GetUnrollStatusRequest)(nil), // 145: waverpc.GetUnrollStatusRequest + (*UnrollProgress)(nil), // 146: waverpc.UnrollProgress + (*UnrollCSV)(nil), // 147: waverpc.UnrollCSV + (*UnrollFees)(nil), // 148: waverpc.UnrollFees + (*GetUnrollStatusResponse)(nil), // 149: waverpc.GetUnrollStatusResponse + (*ArmVHTLCRecoveryRequest)(nil), // 150: waverpc.ArmVHTLCRecoveryRequest + (*ArmVHTLCRecoveryResponse)(nil), // 151: waverpc.ArmVHTLCRecoveryResponse + (*EscalateVHTLCRecoveryRequest)(nil), // 152: waverpc.EscalateVHTLCRecoveryRequest + (*EscalateVHTLCRecoveryResponse)(nil), // 153: waverpc.EscalateVHTLCRecoveryResponse + (*CancelVHTLCRecoveryRequest)(nil), // 154: waverpc.CancelVHTLCRecoveryRequest + (*CancelVHTLCRecoveryResponse)(nil), // 155: waverpc.CancelVHTLCRecoveryResponse + (*GetVHTLCRecoveryStatusRequest)(nil), // 156: waverpc.GetVHTLCRecoveryStatusRequest + (*GetVHTLCRecoveryStatusResponse)(nil), // 157: waverpc.GetVHTLCRecoveryStatusResponse + (*ListVHTLCRecoveriesRequest)(nil), // 158: waverpc.ListVHTLCRecoveriesRequest + (*ListVHTLCRecoveriesResponse)(nil), // 159: waverpc.ListVHTLCRecoveriesResponse + (*VHTLCRecoveryStatus)(nil), // 160: waverpc.VHTLCRecoveryStatus + (*SignOutSwapHtlcAckRequest)(nil), // 161: waverpc.SignOutSwapHtlcAckRequest + (*SignOutSwapHtlcAckResponse)(nil), // 162: waverpc.SignOutSwapHtlcAckResponse + (*SignCreditAccountAuthorizationRequest)(nil), // 163: waverpc.SignCreditAccountAuthorizationRequest + (*SignCreditAccountAuthorizationResponse)(nil), // 164: waverpc.SignCreditAccountAuthorizationResponse + (*MacaroonPermission)(nil), // 165: waverpc.MacaroonPermission + (*BakeMacaroonRequest)(nil), // 166: waverpc.BakeMacaroonRequest + (*BakeMacaroonResponse)(nil), // 167: waverpc.BakeMacaroonResponse + (*MacaroonPermissionList)(nil), // 168: waverpc.MacaroonPermissionList + (*ListPermissionsRequest)(nil), // 169: waverpc.ListPermissionsRequest + (*ListPermissionsResponse)(nil), // 170: waverpc.ListPermissionsResponse + (*DeriveSwapPreimageRequest)(nil), // 171: waverpc.DeriveSwapPreimageRequest + (*DeriveSwapPreimageResponse)(nil), // 172: waverpc.DeriveSwapPreimageResponse + (*CooperativeOORPackage)(nil), // 173: waverpc.CooperativeOORPackage + nil, // 174: waverpc.LeaveVTXOsRequest.DestinationsEntry + nil, // 175: waverpc.LeaveVTXOsResponse.ErrorsEntry + nil, // 176: waverpc.ListPermissionsResponse.MethodPermissionsEntry } var file_daemon_proto_depIdxs = []int32{ 0, // 0: waverpc.GetInfoResponse.wallet_state:type_name -> waverpc.WalletState @@ -14192,72 +14460,72 @@ var file_daemon_proto_depIdxs = []int32{ 55, // 19: waverpc.CustomOORInput.payout_signatures:type_name -> waverpc.TaprootScriptSignature 50, // 20: waverpc.PrepareOORRequest.recipient:type_name -> waverpc.Output 54, // 21: waverpc.PrepareOORRequest.custom_inputs:type_name -> waverpc.CustomOORInput - 58, // 22: waverpc.PrepareOORResponse.custom_inputs:type_name -> waverpc.PreparedOORCustomInput + 60, // 22: waverpc.PrepareOORResponse.custom_inputs:type_name -> waverpc.PreparedOORCustomInput 54, // 23: waverpc.SignOORCustomInputRequest.custom_input:type_name -> waverpc.CustomOORInput - 171, // 24: waverpc.SignOORCustomInputRequest.cooperative_package:type_name -> waverpc.CooperativeOORPackage + 173, // 24: waverpc.SignOORCustomInputRequest.cooperative_package:type_name -> waverpc.CooperativeOORPackage 55, // 25: waverpc.SignOORCustomInputResponse.signature:type_name -> waverpc.TaprootScriptSignature 55, // 26: waverpc.SignOORCustomInputResponse.payout_signature:type_name -> waverpc.TaprootScriptSignature 3, // 27: waverpc.ForfeitSigningContext.signing_route:type_name -> waverpc.ForfeitSigningRoute - 65, // 28: waverpc.RefreshVTXOsRequest.outpoints:type_name -> waverpc.OutpointSelection - 68, // 29: waverpc.RefreshVTXOsResponse.fee_estimate:type_name -> waverpc.RefreshFeeEstimate - 69, // 30: waverpc.RefreshFeeEstimate.outpoints:type_name -> waverpc.OutpointFeeEstimate - 64, // 31: waverpc.CustomRefreshVTXOInput.forfeit_signing_context:type_name -> waverpc.ForfeitSigningContext - 70, // 32: waverpc.RefreshCustomVTXOsRequest.inputs:type_name -> waverpc.CustomRefreshVTXOInput - 71, // 33: waverpc.RefreshCustomVTXOsRequest.outputs:type_name -> waverpc.CustomRefreshVTXOOutput + 67, // 28: waverpc.RefreshVTXOsRequest.outpoints:type_name -> waverpc.OutpointSelection + 70, // 29: waverpc.RefreshVTXOsResponse.fee_estimate:type_name -> waverpc.RefreshFeeEstimate + 71, // 30: waverpc.RefreshFeeEstimate.outpoints:type_name -> waverpc.OutpointFeeEstimate + 66, // 31: waverpc.CustomRefreshVTXOInput.forfeit_signing_context:type_name -> waverpc.ForfeitSigningContext + 72, // 32: waverpc.RefreshCustomVTXOsRequest.inputs:type_name -> waverpc.CustomRefreshVTXOInput + 73, // 33: waverpc.RefreshCustomVTXOsRequest.outputs:type_name -> waverpc.CustomRefreshVTXOOutput 3, // 34: waverpc.PendingForfeitParticipantSignatureRequest.signing_route:type_name -> waverpc.ForfeitSigningRoute - 74, // 35: waverpc.ListPendingForfeitParticipantSignatureRequestsResponse.requests:type_name -> waverpc.PendingForfeitParticipantSignatureRequest - 77, // 36: waverpc.SubmitForfeitParticipantSignaturesRequest.signatures:type_name -> waverpc.ForfeitParticipantSignature - 65, // 37: waverpc.LeaveVTXOsRequest.outpoints:type_name -> waverpc.OutpointSelection - 80, // 38: waverpc.LeaveVTXOsRequest.default_destination:type_name -> waverpc.LeaveDestination - 172, // 39: waverpc.LeaveVTXOsRequest.destinations:type_name -> waverpc.LeaveVTXOsRequest.DestinationsEntry - 173, // 40: waverpc.LeaveVTXOsResponse.errors:type_name -> waverpc.LeaveVTXOsResponse.ErrorsEntry - 80, // 41: waverpc.SendOnChainRequest.destination:type_name -> waverpc.LeaveDestination - 92, // 42: waverpc.ListAssetDepositsResponse.deposits:type_name -> waverpc.AssetDeposit + 76, // 35: waverpc.ListPendingForfeitParticipantSignatureRequestsResponse.requests:type_name -> waverpc.PendingForfeitParticipantSignatureRequest + 79, // 36: waverpc.SubmitForfeitParticipantSignaturesRequest.signatures:type_name -> waverpc.ForfeitParticipantSignature + 67, // 37: waverpc.LeaveVTXOsRequest.outpoints:type_name -> waverpc.OutpointSelection + 82, // 38: waverpc.LeaveVTXOsRequest.default_destination:type_name -> waverpc.LeaveDestination + 174, // 39: waverpc.LeaveVTXOsRequest.destinations:type_name -> waverpc.LeaveVTXOsRequest.DestinationsEntry + 175, // 40: waverpc.LeaveVTXOsResponse.errors:type_name -> waverpc.LeaveVTXOsResponse.ErrorsEntry + 82, // 41: waverpc.SendOnChainRequest.destination:type_name -> waverpc.LeaveDestination + 94, // 42: waverpc.ListAssetDepositsResponse.deposits:type_name -> waverpc.AssetDeposit 4, // 43: waverpc.AssetDeposit.status:type_name -> waverpc.AssetDepositStatus - 100, // 44: waverpc.ListOwnedAssetsResponse.assets:type_name -> waverpc.OwnedAsset - 102, // 45: waverpc.ListAssetAddressesResponse.addresses:type_name -> waverpc.AssetAddress - 107, // 46: waverpc.ListAssetReceivesResponse.receives:type_name -> waverpc.AssetReceive + 102, // 44: waverpc.ListOwnedAssetsResponse.assets:type_name -> waverpc.OwnedAsset + 104, // 45: waverpc.ListAssetAddressesResponse.addresses:type_name -> waverpc.AssetAddress + 109, // 46: waverpc.ListAssetReceivesResponse.receives:type_name -> waverpc.AssetReceive 5, // 47: waverpc.AssetReceive.status:type_name -> waverpc.AssetReceiveStatus - 113, // 48: waverpc.SweepBoardingUTXOsResponse.sweepable_outputs:type_name -> waverpc.BoardingSweepOutput - 116, // 49: waverpc.BoardingSweep.inputs:type_name -> waverpc.BoardingSweepInput - 117, // 50: waverpc.ListBoardingSweepsResponse.sweeps:type_name -> waverpc.BoardingSweep + 115, // 48: waverpc.SweepBoardingUTXOsResponse.sweepable_outputs:type_name -> waverpc.BoardingSweepOutput + 118, // 49: waverpc.BoardingSweep.inputs:type_name -> waverpc.BoardingSweepInput + 119, // 50: waverpc.ListBoardingSweepsResponse.sweeps:type_name -> waverpc.BoardingSweep 6, // 51: waverpc.RoundInfo.state:type_name -> waverpc.RoundState - 119, // 52: waverpc.RoundInfo.vtxos:type_name -> waverpc.RoundVTXOInfo - 120, // 53: waverpc.RoundInfo.batch_window:type_name -> waverpc.ScheduledBatchWindow + 121, // 52: waverpc.RoundInfo.vtxos:type_name -> waverpc.RoundVTXOInfo + 122, // 53: waverpc.RoundInfo.batch_window:type_name -> waverpc.ScheduledBatchWindow 6, // 54: waverpc.ListRoundsRequest.state_filter:type_name -> waverpc.RoundState - 121, // 55: waverpc.GetRoundResponse.round:type_name -> waverpc.RoundInfo - 121, // 56: waverpc.ListRoundsResponse.rounds:type_name -> waverpc.RoundInfo - 121, // 57: waverpc.WatchRoundsResponse.round:type_name -> waverpc.RoundInfo + 123, // 55: waverpc.GetRoundResponse.round:type_name -> waverpc.RoundInfo + 123, // 56: waverpc.ListRoundsResponse.rounds:type_name -> waverpc.RoundInfo + 123, // 57: waverpc.WatchRoundsResponse.round:type_name -> waverpc.RoundInfo 7, // 58: waverpc.OORSessionInfo.direction:type_name -> waverpc.OORSessionDirection 8, // 59: waverpc.OORSessionInfo.status:type_name -> waverpc.OORSessionStatus 7, // 60: waverpc.ListOORSessionsRequest.direction_filter:type_name -> waverpc.OORSessionDirection 8, // 61: waverpc.ListOORSessionsRequest.status_filter:type_name -> waverpc.OORSessionStatus - 128, // 62: waverpc.ListOORSessionsResponse.sessions:type_name -> waverpc.OORSessionInfo - 128, // 63: waverpc.GetOORSessionResponse.session:type_name -> waverpc.OORSessionInfo - 136, // 64: waverpc.GetFeeHistoryResponse.entries:type_name -> waverpc.FeeHistoryEntry - 139, // 65: waverpc.ListTransactionsResponse.transactions:type_name -> waverpc.TransactionHistoryEntry + 130, // 62: waverpc.ListOORSessionsResponse.sessions:type_name -> waverpc.OORSessionInfo + 130, // 63: waverpc.GetOORSessionResponse.session:type_name -> waverpc.OORSessionInfo + 138, // 64: waverpc.GetFeeHistoryResponse.entries:type_name -> waverpc.FeeHistoryEntry + 141, // 65: waverpc.ListTransactionsResponse.transactions:type_name -> waverpc.TransactionHistoryEntry 9, // 66: waverpc.GetUnrollStatusResponse.status:type_name -> waverpc.UnrollJobStatus - 144, // 67: waverpc.GetUnrollStatusResponse.progress:type_name -> waverpc.UnrollProgress - 145, // 68: waverpc.GetUnrollStatusResponse.csv:type_name -> waverpc.UnrollCSV - 146, // 69: waverpc.GetUnrollStatusResponse.fees:type_name -> waverpc.UnrollFees + 146, // 67: waverpc.GetUnrollStatusResponse.progress:type_name -> waverpc.UnrollProgress + 147, // 68: waverpc.GetUnrollStatusResponse.csv:type_name -> waverpc.UnrollCSV + 148, // 69: waverpc.GetUnrollStatusResponse.fees:type_name -> waverpc.UnrollFees 10, // 70: waverpc.ArmVHTLCRecoveryRequest.direction:type_name -> waverpc.VHTLCRecoveryDirection 11, // 71: waverpc.ArmVHTLCRecoveryRequest.action:type_name -> waverpc.VHTLCRecoveryAction - 158, // 72: waverpc.ArmVHTLCRecoveryResponse.status:type_name -> waverpc.VHTLCRecoveryStatus - 158, // 73: waverpc.EscalateVHTLCRecoveryResponse.status:type_name -> waverpc.VHTLCRecoveryStatus - 158, // 74: waverpc.CancelVHTLCRecoveryResponse.status:type_name -> waverpc.VHTLCRecoveryStatus - 158, // 75: waverpc.GetVHTLCRecoveryStatusResponse.status:type_name -> waverpc.VHTLCRecoveryStatus - 158, // 76: waverpc.ListVHTLCRecoveriesResponse.statuses:type_name -> waverpc.VHTLCRecoveryStatus + 160, // 72: waverpc.ArmVHTLCRecoveryResponse.status:type_name -> waverpc.VHTLCRecoveryStatus + 160, // 73: waverpc.EscalateVHTLCRecoveryResponse.status:type_name -> waverpc.VHTLCRecoveryStatus + 160, // 74: waverpc.CancelVHTLCRecoveryResponse.status:type_name -> waverpc.VHTLCRecoveryStatus + 160, // 75: waverpc.GetVHTLCRecoveryStatusResponse.status:type_name -> waverpc.VHTLCRecoveryStatus + 160, // 76: waverpc.ListVHTLCRecoveriesResponse.statuses:type_name -> waverpc.VHTLCRecoveryStatus 10, // 77: waverpc.VHTLCRecoveryStatus.direction:type_name -> waverpc.VHTLCRecoveryDirection 11, // 78: waverpc.VHTLCRecoveryStatus.action:type_name -> waverpc.VHTLCRecoveryAction 12, // 79: waverpc.VHTLCRecoveryStatus.state:type_name -> waverpc.VHTLCRecoveryState 9, // 80: waverpc.VHTLCRecoveryStatus.unroll_status:type_name -> waverpc.UnrollJobStatus - 163, // 81: waverpc.BakeMacaroonRequest.permissions:type_name -> waverpc.MacaroonPermission - 163, // 82: waverpc.MacaroonPermissionList.permissions:type_name -> waverpc.MacaroonPermission - 174, // 83: waverpc.ListPermissionsResponse.method_permissions:type_name -> waverpc.ListPermissionsResponse.MethodPermissionsEntry + 165, // 81: waverpc.BakeMacaroonRequest.permissions:type_name -> waverpc.MacaroonPermission + 165, // 82: waverpc.MacaroonPermissionList.permissions:type_name -> waverpc.MacaroonPermission + 176, // 83: waverpc.ListPermissionsResponse.method_permissions:type_name -> waverpc.ListPermissionsResponse.MethodPermissionsEntry 54, // 84: waverpc.CooperativeOORPackage.custom_input:type_name -> waverpc.CustomOORInput 50, // 85: waverpc.CooperativeOORPackage.recipient:type_name -> waverpc.Output - 80, // 86: waverpc.LeaveVTXOsRequest.DestinationsEntry.value:type_name -> waverpc.LeaveDestination - 166, // 87: waverpc.ListPermissionsResponse.MethodPermissionsEntry.value:type_name -> waverpc.MacaroonPermissionList + 82, // 86: waverpc.LeaveVTXOsRequest.DestinationsEntry.value:type_name -> waverpc.LeaveDestination + 168, // 87: waverpc.ListPermissionsResponse.MethodPermissionsEntry.value:type_name -> waverpc.MacaroonPermissionList 13, // 88: waverpc.DaemonService.GetInfo:input_type -> waverpc.GetInfoRequest 16, // 89: waverpc.DaemonService.GenSeed:input_type -> waverpc.GenSeedRequest 18, // 90: waverpc.DaemonService.InitWallet:input_type -> waverpc.InitWalletRequest @@ -14271,121 +14539,123 @@ var file_daemon_proto_depIdxs = []int32{ 38, // 98: waverpc.DaemonService.SignReceiveAuthMessageCompact:input_type -> waverpc.SignReceiveAuthMessageCompactRequest 40, // 99: waverpc.DaemonService.SignIdentitySchnorr:input_type -> waverpc.SignIdentitySchnorrRequest 42, // 100: waverpc.DaemonService.ReceiveAuthECDH:input_type -> waverpc.ReceiveAuthECDHRequest - 169, // 101: waverpc.DaemonService.DeriveSwapPreimage:input_type -> waverpc.DeriveSwapPreimageRequest + 171, // 101: waverpc.DaemonService.DeriveSwapPreimage:input_type -> waverpc.DeriveSwapPreimageRequest 44, // 102: waverpc.DaemonService.GetIndexedVTXOByPkScript:input_type -> waverpc.GetIndexedVTXOByPkScriptRequest 46, // 103: waverpc.DaemonService.GetVTXOExpiryInfo:input_type -> waverpc.GetVTXOExpiryInfoRequest 48, // 104: waverpc.DaemonService.GetIndexedOORSessionByTxid:input_type -> waverpc.GetIndexedOORSessionByTxidRequest 51, // 105: waverpc.DaemonService.SendVTXO:input_type -> waverpc.SendVTXORequest 53, // 106: waverpc.DaemonService.SendOOR:input_type -> waverpc.SendOORRequest - 57, // 107: waverpc.DaemonService.PrepareOOR:input_type -> waverpc.PrepareOORRequest - 60, // 108: waverpc.DaemonService.SignOORCustomInput:input_type -> waverpc.SignOORCustomInputRequest - 62, // 109: waverpc.DaemonService.SignVTXOForfeit:input_type -> waverpc.SignVTXOForfeitRequest - 66, // 110: waverpc.DaemonService.RefreshVTXOs:input_type -> waverpc.RefreshVTXOsRequest - 72, // 111: waverpc.DaemonService.RefreshCustomVTXOs:input_type -> waverpc.RefreshCustomVTXOsRequest - 75, // 112: waverpc.DaemonService.ListPendingForfeitParticipantSignatureRequests:input_type -> waverpc.ListPendingForfeitParticipantSignatureRequestsRequest - 78, // 113: waverpc.DaemonService.SubmitForfeitParticipantSignatures:input_type -> waverpc.SubmitForfeitParticipantSignaturesRequest - 81, // 114: waverpc.DaemonService.LeaveVTXOs:input_type -> waverpc.LeaveVTXOsRequest - 83, // 115: waverpc.DaemonService.SendOnChain:input_type -> waverpc.SendOnChainRequest - 85, // 116: waverpc.DaemonService.Board:input_type -> waverpc.BoardRequest - 87, // 117: waverpc.DaemonService.DepositAsset:input_type -> waverpc.DepositAssetRequest - 88, // 118: waverpc.DaemonService.ListAssetDeposits:input_type -> waverpc.ListAssetDepositsRequest - 89, // 119: waverpc.DaemonService.BoardAssetDeposit:input_type -> waverpc.BoardAssetDepositRequest - 90, // 120: waverpc.DaemonService.ClaimAssetDeposit:input_type -> waverpc.ClaimAssetDepositRequest - 93, // 121: waverpc.DaemonService.NewAssetReceiveKeys:input_type -> waverpc.NewAssetReceiveKeysRequest - 95, // 122: waverpc.DaemonService.ImportAssetProof:input_type -> waverpc.ImportAssetProofRequest - 98, // 123: waverpc.DaemonService.ListOwnedAssets:input_type -> waverpc.ListOwnedAssetsRequest - 96, // 124: waverpc.DaemonService.NewAssetFundingAddress:input_type -> waverpc.NewAssetFundingAddressRequest - 101, // 125: waverpc.DaemonService.NewAssetAddress:input_type -> waverpc.NewAssetAddressRequest - 103, // 126: waverpc.DaemonService.ListAssetAddresses:input_type -> waverpc.ListAssetAddressesRequest - 105, // 127: waverpc.DaemonService.ListAssetReceives:input_type -> waverpc.ListAssetReceivesRequest - 108, // 128: waverpc.DaemonService.SyncAssetReceives:input_type -> waverpc.SyncAssetReceivesRequest - 110, // 129: waverpc.DaemonService.JoinNextRound:input_type -> waverpc.JoinNextRoundRequest - 112, // 130: waverpc.DaemonService.SweepBoardingUTXOs:input_type -> waverpc.SweepBoardingUTXOsRequest - 115, // 131: waverpc.DaemonService.ListBoardingSweeps:input_type -> waverpc.ListBoardingSweepsRequest - 122, // 132: waverpc.DaemonService.ListRounds:input_type -> waverpc.ListRoundsRequest - 123, // 133: waverpc.DaemonService.GetRound:input_type -> waverpc.GetRoundRequest - 126, // 134: waverpc.DaemonService.WatchRounds:input_type -> waverpc.WatchRoundsRequest - 129, // 135: waverpc.DaemonService.ListOORSessions:input_type -> waverpc.ListOORSessionsRequest - 131, // 136: waverpc.DaemonService.GetOORSession:input_type -> waverpc.GetOORSessionRequest - 133, // 137: waverpc.DaemonService.EstimateFee:input_type -> waverpc.EstimateFeeRequest - 135, // 138: waverpc.DaemonService.GetFeeHistory:input_type -> waverpc.GetFeeHistoryRequest - 138, // 139: waverpc.DaemonService.ListTransactions:input_type -> waverpc.ListTransactionsRequest - 141, // 140: waverpc.DaemonService.Unroll:input_type -> waverpc.UnrollRequest - 143, // 141: waverpc.DaemonService.GetUnrollStatus:input_type -> waverpc.GetUnrollStatusRequest - 148, // 142: waverpc.DaemonService.ArmVHTLCRecovery:input_type -> waverpc.ArmVHTLCRecoveryRequest - 150, // 143: waverpc.DaemonService.EscalateVHTLCRecovery:input_type -> waverpc.EscalateVHTLCRecoveryRequest - 152, // 144: waverpc.DaemonService.CancelVHTLCRecovery:input_type -> waverpc.CancelVHTLCRecoveryRequest - 154, // 145: waverpc.DaemonService.GetVHTLCRecoveryStatus:input_type -> waverpc.GetVHTLCRecoveryStatusRequest - 156, // 146: waverpc.DaemonService.ListVHTLCRecoveries:input_type -> waverpc.ListVHTLCRecoveriesRequest - 159, // 147: waverpc.DaemonService.SignOutSwapHtlcAck:input_type -> waverpc.SignOutSwapHtlcAckRequest - 161, // 148: waverpc.DaemonService.SignCreditAccountAuthorization:input_type -> waverpc.SignCreditAccountAuthorizationRequest - 164, // 149: waverpc.MacaroonService.BakeMacaroon:input_type -> waverpc.BakeMacaroonRequest - 167, // 150: waverpc.MacaroonService.ListPermissions:input_type -> waverpc.ListPermissionsRequest - 14, // 151: waverpc.DaemonService.GetInfo:output_type -> waverpc.GetInfoResponse - 17, // 152: waverpc.DaemonService.GenSeed:output_type -> waverpc.GenSeedResponse - 19, // 153: waverpc.DaemonService.InitWallet:output_type -> waverpc.InitWalletResponse - 21, // 154: waverpc.DaemonService.UnlockWallet:output_type -> waverpc.UnlockWalletResponse - 23, // 155: waverpc.DaemonService.GetBalance:output_type -> waverpc.GetBalanceResponse - 29, // 156: waverpc.DaemonService.ListVTXOs:output_type -> waverpc.ListVTXOsResponse - 31, // 157: waverpc.DaemonService.NewAddress:output_type -> waverpc.NewAddressResponse - 33, // 158: waverpc.DaemonService.NewReceiveScript:output_type -> waverpc.NewReceiveScriptResponse - 35, // 159: waverpc.DaemonService.ReceiveAuthKey:output_type -> waverpc.ReceiveAuthKeyResponse - 37, // 160: waverpc.DaemonService.SignReceiveAuthMessage:output_type -> waverpc.SignReceiveAuthMessageResponse - 39, // 161: waverpc.DaemonService.SignReceiveAuthMessageCompact:output_type -> waverpc.SignReceiveAuthMessageCompactResponse - 41, // 162: waverpc.DaemonService.SignIdentitySchnorr:output_type -> waverpc.SignIdentitySchnorrResponse - 43, // 163: waverpc.DaemonService.ReceiveAuthECDH:output_type -> waverpc.ReceiveAuthECDHResponse - 170, // 164: waverpc.DaemonService.DeriveSwapPreimage:output_type -> waverpc.DeriveSwapPreimageResponse - 45, // 165: waverpc.DaemonService.GetIndexedVTXOByPkScript:output_type -> waverpc.GetIndexedVTXOByPkScriptResponse - 47, // 166: waverpc.DaemonService.GetVTXOExpiryInfo:output_type -> waverpc.GetVTXOExpiryInfoResponse - 49, // 167: waverpc.DaemonService.GetIndexedOORSessionByTxid:output_type -> waverpc.GetIndexedOORSessionByTxidResponse - 52, // 168: waverpc.DaemonService.SendVTXO:output_type -> waverpc.SendVTXOResponse - 56, // 169: waverpc.DaemonService.SendOOR:output_type -> waverpc.SendOORResponse - 59, // 170: waverpc.DaemonService.PrepareOOR:output_type -> waverpc.PrepareOORResponse - 61, // 171: waverpc.DaemonService.SignOORCustomInput:output_type -> waverpc.SignOORCustomInputResponse - 63, // 172: waverpc.DaemonService.SignVTXOForfeit:output_type -> waverpc.SignVTXOForfeitResponse - 67, // 173: waverpc.DaemonService.RefreshVTXOs:output_type -> waverpc.RefreshVTXOsResponse - 73, // 174: waverpc.DaemonService.RefreshCustomVTXOs:output_type -> waverpc.RefreshCustomVTXOsResponse - 76, // 175: waverpc.DaemonService.ListPendingForfeitParticipantSignatureRequests:output_type -> waverpc.ListPendingForfeitParticipantSignatureRequestsResponse - 79, // 176: waverpc.DaemonService.SubmitForfeitParticipantSignatures:output_type -> waverpc.SubmitForfeitParticipantSignaturesResponse - 82, // 177: waverpc.DaemonService.LeaveVTXOs:output_type -> waverpc.LeaveVTXOsResponse - 84, // 178: waverpc.DaemonService.SendOnChain:output_type -> waverpc.SendOnChainResponse - 86, // 179: waverpc.DaemonService.Board:output_type -> waverpc.BoardResponse - 92, // 180: waverpc.DaemonService.DepositAsset:output_type -> waverpc.AssetDeposit - 91, // 181: waverpc.DaemonService.ListAssetDeposits:output_type -> waverpc.ListAssetDepositsResponse - 92, // 182: waverpc.DaemonService.BoardAssetDeposit:output_type -> waverpc.AssetDeposit - 92, // 183: waverpc.DaemonService.ClaimAssetDeposit:output_type -> waverpc.AssetDeposit - 94, // 184: waverpc.DaemonService.NewAssetReceiveKeys:output_type -> waverpc.AssetReceiveKeys - 100, // 185: waverpc.DaemonService.ImportAssetProof:output_type -> waverpc.OwnedAsset - 99, // 186: waverpc.DaemonService.ListOwnedAssets:output_type -> waverpc.ListOwnedAssetsResponse - 97, // 187: waverpc.DaemonService.NewAssetFundingAddress:output_type -> waverpc.AssetFundingAddress - 102, // 188: waverpc.DaemonService.NewAssetAddress:output_type -> waverpc.AssetAddress - 104, // 189: waverpc.DaemonService.ListAssetAddresses:output_type -> waverpc.ListAssetAddressesResponse - 106, // 190: waverpc.DaemonService.ListAssetReceives:output_type -> waverpc.ListAssetReceivesResponse - 109, // 191: waverpc.DaemonService.SyncAssetReceives:output_type -> waverpc.SyncAssetReceivesResponse - 111, // 192: waverpc.DaemonService.JoinNextRound:output_type -> waverpc.JoinNextRoundResponse - 114, // 193: waverpc.DaemonService.SweepBoardingUTXOs:output_type -> waverpc.SweepBoardingUTXOsResponse - 118, // 194: waverpc.DaemonService.ListBoardingSweeps:output_type -> waverpc.ListBoardingSweepsResponse - 125, // 195: waverpc.DaemonService.ListRounds:output_type -> waverpc.ListRoundsResponse - 124, // 196: waverpc.DaemonService.GetRound:output_type -> waverpc.GetRoundResponse - 127, // 197: waverpc.DaemonService.WatchRounds:output_type -> waverpc.WatchRoundsResponse - 130, // 198: waverpc.DaemonService.ListOORSessions:output_type -> waverpc.ListOORSessionsResponse - 132, // 199: waverpc.DaemonService.GetOORSession:output_type -> waverpc.GetOORSessionResponse - 134, // 200: waverpc.DaemonService.EstimateFee:output_type -> waverpc.EstimateFeeResponse - 137, // 201: waverpc.DaemonService.GetFeeHistory:output_type -> waverpc.GetFeeHistoryResponse - 140, // 202: waverpc.DaemonService.ListTransactions:output_type -> waverpc.ListTransactionsResponse - 142, // 203: waverpc.DaemonService.Unroll:output_type -> waverpc.UnrollResponse - 147, // 204: waverpc.DaemonService.GetUnrollStatus:output_type -> waverpc.GetUnrollStatusResponse - 149, // 205: waverpc.DaemonService.ArmVHTLCRecovery:output_type -> waverpc.ArmVHTLCRecoveryResponse - 151, // 206: waverpc.DaemonService.EscalateVHTLCRecovery:output_type -> waverpc.EscalateVHTLCRecoveryResponse - 153, // 207: waverpc.DaemonService.CancelVHTLCRecovery:output_type -> waverpc.CancelVHTLCRecoveryResponse - 155, // 208: waverpc.DaemonService.GetVHTLCRecoveryStatus:output_type -> waverpc.GetVHTLCRecoveryStatusResponse - 157, // 209: waverpc.DaemonService.ListVHTLCRecoveries:output_type -> waverpc.ListVHTLCRecoveriesResponse - 160, // 210: waverpc.DaemonService.SignOutSwapHtlcAck:output_type -> waverpc.SignOutSwapHtlcAckResponse - 162, // 211: waverpc.DaemonService.SignCreditAccountAuthorization:output_type -> waverpc.SignCreditAccountAuthorizationResponse - 165, // 212: waverpc.MacaroonService.BakeMacaroon:output_type -> waverpc.BakeMacaroonResponse - 168, // 213: waverpc.MacaroonService.ListPermissions:output_type -> waverpc.ListPermissionsResponse - 151, // [151:214] is the sub-list for method output_type - 88, // [88:151] is the sub-list for method input_type + 57, // 107: waverpc.DaemonService.SendAssetOOR:input_type -> waverpc.SendAssetOORRequest + 59, // 108: waverpc.DaemonService.PrepareOOR:input_type -> waverpc.PrepareOORRequest + 62, // 109: waverpc.DaemonService.SignOORCustomInput:input_type -> waverpc.SignOORCustomInputRequest + 64, // 110: waverpc.DaemonService.SignVTXOForfeit:input_type -> waverpc.SignVTXOForfeitRequest + 68, // 111: waverpc.DaemonService.RefreshVTXOs:input_type -> waverpc.RefreshVTXOsRequest + 74, // 112: waverpc.DaemonService.RefreshCustomVTXOs:input_type -> waverpc.RefreshCustomVTXOsRequest + 77, // 113: waverpc.DaemonService.ListPendingForfeitParticipantSignatureRequests:input_type -> waverpc.ListPendingForfeitParticipantSignatureRequestsRequest + 80, // 114: waverpc.DaemonService.SubmitForfeitParticipantSignatures:input_type -> waverpc.SubmitForfeitParticipantSignaturesRequest + 83, // 115: waverpc.DaemonService.LeaveVTXOs:input_type -> waverpc.LeaveVTXOsRequest + 85, // 116: waverpc.DaemonService.SendOnChain:input_type -> waverpc.SendOnChainRequest + 87, // 117: waverpc.DaemonService.Board:input_type -> waverpc.BoardRequest + 89, // 118: waverpc.DaemonService.DepositAsset:input_type -> waverpc.DepositAssetRequest + 90, // 119: waverpc.DaemonService.ListAssetDeposits:input_type -> waverpc.ListAssetDepositsRequest + 91, // 120: waverpc.DaemonService.BoardAssetDeposit:input_type -> waverpc.BoardAssetDepositRequest + 92, // 121: waverpc.DaemonService.ClaimAssetDeposit:input_type -> waverpc.ClaimAssetDepositRequest + 95, // 122: waverpc.DaemonService.NewAssetReceiveKeys:input_type -> waverpc.NewAssetReceiveKeysRequest + 97, // 123: waverpc.DaemonService.ImportAssetProof:input_type -> waverpc.ImportAssetProofRequest + 100, // 124: waverpc.DaemonService.ListOwnedAssets:input_type -> waverpc.ListOwnedAssetsRequest + 98, // 125: waverpc.DaemonService.NewAssetFundingAddress:input_type -> waverpc.NewAssetFundingAddressRequest + 103, // 126: waverpc.DaemonService.NewAssetAddress:input_type -> waverpc.NewAssetAddressRequest + 105, // 127: waverpc.DaemonService.ListAssetAddresses:input_type -> waverpc.ListAssetAddressesRequest + 107, // 128: waverpc.DaemonService.ListAssetReceives:input_type -> waverpc.ListAssetReceivesRequest + 110, // 129: waverpc.DaemonService.SyncAssetReceives:input_type -> waverpc.SyncAssetReceivesRequest + 112, // 130: waverpc.DaemonService.JoinNextRound:input_type -> waverpc.JoinNextRoundRequest + 114, // 131: waverpc.DaemonService.SweepBoardingUTXOs:input_type -> waverpc.SweepBoardingUTXOsRequest + 117, // 132: waverpc.DaemonService.ListBoardingSweeps:input_type -> waverpc.ListBoardingSweepsRequest + 124, // 133: waverpc.DaemonService.ListRounds:input_type -> waverpc.ListRoundsRequest + 125, // 134: waverpc.DaemonService.GetRound:input_type -> waverpc.GetRoundRequest + 128, // 135: waverpc.DaemonService.WatchRounds:input_type -> waverpc.WatchRoundsRequest + 131, // 136: waverpc.DaemonService.ListOORSessions:input_type -> waverpc.ListOORSessionsRequest + 133, // 137: waverpc.DaemonService.GetOORSession:input_type -> waverpc.GetOORSessionRequest + 135, // 138: waverpc.DaemonService.EstimateFee:input_type -> waverpc.EstimateFeeRequest + 137, // 139: waverpc.DaemonService.GetFeeHistory:input_type -> waverpc.GetFeeHistoryRequest + 140, // 140: waverpc.DaemonService.ListTransactions:input_type -> waverpc.ListTransactionsRequest + 143, // 141: waverpc.DaemonService.Unroll:input_type -> waverpc.UnrollRequest + 145, // 142: waverpc.DaemonService.GetUnrollStatus:input_type -> waverpc.GetUnrollStatusRequest + 150, // 143: waverpc.DaemonService.ArmVHTLCRecovery:input_type -> waverpc.ArmVHTLCRecoveryRequest + 152, // 144: waverpc.DaemonService.EscalateVHTLCRecovery:input_type -> waverpc.EscalateVHTLCRecoveryRequest + 154, // 145: waverpc.DaemonService.CancelVHTLCRecovery:input_type -> waverpc.CancelVHTLCRecoveryRequest + 156, // 146: waverpc.DaemonService.GetVHTLCRecoveryStatus:input_type -> waverpc.GetVHTLCRecoveryStatusRequest + 158, // 147: waverpc.DaemonService.ListVHTLCRecoveries:input_type -> waverpc.ListVHTLCRecoveriesRequest + 161, // 148: waverpc.DaemonService.SignOutSwapHtlcAck:input_type -> waverpc.SignOutSwapHtlcAckRequest + 163, // 149: waverpc.DaemonService.SignCreditAccountAuthorization:input_type -> waverpc.SignCreditAccountAuthorizationRequest + 166, // 150: waverpc.MacaroonService.BakeMacaroon:input_type -> waverpc.BakeMacaroonRequest + 169, // 151: waverpc.MacaroonService.ListPermissions:input_type -> waverpc.ListPermissionsRequest + 14, // 152: waverpc.DaemonService.GetInfo:output_type -> waverpc.GetInfoResponse + 17, // 153: waverpc.DaemonService.GenSeed:output_type -> waverpc.GenSeedResponse + 19, // 154: waverpc.DaemonService.InitWallet:output_type -> waverpc.InitWalletResponse + 21, // 155: waverpc.DaemonService.UnlockWallet:output_type -> waverpc.UnlockWalletResponse + 23, // 156: waverpc.DaemonService.GetBalance:output_type -> waverpc.GetBalanceResponse + 29, // 157: waverpc.DaemonService.ListVTXOs:output_type -> waverpc.ListVTXOsResponse + 31, // 158: waverpc.DaemonService.NewAddress:output_type -> waverpc.NewAddressResponse + 33, // 159: waverpc.DaemonService.NewReceiveScript:output_type -> waverpc.NewReceiveScriptResponse + 35, // 160: waverpc.DaemonService.ReceiveAuthKey:output_type -> waverpc.ReceiveAuthKeyResponse + 37, // 161: waverpc.DaemonService.SignReceiveAuthMessage:output_type -> waverpc.SignReceiveAuthMessageResponse + 39, // 162: waverpc.DaemonService.SignReceiveAuthMessageCompact:output_type -> waverpc.SignReceiveAuthMessageCompactResponse + 41, // 163: waverpc.DaemonService.SignIdentitySchnorr:output_type -> waverpc.SignIdentitySchnorrResponse + 43, // 164: waverpc.DaemonService.ReceiveAuthECDH:output_type -> waverpc.ReceiveAuthECDHResponse + 172, // 165: waverpc.DaemonService.DeriveSwapPreimage:output_type -> waverpc.DeriveSwapPreimageResponse + 45, // 166: waverpc.DaemonService.GetIndexedVTXOByPkScript:output_type -> waverpc.GetIndexedVTXOByPkScriptResponse + 47, // 167: waverpc.DaemonService.GetVTXOExpiryInfo:output_type -> waverpc.GetVTXOExpiryInfoResponse + 49, // 168: waverpc.DaemonService.GetIndexedOORSessionByTxid:output_type -> waverpc.GetIndexedOORSessionByTxidResponse + 52, // 169: waverpc.DaemonService.SendVTXO:output_type -> waverpc.SendVTXOResponse + 56, // 170: waverpc.DaemonService.SendOOR:output_type -> waverpc.SendOORResponse + 58, // 171: waverpc.DaemonService.SendAssetOOR:output_type -> waverpc.SendAssetOORResponse + 61, // 172: waverpc.DaemonService.PrepareOOR:output_type -> waverpc.PrepareOORResponse + 63, // 173: waverpc.DaemonService.SignOORCustomInput:output_type -> waverpc.SignOORCustomInputResponse + 65, // 174: waverpc.DaemonService.SignVTXOForfeit:output_type -> waverpc.SignVTXOForfeitResponse + 69, // 175: waverpc.DaemonService.RefreshVTXOs:output_type -> waverpc.RefreshVTXOsResponse + 75, // 176: waverpc.DaemonService.RefreshCustomVTXOs:output_type -> waverpc.RefreshCustomVTXOsResponse + 78, // 177: waverpc.DaemonService.ListPendingForfeitParticipantSignatureRequests:output_type -> waverpc.ListPendingForfeitParticipantSignatureRequestsResponse + 81, // 178: waverpc.DaemonService.SubmitForfeitParticipantSignatures:output_type -> waverpc.SubmitForfeitParticipantSignaturesResponse + 84, // 179: waverpc.DaemonService.LeaveVTXOs:output_type -> waverpc.LeaveVTXOsResponse + 86, // 180: waverpc.DaemonService.SendOnChain:output_type -> waverpc.SendOnChainResponse + 88, // 181: waverpc.DaemonService.Board:output_type -> waverpc.BoardResponse + 94, // 182: waverpc.DaemonService.DepositAsset:output_type -> waverpc.AssetDeposit + 93, // 183: waverpc.DaemonService.ListAssetDeposits:output_type -> waverpc.ListAssetDepositsResponse + 94, // 184: waverpc.DaemonService.BoardAssetDeposit:output_type -> waverpc.AssetDeposit + 94, // 185: waverpc.DaemonService.ClaimAssetDeposit:output_type -> waverpc.AssetDeposit + 96, // 186: waverpc.DaemonService.NewAssetReceiveKeys:output_type -> waverpc.AssetReceiveKeys + 102, // 187: waverpc.DaemonService.ImportAssetProof:output_type -> waverpc.OwnedAsset + 101, // 188: waverpc.DaemonService.ListOwnedAssets:output_type -> waverpc.ListOwnedAssetsResponse + 99, // 189: waverpc.DaemonService.NewAssetFundingAddress:output_type -> waverpc.AssetFundingAddress + 104, // 190: waverpc.DaemonService.NewAssetAddress:output_type -> waverpc.AssetAddress + 106, // 191: waverpc.DaemonService.ListAssetAddresses:output_type -> waverpc.ListAssetAddressesResponse + 108, // 192: waverpc.DaemonService.ListAssetReceives:output_type -> waverpc.ListAssetReceivesResponse + 111, // 193: waverpc.DaemonService.SyncAssetReceives:output_type -> waverpc.SyncAssetReceivesResponse + 113, // 194: waverpc.DaemonService.JoinNextRound:output_type -> waverpc.JoinNextRoundResponse + 116, // 195: waverpc.DaemonService.SweepBoardingUTXOs:output_type -> waverpc.SweepBoardingUTXOsResponse + 120, // 196: waverpc.DaemonService.ListBoardingSweeps:output_type -> waverpc.ListBoardingSweepsResponse + 127, // 197: waverpc.DaemonService.ListRounds:output_type -> waverpc.ListRoundsResponse + 126, // 198: waverpc.DaemonService.GetRound:output_type -> waverpc.GetRoundResponse + 129, // 199: waverpc.DaemonService.WatchRounds:output_type -> waverpc.WatchRoundsResponse + 132, // 200: waverpc.DaemonService.ListOORSessions:output_type -> waverpc.ListOORSessionsResponse + 134, // 201: waverpc.DaemonService.GetOORSession:output_type -> waverpc.GetOORSessionResponse + 136, // 202: waverpc.DaemonService.EstimateFee:output_type -> waverpc.EstimateFeeResponse + 139, // 203: waverpc.DaemonService.GetFeeHistory:output_type -> waverpc.GetFeeHistoryResponse + 142, // 204: waverpc.DaemonService.ListTransactions:output_type -> waverpc.ListTransactionsResponse + 144, // 205: waverpc.DaemonService.Unroll:output_type -> waverpc.UnrollResponse + 149, // 206: waverpc.DaemonService.GetUnrollStatus:output_type -> waverpc.GetUnrollStatusResponse + 151, // 207: waverpc.DaemonService.ArmVHTLCRecovery:output_type -> waverpc.ArmVHTLCRecoveryResponse + 153, // 208: waverpc.DaemonService.EscalateVHTLCRecovery:output_type -> waverpc.EscalateVHTLCRecoveryResponse + 155, // 209: waverpc.DaemonService.CancelVHTLCRecovery:output_type -> waverpc.CancelVHTLCRecoveryResponse + 157, // 210: waverpc.DaemonService.GetVHTLCRecoveryStatus:output_type -> waverpc.GetVHTLCRecoveryStatusResponse + 159, // 211: waverpc.DaemonService.ListVHTLCRecoveries:output_type -> waverpc.ListVHTLCRecoveriesResponse + 162, // 212: waverpc.DaemonService.SignOutSwapHtlcAck:output_type -> waverpc.SignOutSwapHtlcAckResponse + 164, // 213: waverpc.DaemonService.SignCreditAccountAuthorization:output_type -> waverpc.SignCreditAccountAuthorizationResponse + 167, // 214: waverpc.MacaroonService.BakeMacaroon:output_type -> waverpc.BakeMacaroonResponse + 170, // 215: waverpc.MacaroonService.ListPermissions:output_type -> waverpc.ListPermissionsResponse + 152, // [152:216] is the sub-list for method output_type + 88, // [88:152] is the sub-list for method input_type 88, // [88:88] is the sub-list for extension type_name 88, // [88:88] is the sub-list for extension extendee 0, // [0:88] is the sub-list for field type_name @@ -14405,31 +14675,35 @@ func file_daemon_proto_init() { (*Output_Pubkey)(nil), (*Output_PolicyTemplate)(nil), } - file_daemon_proto_msgTypes[53].OneofWrappers = []any{ + file_daemon_proto_msgTypes[44].OneofWrappers = []any{ + (*SendAssetOORRequest_Pubkey)(nil), + (*SendAssetOORRequest_PolicyTemplate)(nil), + } + file_daemon_proto_msgTypes[55].OneofWrappers = []any{ (*RefreshVTXOsRequest_Outpoints)(nil), (*RefreshVTXOsRequest_All)(nil), } - file_daemon_proto_msgTypes[55].OneofWrappers = []any{} - file_daemon_proto_msgTypes[67].OneofWrappers = []any{ + file_daemon_proto_msgTypes[57].OneofWrappers = []any{} + file_daemon_proto_msgTypes[69].OneofWrappers = []any{ (*LeaveDestination_Address)(nil), (*LeaveDestination_PkScript)(nil), } - file_daemon_proto_msgTypes[68].OneofWrappers = []any{ + file_daemon_proto_msgTypes[70].OneofWrappers = []any{ (*LeaveVTXOsRequest_Outpoints)(nil), (*LeaveVTXOsRequest_All)(nil), } - file_daemon_proto_msgTypes[70].OneofWrappers = []any{ + file_daemon_proto_msgTypes[72].OneofWrappers = []any{ (*SendOnChainRequest_AmountSat)(nil), (*SendOnChainRequest_SweepAll)(nil), } - file_daemon_proto_msgTypes[123].OneofWrappers = []any{} + file_daemon_proto_msgTypes[125].OneofWrappers = []any{} type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_daemon_proto_rawDesc), len(file_daemon_proto_rawDesc)), NumEnums: 13, - NumMessages: 162, + NumMessages: 164, NumExtensions: 0, NumServices: 2, }, diff --git a/waverpc/daemon.pb.gw.go b/waverpc/daemon.pb.gw.go index f9738422e..bebd17e27 100644 --- a/waverpc/daemon.pb.gw.go +++ b/waverpc/daemon.pb.gw.go @@ -548,6 +548,33 @@ func local_request_DaemonService_SendOOR_0(ctx context.Context, marshaler runtim return msg, metadata, err } +func request_DaemonService_SendAssetOOR_0(ctx context.Context, marshaler runtime.Marshaler, client DaemonServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var ( + protoReq SendAssetOORRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } + msg, err := client.SendAssetOOR(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err +} + +func local_request_DaemonService_SendAssetOOR_0(ctx context.Context, marshaler runtime.Marshaler, server DaemonServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var ( + protoReq SendAssetOORRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + msg, err := server.SendAssetOOR(ctx, &protoReq) + return msg, metadata, err +} + func request_DaemonService_PrepareOOR_0(ctx context.Context, marshaler runtime.Marshaler, client DaemonServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq PrepareOORRequest @@ -2112,6 +2139,26 @@ func RegisterDaemonServiceHandlerServer(ctx context.Context, mux *runtime.ServeM } forward_DaemonService_SendOOR_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) + mux.Handle(http.MethodPost, pattern_DaemonService_SendAssetOOR_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/waverpc.DaemonService/SendAssetOOR", runtime.WithHTTPPathPattern("/v1/daemon/send-asset-oor")) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_DaemonService_SendAssetOOR_0(annotatedContext, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) + if err != nil { + runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) + return + } + forward_DaemonService_SendAssetOOR_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) mux.Handle(http.MethodPost, pattern_DaemonService_PrepareOOR_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() @@ -3352,6 +3399,23 @@ func RegisterDaemonServiceHandlerClient(ctx context.Context, mux *runtime.ServeM } forward_DaemonService_SendOOR_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) + mux.Handle(http.MethodPost, pattern_DaemonService_SendAssetOOR_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/waverpc.DaemonService/SendAssetOOR", runtime.WithHTTPPathPattern("/v1/daemon/send-asset-oor")) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_DaemonService_SendAssetOOR_0(annotatedContext, inboundMarshaler, client, req, pathParams) + annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) + if err != nil { + runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) + return + } + forward_DaemonService_SendAssetOOR_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) mux.Handle(http.MethodPost, pattern_DaemonService_PrepareOOR_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() @@ -4089,6 +4153,7 @@ var ( pattern_DaemonService_GetIndexedOORSessionByTxid_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "daemon", "get-indexed-oor-session-by-txid"}, "")) pattern_DaemonService_SendVTXO_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "daemon", "send-vtxo"}, "")) pattern_DaemonService_SendOOR_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "daemon", "send-oor"}, "")) + pattern_DaemonService_SendAssetOOR_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "daemon", "send-asset-oor"}, "")) pattern_DaemonService_PrepareOOR_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "daemon", "prepare-oor"}, "")) pattern_DaemonService_SignOORCustomInput_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "daemon", "sign-oor-custom-input"}, "")) pattern_DaemonService_SignVTXOForfeit_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "daemon", "sign-vtxo-forfeit"}, "")) @@ -4153,6 +4218,7 @@ var ( forward_DaemonService_GetIndexedOORSessionByTxid_0 = runtime.ForwardResponseMessage forward_DaemonService_SendVTXO_0 = runtime.ForwardResponseMessage forward_DaemonService_SendOOR_0 = runtime.ForwardResponseMessage + forward_DaemonService_SendAssetOOR_0 = runtime.ForwardResponseMessage forward_DaemonService_PrepareOOR_0 = runtime.ForwardResponseMessage forward_DaemonService_SignOORCustomInput_0 = runtime.ForwardResponseMessage forward_DaemonService_SignVTXOForfeit_0 = runtime.ForwardResponseMessage diff --git a/waverpc/daemon_grpc.pb.go b/waverpc/daemon_grpc.pb.go index f868931d6..a5637adcb 100644 --- a/waverpc/daemon_grpc.pb.go +++ b/waverpc/daemon_grpc.pb.go @@ -38,6 +38,7 @@ const ( DaemonService_GetIndexedOORSessionByTxid_FullMethodName = "/waverpc.DaemonService/GetIndexedOORSessionByTxid" DaemonService_SendVTXO_FullMethodName = "/waverpc.DaemonService/SendVTXO" DaemonService_SendOOR_FullMethodName = "/waverpc.DaemonService/SendOOR" + DaemonService_SendAssetOOR_FullMethodName = "/waverpc.DaemonService/SendAssetOOR" DaemonService_PrepareOOR_FullMethodName = "/waverpc.DaemonService/PrepareOOR" DaemonService_SignOORCustomInput_FullMethodName = "/waverpc.DaemonService/SignOORCustomInput" DaemonService_SignVTXOForfeit_FullMethodName = "/waverpc.DaemonService/SignVTXOForfeit" @@ -153,6 +154,10 @@ type DaemonServiceClient interface { // SendOOR initiates an out-of-round transfer directly between the // client and operator, without waiting for a round. SendOOR(ctx context.Context, in *SendOORRequest, opts ...grpc.CallOption) (*SendOORResponse, error) + // SendAssetOOR initiates an out-of-round Taproot Asset transfer directly + // between the client and operator, merging up to eight live asset VTXOs + // and leasing an operator carrier float for the new asset leaves. + SendAssetOOR(ctx context.Context, in *SendAssetOORRequest, opts ...grpc.CallOption) (*SendAssetOORResponse, error) // PrepareOOR builds the deterministic OOR package without submitting it. // This lets callers collect signatures from external custom-input // participants before calling SendOOR with the same parameters. @@ -543,6 +548,16 @@ func (c *daemonServiceClient) SendOOR(ctx context.Context, in *SendOORRequest, o return out, nil } +func (c *daemonServiceClient) SendAssetOOR(ctx context.Context, in *SendAssetOORRequest, opts ...grpc.CallOption) (*SendAssetOORResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(SendAssetOORResponse) + err := c.cc.Invoke(ctx, DaemonService_SendAssetOOR_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + func (c *daemonServiceClient) PrepareOOR(ctx context.Context, in *PrepareOORRequest, opts ...grpc.CallOption) (*PrepareOORResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(PrepareOORResponse) @@ -1043,6 +1058,10 @@ type DaemonServiceServer interface { // SendOOR initiates an out-of-round transfer directly between the // client and operator, without waiting for a round. SendOOR(context.Context, *SendOORRequest) (*SendOORResponse, error) + // SendAssetOOR initiates an out-of-round Taproot Asset transfer directly + // between the client and operator, merging up to eight live asset VTXOs + // and leasing an operator carrier float for the new asset leaves. + SendAssetOOR(context.Context, *SendAssetOORRequest) (*SendAssetOORResponse, error) // PrepareOOR builds the deterministic OOR package without submitting it. // This lets callers collect signatures from external custom-input // participants before calling SendOOR with the same parameters. @@ -1300,6 +1319,9 @@ func (UnimplementedDaemonServiceServer) SendVTXO(context.Context, *SendVTXOReque func (UnimplementedDaemonServiceServer) SendOOR(context.Context, *SendOORRequest) (*SendOORResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method SendOOR not implemented") } +func (UnimplementedDaemonServiceServer) SendAssetOOR(context.Context, *SendAssetOORRequest) (*SendAssetOORResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method SendAssetOOR not implemented") +} func (UnimplementedDaemonServiceServer) PrepareOOR(context.Context, *PrepareOORRequest) (*PrepareOORResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method PrepareOOR not implemented") } @@ -1789,6 +1811,24 @@ func _DaemonService_SendOOR_Handler(srv interface{}, ctx context.Context, dec fu return interceptor(ctx, in, info, handler) } +func _DaemonService_SendAssetOOR_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(SendAssetOORRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(DaemonServiceServer).SendAssetOOR(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: DaemonService_SendAssetOOR_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(DaemonServiceServer).SendAssetOOR(ctx, req.(*SendAssetOORRequest)) + } + return interceptor(ctx, in, info, handler) +} + func _DaemonService_PrepareOOR_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(PrepareOORRequest) if err := dec(in); err != nil { @@ -2621,6 +2661,10 @@ var DaemonService_ServiceDesc = grpc.ServiceDesc{ MethodName: "SendOOR", Handler: _DaemonService_SendOOR_Handler, }, + { + MethodName: "SendAssetOOR", + Handler: _DaemonService_SendAssetOOR_Handler, + }, { MethodName: "PrepareOOR", Handler: _DaemonService_PrepareOOR_Handler, diff --git a/waverpc/daemon_mailboxrpc.pb.go b/waverpc/daemon_mailboxrpc.pb.go index a387d690c..5c40bc550 100644 --- a/waverpc/daemon_mailboxrpc.pb.go +++ b/waverpc/daemon_mailboxrpc.pb.go @@ -62,6 +62,8 @@ type DaemonServiceMailboxServer interface { SendVTXO(ctx context.Context, req *SendVTXORequest) (*SendVTXOResponse, error) // SendOOR handles SendOOR. SendOOR(ctx context.Context, req *SendOORRequest) (*SendOORResponse, error) + // SendAssetOOR handles SendAssetOOR. + SendAssetOOR(ctx context.Context, req *SendAssetOORRequest) (*SendAssetOORResponse, error) // PrepareOOR handles PrepareOOR. PrepareOOR(ctx context.Context, req *PrepareOORRequest) (*PrepareOORResponse, error) // SignOORCustomInput handles SignOORCustomInput. @@ -340,6 +342,16 @@ func RegisterDaemonServiceMailboxServer(r rpc.Router, impl DaemonServiceMailboxS return impl.SendOOR(ctx, req) }) + r.Handle("waverpc.DaemonService", "SendAssetOOR", func() proto.Message { + return &SendAssetOORRequest{} + }, func(ctx context.Context, msg proto.Message) (proto.Message, error) { + req, ok := msg.(*SendAssetOORRequest) + if !ok { + return nil, fmt.Errorf("unexpected request type: %T", msg) + } + + return impl.SendAssetOOR(ctx, req) + }) r.Handle("waverpc.DaemonService", "PrepareOOR", func() proto.Message { return &PrepareOORRequest{} }, func(ctx context.Context, msg proto.Message) (proto.Message, error) { @@ -1199,6 +1211,29 @@ func (c *DaemonServiceMailboxClient) SendOOR(ctx context.Context, req *SendOORRe return resp, nil } +// SendAssetOOR calls the SendAssetOOR RPC. +func (c *DaemonServiceMailboxClient) SendAssetOOR(ctx context.Context, req *SendAssetOORRequest, opts ...rpc.RPCOptions) (*SendAssetOORResponse, error) { + var opt rpc.RPCOptions + if len(opts) > 0 { + opt = opts[0] + } + + result, err := c.C.SendRPC(ctx, rpc.ServiceMethod{ + Service: "waverpc.DaemonService", + Method: "SendAssetOOR", + }, req, opt) + if err != nil { + return nil, err + } + + resp := new(SendAssetOORResponse) + if err := c.C.AwaitRPC(ctx, result.CorrelationID, resp); err != nil { + return nil, err + } + + return resp, nil +} + // PrepareOOR calls the PrepareOOR RPC. func (c *DaemonServiceMailboxClient) PrepareOOR(ctx context.Context, req *PrepareOORRequest, opts ...rpc.RPCOptions) (*PrepareOORResponse, error) { var opt rpc.RPCOptions From 31c7def92f5ed07e20d7a1512ddf4a58ea7454a3 Mon Sep 17 00:00:00 2001 From: Dario Anongba Varela Date: Thu, 26 Nov 2026 23:52:38 +0100 Subject: [PATCH 03/15] multi: authenticate asset batch output expiry via batch asset root Asset batch outputs commit to TapBranch(SweepTapscriptRoot, BatchAssetRoot) rather than SweepTapscriptRoot alone. Export arkscript.TapBranchHash, carry optional 32-byte BatchAssetRoot on tree.Tree, lib/treecodec (TLV type 7), arkrpc.TreePath, and tapassets.TreeRootAssetSource, and fold it into vtxo.validateExpiryFragment so AuthenticateBatchEvidence verifies confirmed asset batch outputs without trusting operator expiry scalars. --- arkrpc/AGENTS.md | 4 +- arkrpc/CLAUDE.md | 4 +- arkrpc/tree_path_convert.go | 17 +++++ arkrpc/tree_path_convert_test.go | 51 +++++++++++++ db/tree_codec_asset_test.go | 2 + lib/arkscript/AGENTS.md | 2 +- lib/arkscript/CLAUDE.md | 2 +- lib/arkscript/compose.go | 12 ++- lib/tree/AGENTS.md | 2 +- lib/tree/CLAUDE.md | 2 +- lib/tree/tree.go | 7 ++ lib/treecodec/AGENTS.md | 3 + lib/treecodec/CLAUDE.md | 3 + lib/treecodec/codec.go | 48 +++++++++--- tapassets/batch_anchor.go | 7 +- tapassets/tree_assembler.go | 1 + tapassets/tree_materializer.go | 4 + vtxo/authenticated_expiry.go | 18 ++++- vtxo/authenticated_expiry_test.go | 123 ++++++++++++++++++++++++++++++ 19 files changed, 288 insertions(+), 24 deletions(-) diff --git a/arkrpc/AGENTS.md b/arkrpc/AGENTS.md index 2a7769200..90f4ea617 100644 --- a/arkrpc/AGENTS.md +++ b/arkrpc/AGENTS.md @@ -9,7 +9,9 @@ Proto source: `arkrpc/ark.proto`, `arkrpc/indexer.proto`. ## Key Types - `TreePath` / `TreePathNode` / `TxOut` — Structured proto messages for the - VTXO commitment tree path. + VTXO commitment tree path. `TreePath.batch_asset_root` carries the optional + 32-byte Taproot Asset commitment sibling hash composed beside + `sweep_tapscript_root` in `batch_output` for asset trees. - `TreePathFromTree` / `TreePathToTree` — Lossless conversion between `tree.Tree` and `arkrpc.TreePath`. Uses deterministic pre-order flattening with sorted child indices. Re-exported under the narrower diff --git a/arkrpc/CLAUDE.md b/arkrpc/CLAUDE.md index 2a7769200..90f4ea617 100644 --- a/arkrpc/CLAUDE.md +++ b/arkrpc/CLAUDE.md @@ -9,7 +9,9 @@ Proto source: `arkrpc/ark.proto`, `arkrpc/indexer.proto`. ## Key Types - `TreePath` / `TreePathNode` / `TxOut` — Structured proto messages for the - VTXO commitment tree path. + VTXO commitment tree path. `TreePath.batch_asset_root` carries the optional + 32-byte Taproot Asset commitment sibling hash composed beside + `sweep_tapscript_root` in `batch_output` for asset trees. - `TreePathFromTree` / `TreePathToTree` — Lossless conversion between `tree.Tree` and `arkrpc.TreePath`. Uses deterministic pre-order flattening with sorted child indices. Re-exported under the narrower diff --git a/arkrpc/tree_path_convert.go b/arkrpc/tree_path_convert.go index c256c4dd8..969485de4 100644 --- a/arkrpc/tree_path_convert.go +++ b/arkrpc/tree_path_convert.go @@ -1,6 +1,7 @@ package arkrpc import ( + "bytes" "fmt" "sort" @@ -30,11 +31,19 @@ func TreePathFromTree(t *tree.Tree) (*TreePath, error) { return nil, err } + if len(t.BatchAssetRoot) != 0 && + len(t.BatchAssetRoot) != chainhash.HashSize { + return nil, fmt.Errorf("batch asset root must be %d "+ + "bytes, got %d", chainhash.HashSize, + len(t.BatchAssetRoot)) + } + return &TreePath{ Nodes: nodes, BatchOutpoint: outpointToProto(t.BatchOutpoint), BatchOutput: txOutToProto(t.BatchOutput), SweepTapscriptRoot: t.SweepTapscriptRoot, + BatchAssetRoot: bytes.Clone(t.BatchAssetRoot), }, nil } @@ -196,11 +205,19 @@ func TreePathToTree(tp *TreePath, return nil, fmt.Errorf("batch output: %w", err) } + if len(tp.BatchAssetRoot) != 0 && + len(tp.BatchAssetRoot) != chainhash.HashSize { + return nil, fmt.Errorf("batch asset root must be %d "+ + "bytes, got %d", chainhash.HashSize, + len(tp.BatchAssetRoot)) + } + return &tree.Tree{ Root: goNodes[0], BatchOutpoint: batchOP, BatchOutput: batchOut, SweepTapscriptRoot: tp.SweepTapscriptRoot, + BatchAssetRoot: bytes.Clone(tp.BatchAssetRoot), }, nil } diff --git a/arkrpc/tree_path_convert_test.go b/arkrpc/tree_path_convert_test.go index 5ebd299ce..9af63a48e 100644 --- a/arkrpc/tree_path_convert_test.go +++ b/arkrpc/tree_path_convert_test.go @@ -303,3 +303,54 @@ func TestTreePathTxOutRoundTrip(t *testing.T) { require.Equal(t, out.PkScript, got.PkScript) }) } + +// TestTreePathBatchAssetRootRoundTrip checks that an optional 32-byte +// BatchAssetRoot round-trips through proto conversion and that non-32-byte +// roots are rejected on both directions. +func TestTreePathBatchAssetRootRoundTrip(t *testing.T) { + t.Parallel() + + rootHash := make([]byte, chainhash.HashSize) + for i := range rootHash { + rootHash[i] = byte(i + 1) + } + + orig := &tree.Tree{ + Root: &tree.Node{ + Input: wire.OutPoint{ + Hash: chainhash.Hash{ + 0x01, + }, + }, + }, + BatchOutpoint: wire.OutPoint{ + Hash: chainhash.Hash{ + 0x01, + }, + }, + BatchOutput: &wire.TxOut{ + Value: 1_000, + PkScript: []byte{ + 0x51, + }, + }, + SweepTapscriptRoot: make([]byte, chainhash.HashSize), + BatchAssetRoot: rootHash, + } + + pb, err := TreePathFromTree(orig) + require.NoError(t, err) + require.Equal(t, rootHash, pb.BatchAssetRoot) + + got, err := TreePathToTree(pb) + require.NoError(t, err) + require.Equal(t, rootHash, got.BatchAssetRoot) + + orig.BatchAssetRoot = []byte{0x01, 0x02} + _, err = TreePathFromTree(orig) + require.ErrorContains(t, err, "batch asset root must be 32") + + pb.BatchAssetRoot = []byte{0x01, 0x02} + _, err = TreePathToTree(pb) + require.ErrorContains(t, err, "batch asset root must be 32") +} diff --git a/db/tree_codec_asset_test.go b/db/tree_codec_asset_test.go index a3f26df8b..9ea06206e 100644 --- a/db/tree_codec_asset_test.go +++ b/db/tree_codec_asset_test.go @@ -76,6 +76,7 @@ func newAssetCodecTree(t *testing.T) *tree.Tree { }, }, SweepTapscriptRoot: assetCodecHash("sweep"), + BatchAssetRoot: assetCodecHash("batch-asset-root"), AssetContext: assetCtx, } } @@ -90,6 +91,7 @@ func TestTreeCodecAssetRoundTrip(t *testing.T) { decoded, err := DeserializeTree(encoded) require.NoError(t, err) + require.Equal(t, original.BatchAssetRoot, decoded.BatchAssetRoot) require.NotNil(t, decoded.AssetContext) require.Equal( t, original.AssetContext.AssetRef(), diff --git a/lib/arkscript/AGENTS.md b/lib/arkscript/AGENTS.md index b9f513ddc..77ad38817 100644 --- a/lib/arkscript/AGENTS.md +++ b/lib/arkscript/AGENTS.md @@ -56,7 +56,7 @@ validated invariants. supplying a control block for an unrelated tap tree and obtaining a signature over an attacker-chosen tapscript. - `StandardVTXOParams` — Decoded parameters for a standard Ark VTXO policy (owner key, operator key, CSV delay). Derived via `DecodeStandardVTXOParams`. -- `ComposedPolicy` — Composes an existing `CompiledPolicy` with an additional sibling tap branch root, allowing sub-tree aggregation. Built with `ComposeWithSiblingRoot`. +- `ComposedPolicy` — Composes an existing `CompiledPolicy` with an additional sibling tap branch root, allowing sub-tree aggregation. Built with `ComposeWithSiblingRoot` (which combines roots via `TapBranchHash`). - `ComposedBoardingScript` — Combines a boarding policy with a disclosed asset commitment leaf hash to reconstruct the deposit script and Taproot root. `ComposedBoardingExitSpend` returns the owner's exit spend of that deposit, diff --git a/lib/arkscript/CLAUDE.md b/lib/arkscript/CLAUDE.md index b9f513ddc..77ad38817 100644 --- a/lib/arkscript/CLAUDE.md +++ b/lib/arkscript/CLAUDE.md @@ -56,7 +56,7 @@ validated invariants. supplying a control block for an unrelated tap tree and obtaining a signature over an attacker-chosen tapscript. - `StandardVTXOParams` — Decoded parameters for a standard Ark VTXO policy (owner key, operator key, CSV delay). Derived via `DecodeStandardVTXOParams`. -- `ComposedPolicy` — Composes an existing `CompiledPolicy` with an additional sibling tap branch root, allowing sub-tree aggregation. Built with `ComposeWithSiblingRoot`. +- `ComposedPolicy` — Composes an existing `CompiledPolicy` with an additional sibling tap branch root, allowing sub-tree aggregation. Built with `ComposeWithSiblingRoot` (which combines roots via `TapBranchHash`). - `ComposedBoardingScript` — Combines a boarding policy with a disclosed asset commitment leaf hash to reconstruct the deposit script and Taproot root. `ComposedBoardingExitSpend` returns the owner's exit spend of that deposit, diff --git a/lib/arkscript/compose.go b/lib/arkscript/compose.go index 0afcd67fd..98fc39c0e 100644 --- a/lib/arkscript/compose.go +++ b/lib/arkscript/compose.go @@ -114,9 +114,9 @@ func ComposeWithSiblingRoot(policy *CompiledPolicy, }, nil } -// tapBranchHashCompose computes the BIP-341 TapBranch hash for combining two -// roots. -func tapBranchHashCompose(a, b chainhash.Hash) chainhash.Hash { +// TapBranchHash computes the BIP-341 TapBranch hash combining two taproot +// subtree or leaf hashes in lexicographical order. +func TapBranchHash(a, b chainhash.Hash) chainhash.Hash { // Sort lexicographically per BIP-341. if bytes.Compare(a[:], b[:]) > 0 { a, b = b, a @@ -125,6 +125,12 @@ func tapBranchHashCompose(a, b chainhash.Hash) chainhash.Hash { return *chainhash.TaggedHash(chainhash.TagTapBranch, a[:], b[:]) } +// tapBranchHashCompose computes the BIP-341 TapBranch hash for combining two +// roots. +func tapBranchHashCompose(a, b chainhash.Hash) chainhash.Hash { + return TapBranchHash(a, b) +} + // PolicyRoot returns just the policy root hash from a compiled policy. // This can be used when the caller needs to provide the root for external // composition. The policy must not be nil. diff --git a/lib/tree/AGENTS.md b/lib/tree/AGENTS.md index fe362da0e..7766f1e52 100644 --- a/lib/tree/AGENTS.md +++ b/lib/tree/AGENTS.md @@ -8,7 +8,7 @@ descriptors through branch nodes to the batch output. ## Key Types -- `Tree` — Complete VTXO or connector tree: root outpoint, root output, node hierarchy, and traversal helpers. `Verify` checks structure plus value flow; `ValidateValueConservation` exposes the funding check separately for callers that have already bound `BatchOutput` to an authoritative prevout. Built via `BuildVTXOTree` or `BuildConnectorTree`. +- `Tree` — Complete VTXO or connector tree: root outpoint, root output, optional 32-byte `BatchAssetRoot` (Taproot Asset commitment sibling composed beside `SweepTapscriptRoot` in `BatchOutput` for asset trees), node hierarchy, and traversal helpers. `Verify` checks structure plus value flow; `ValidateValueConservation` exposes the funding check separately for callers that have already bound `BatchOutput` to an authoritative prevout. Built via `BuildVTXOTree` or `BuildConnectorTree`. - `Node` — Single tree node representing a transaction in the tree (branch or leaf). - `LeafDescriptor` — Describes a single VTXO leaf: amount, owner pubkeys, cosigner keys, CSV delay. - `VTXODescriptor` — Interface for VTXO metadata needed by tree construction (amount, cosigners, owner key). diff --git a/lib/tree/CLAUDE.md b/lib/tree/CLAUDE.md index fe362da0e..7766f1e52 100644 --- a/lib/tree/CLAUDE.md +++ b/lib/tree/CLAUDE.md @@ -8,7 +8,7 @@ descriptors through branch nodes to the batch output. ## Key Types -- `Tree` — Complete VTXO or connector tree: root outpoint, root output, node hierarchy, and traversal helpers. `Verify` checks structure plus value flow; `ValidateValueConservation` exposes the funding check separately for callers that have already bound `BatchOutput` to an authoritative prevout. Built via `BuildVTXOTree` or `BuildConnectorTree`. +- `Tree` — Complete VTXO or connector tree: root outpoint, root output, optional 32-byte `BatchAssetRoot` (Taproot Asset commitment sibling composed beside `SweepTapscriptRoot` in `BatchOutput` for asset trees), node hierarchy, and traversal helpers. `Verify` checks structure plus value flow; `ValidateValueConservation` exposes the funding check separately for callers that have already bound `BatchOutput` to an authoritative prevout. Built via `BuildVTXOTree` or `BuildConnectorTree`. - `Node` — Single tree node representing a transaction in the tree (branch or leaf). - `LeafDescriptor` — Describes a single VTXO leaf: amount, owner pubkeys, cosigner keys, CSV delay. - `VTXODescriptor` — Interface for VTXO metadata needed by tree construction (amount, cosigners, owner key). diff --git a/lib/tree/tree.go b/lib/tree/tree.go index db5d91c3c..ccee9e309 100644 --- a/lib/tree/tree.go +++ b/lib/tree/tree.go @@ -42,6 +42,11 @@ type Tree struct { // For connector trees, this is nil (no sweep script). SweepTapscriptRoot []byte + // BatchAssetRoot is the optional 32-byte Taproot Asset commitment leaf + // hash composed beside SweepTapscriptRoot in BatchOutput. Empty for + // Bitcoin-only trees. + BatchAssetRoot []byte + // SweepKey and SweepDelay retain the public operator policy needed to // prove the commitment's expiry offline. They are advisory until bound // to SweepTapscriptRoot and BatchOutput; zero values mean unavailable. @@ -142,6 +147,7 @@ func (t *Tree) ExtractPathForCoSigners(targetKeys ...*btcec.PublicKey) (*Tree, BatchOutpoint: t.BatchOutpoint, BatchOutput: t.BatchOutput, SweepTapscriptRoot: t.SweepTapscriptRoot, + BatchAssetRoot: bytes.Clone(t.BatchAssetRoot), SweepKey: t.SweepKey, SweepDelay: t.SweepDelay, AssetContext: t.AssetContext.cloneForRoot(extractedRoot), @@ -177,6 +183,7 @@ func (t *Tree) ExtractPathForIndices(leafIndices ...int) (*Tree, error) { BatchOutpoint: t.BatchOutpoint, BatchOutput: t.BatchOutput, SweepTapscriptRoot: t.SweepTapscriptRoot, + BatchAssetRoot: bytes.Clone(t.BatchAssetRoot), SweepKey: t.SweepKey, SweepDelay: t.SweepDelay, AssetContext: t.AssetContext.cloneForRoot(extractedRoot), diff --git a/lib/treecodec/AGENTS.md b/lib/treecodec/AGENTS.md index 80bf39881..157f52ad5 100644 --- a/lib/treecodec/AGENTS.md +++ b/lib/treecodec/AGENTS.md @@ -25,6 +25,9 @@ preserves its existing codec API through wrappers around this package. - Child serialization is deterministic. - The complete representation retains cached final signing keys. - Asset context is validated before encoding and after restoration. +- Optional `BatchAssetRoot` (TLV type 7) is emitted only when non-empty and + must be exactly 32 bytes when present, keeping Bitcoin-only tree blobs + byte-identical. ## Deep Docs diff --git a/lib/treecodec/CLAUDE.md b/lib/treecodec/CLAUDE.md index 80bf39881..157f52ad5 100644 --- a/lib/treecodec/CLAUDE.md +++ b/lib/treecodec/CLAUDE.md @@ -25,6 +25,9 @@ preserves its existing codec API through wrappers around this package. - Child serialization is deterministic. - The complete representation retains cached final signing keys. - Asset context is validated before encoding and after restoration. +- Optional `BatchAssetRoot` (TLV type 7) is emitted only when non-empty and + must be exactly 32 bytes when present, keeping Bitcoin-only tree blobs + byte-identical. ## Deep Docs diff --git a/lib/treecodec/codec.go b/lib/treecodec/codec.go index a0c244518..c1a8163e5 100644 --- a/lib/treecodec/codec.go +++ b/lib/treecodec/codec.go @@ -10,6 +10,7 @@ import ( "github.com/btcsuite/btcd/btcec/v2" "github.com/btcsuite/btcd/btcec/v2/schnorr" "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/chainhash/v2" "github.com/btcsuite/btcd/wire/v2" "github.com/lightninglabs/wavelength/baselib/tlvutil" "github.com/lightninglabs/wavelength/lib/tree" @@ -18,13 +19,14 @@ import ( // TLV type aliases for Tree serialization. type ( - tlvTreeBatchOutpoint = tlv.TlvType0 - tlvTreeBatchOutput = tlv.TlvType1 - tlvTreeSweepRoot = tlv.TlvType2 - tlvTreeRootNode = tlv.TlvType3 - tlvTreeAssetRef = tlv.TlvType4 - tlvTreeSweepKey = tlv.TlvType5 - tlvTreeSweepDelay = tlv.TlvType6 + tlvTreeBatchOutpoint = tlv.TlvType0 + tlvTreeBatchOutput = tlv.TlvType1 + tlvTreeSweepRoot = tlv.TlvType2 + tlvTreeRootNode = tlv.TlvType3 + tlvTreeAssetRef = tlv.TlvType4 + tlvTreeSweepKey = tlv.TlvType5 + tlvTreeSweepDelay = tlv.TlvType6 + tlvTreeBatchAssetRoot = tlv.TlvType7 ) // Tree-decode safety bounds. The wire layer feeds DeserializeTree from @@ -661,9 +663,10 @@ type tlvTree struct { RootNodeData tlv.RecordT[tlvTreeRootNode, tlv.Blob] // AssetRef identifies the asset carried by the tree. - AssetRef tlv.RecordT[tlvTreeAssetRef, tlv.Blob] - SweepKey tlv.RecordT[tlvTreeSweepKey, pubKeyRecord] - SweepDelay tlv.RecordT[tlvTreeSweepDelay, uint32] + AssetRef tlv.RecordT[tlvTreeAssetRef, tlv.Blob] + SweepKey tlv.RecordT[tlvTreeSweepKey, pubKeyRecord] + SweepDelay tlv.RecordT[tlvTreeSweepDelay, uint32] + BatchAssetRoot tlv.RecordT[tlvTreeBatchAssetRoot, tlv.Blob] } // newTlvTree creates a new tlvTree with initialized RecordT fields. @@ -688,6 +691,11 @@ func newTlvTree() *tlvTree { ]( nil, ), + BatchAssetRoot: tlv.NewPrimitiveRecord[ + tlvTreeBatchAssetRoot, tlv.Blob, + ]( + nil, + ), } } @@ -709,6 +717,9 @@ func (t *tlvTree) EncodeRecords() []tlv.Record { if t.SweepDelay.Val != 0 { records = append(records, t.SweepDelay.Record()) } + if len(t.BatchAssetRoot.Val) != 0 { + records = append(records, t.BatchAssetRoot.Record()) + } return records } @@ -723,6 +734,7 @@ func (t *tlvTree) DecodeRecords() []tlv.Record { t.AssetRef.Record(), t.SweepKey.Record(), t.SweepDelay.Record(), + t.BatchAssetRoot.Record(), } } @@ -968,6 +980,14 @@ func serializeTree(t *tree.Tree, includeFinalKey, includeSweepPolicy, // Set SweepRoot. tlvT.SweepRoot.Val = t.SweepTapscriptRoot + if len(t.BatchAssetRoot) > 0 { + if len(t.BatchAssetRoot) != chainhash.HashSize { + return nil, fmt.Errorf("batch asset root must be %d "+ + "bytes, got %d", chainhash.HashSize, + len(t.BatchAssetRoot)) + } + tlvT.BatchAssetRoot.Val = bytes.Clone(t.BatchAssetRoot) + } if t.AssetContext != nil { tlvT.AssetRef.Val = []byte(t.AssetContext.AssetRef()) } @@ -1015,9 +1035,17 @@ func deserializeTree(data []byte, snapshot bool) (*tree.Tree, error) { return nil, fmt.Errorf("decode tree: %w", err) } + if len(tlvT.BatchAssetRoot.Val) != 0 && + len(tlvT.BatchAssetRoot.Val) != chainhash.HashSize { + return nil, fmt.Errorf("batch asset root must be %d "+ + "bytes, got %d", chainhash.HashSize, + len(tlvT.BatchAssetRoot.Val)) + } + t := &tree.Tree{ BatchOutpoint: tlvT.BatchOutpoint.Val.OutPoint, SweepTapscriptRoot: tlvT.SweepRoot.Val, + BatchAssetRoot: bytes.Clone(tlvT.BatchAssetRoot.Val), SweepKey: tlvT.SweepKey.Val.Key, SweepDelay: tlvT.SweepDelay.Val, } diff --git a/tapassets/batch_anchor.go b/tapassets/batch_anchor.go index 43917a14c..4cb4754db 100644 --- a/tapassets/batch_anchor.go +++ b/tapassets/batch_anchor.go @@ -1129,9 +1129,10 @@ func batchRootSource(req *BatchAnchorRequest, outputs []commitOutput, TreeRootAssetSource, error) { root := TreeRootAssetSource{ - Inputs: make([]TreeRootAssetInput, 0, len(outputs)), - SigningTweak: append([]byte(nil), derived.SigningTweak...), - BatchPkScript: append([]byte(nil), derived.PkScript...), + Inputs: make([]TreeRootAssetInput, 0, len(outputs)), + SigningTweak: append([]byte(nil), derived.SigningTweak...), + BatchAssetRoot: append([]byte(nil), derived.AssetRoot[:]...), + BatchPkScript: append([]byte(nil), derived.PkScript...), } anchorOutpoint := wire.OutPoint{ Hash: finalTx.TxHash(), diff --git a/tapassets/tree_assembler.go b/tapassets/tree_assembler.go index 3f39e317a..02e32dfc4 100644 --- a/tapassets/tree_assembler.go +++ b/tapassets/tree_assembler.go @@ -173,6 +173,7 @@ func buildAssetTree(ctx context.Context, cfg TreeMaterializerConfig, BatchOutpoint: req.BatchOutpoint, BatchOutput: req.BatchOutput, SweepTapscriptRoot: sweepRoot[:], + BatchAssetRoot: bytes.Clone(cfg.Root.BatchAssetRoot), AssetContext: structure.AssetContext, } if err := built.Verify(); err != nil { diff --git a/tapassets/tree_materializer.go b/tapassets/tree_materializer.go index f663f0875..a6000aeec 100644 --- a/tapassets/tree_materializer.go +++ b/tapassets/tree_materializer.go @@ -65,6 +65,10 @@ type TreeRootAssetSource struct { // SigningTweak is the batch output's taproot tweak. SigningTweak []byte + // BatchAssetRoot is the optional 32-byte Taproot Asset commitment leaf + // hash composed beside the sweep leaf in BatchPkScript. + BatchAssetRoot []byte + // BatchPkScript is the batch output's P2TR script. BatchPkScript []byte } diff --git a/vtxo/authenticated_expiry.go b/vtxo/authenticated_expiry.go index b8bca54b6..baa432df6 100644 --- a/vtxo/authenticated_expiry.go +++ b/vtxo/authenticated_expiry.go @@ -255,9 +255,23 @@ func validateExpiryFragment(fragment Ancestry) error { ) } + rootTweak := fragment.TreePath.SweepTapscriptRoot + if len(fragment.TreePath.BatchAssetRoot) > 0 { + if len(fragment.TreePath.BatchAssetRoot) != chainhash.HashSize { + return invalidBatchExpiry( + "batch asset root must be %d bytes, got %d", + chainhash.HashSize, + len(fragment.TreePath.BatchAssetRoot), + ) + } + var assetRoot chainhash.Hash + copy(assetRoot[:], fragment.TreePath.BatchAssetRoot) + composedRoot := arkscript.TapBranchHash(sweepRoot, assetRoot) + rootTweak = composedRoot[:] + } + finalKey, err := tree.ComputeFinalKey( - fragment.TreePath.Root.CoSigners, - fragment.TreePath.SweepTapscriptRoot, + fragment.TreePath.Root.CoSigners, rootTweak, ) if err != nil { return invalidBatchExpiry("recompute tree root key: %v", err) diff --git a/vtxo/authenticated_expiry_test.go b/vtxo/authenticated_expiry_test.go index bd8ab0682..38d157e85 100644 --- a/vtxo/authenticated_expiry_test.go +++ b/vtxo/authenticated_expiry_test.go @@ -299,3 +299,126 @@ func testExpiryAncestry(t *testing.T, delay uint32, BlockHeight: height, } } + +// TestAuthenticateBatchExpiryAssetBatchOutput checks that an asset batch +// output composed from SweepTapscriptRoot and BatchAssetRoot authenticates +// its sweep policy and rejects tampered or malformed asset roots. +func TestAuthenticateBatchExpiryAssetBatchOutput(t *testing.T) { + t.Parallel() + + const ( + delay uint32 = 50 + height int32 = 100 + ) + + sweepKey, err := btcec.NewPrivateKey() + require.NoError(t, err) + sweepLeaf, err := arkscript.UnilateralCSVTimeoutTapLeaf( + sweepKey.PubKey(), delay, + ) + require.NoError(t, err) + sweepRoot := sweepLeaf.TapHash() + + var batchAssetRoot chainhash.Hash + copy(batchAssetRoot[:], []byte("batch-asset-root-32-bytes-012345")) + composedRoot := arkscript.TapBranchHash(sweepRoot, batchAssetRoot) + + ownerKey, err := btcec.NewPrivateKey() + require.NoError(t, err) + cosigners := []*btcec.PublicKey{ownerKey.PubKey()} + finalKey, err := tree.ComputeFinalKey(cosigners, composedRoot[:]) + require.NoError(t, err) + batchScript, err := txscript.PayToTaprootScript(finalKey) + require.NoError(t, err) + + tx := wire.NewMsgTx(2) + tx.AddTxIn(&wire.TxIn{ + PreviousOutPoint: wire.OutPoint{ + Hash: chainhash.Hash{0xaa}, + }, + }) + tx.AddTxOut(&wire.TxOut{ + Value: 2_000, + PkScript: batchScript, + }) + txid := tx.TxHash() + + fragment := Ancestry{ + TreePath: &tree.Tree{ + Root: &tree.Node{ + CoSigners: cosigners, + }, + BatchOutpoint: wire.OutPoint{ + Hash: txid, + }, + BatchOutput: tx.TxOut[0], + SweepTapscriptRoot: sweepRoot[:], + BatchAssetRoot: batchAssetRoot[:], + }, + CommitmentTxID: txid, + CommitmentHeight: height, + CommitmentSweepDelay: delay, + CommitmentSweepKey: sweepKey.PubKey(), + } + confirmation := CommitmentConfirmation{ + Tx: tx, + BlockHeight: height, + } + resolve := func(context.Context, chainhash.Hash, []byte, uint32) ( + CommitmentConfirmation, error) { + + return confirmation, nil + } + + evidence, err := AuthenticateBatchEvidence( + t.Context(), []Ancestry{fragment}, resolve, + ) + require.NoError(t, err) + require.Equal(t, height+int32(delay), evidence.BatchExpiry) + require.Equal(t, height, evidence.EarliestCommitmentHeight) + + t.Run("missing batch asset root fails", func(t *testing.T) { + bad := fragment + badTree := *fragment.TreePath + badTree.BatchAssetRoot = nil + bad.TreePath = &badTree + + _, err := AuthenticateBatchEvidence( + t.Context(), []Ancestry{bad}, resolve, + ) + require.ErrorIs(t, err, ErrInvalidBatchExpiryEvidence) + require.ErrorContains( + t, err, "batch output does not match tree root", + ) + }) + + t.Run("tampered batch asset root fails", func(t *testing.T) { + bad := fragment + badTree := *fragment.TreePath + badRoot := append([]byte(nil), batchAssetRoot[:]...) + badRoot[0] ^= 0xff + badTree.BatchAssetRoot = badRoot + bad.TreePath = &badTree + + _, err := AuthenticateBatchEvidence( + t.Context(), []Ancestry{bad}, resolve, + ) + require.ErrorIs(t, err, ErrInvalidBatchExpiryEvidence) + require.ErrorContains( + t, err, "batch output does not match tree root", + ) + }) + + t.Run("malformed batch asset root length fails", func(t *testing.T) { + bad := fragment + badTree := *fragment.TreePath + badTree.BatchAssetRoot = []byte{0x01, 0x02} + bad.TreePath = &badTree + + _, err := AuthenticateBatchEvidence( + t.Context(), []Ancestry{bad}, resolve, + ) + require.ErrorIs(t, err, ErrInvalidBatchExpiryEvidence) + require.ErrorContains(t, err, "batch asset root must be 32") + }) +} From 5feb4f93c7c3e9cc7898336df18012fd8ab3058d Mon Sep 17 00:00:00 2001 From: Dario Anongba Varela Date: Thu, 26 Nov 2026 23:52:38 +0100 Subject: [PATCH 04/15] lib/types: carry OOR carrier pubkey in operator terms Store the operator's advertised compressed OORCarrierPubKey on OperatorTerms so waved can verify leased carrier-float policies before building asset OOR transfers. --- lib/types/AGENTS.md | 2 ++ lib/types/CLAUDE.md | 2 ++ lib/types/boarding.go | 5 +++++ 3 files changed, 9 insertions(+) diff --git a/lib/types/AGENTS.md b/lib/types/AGENTS.md index f980d376f..5a3591605 100644 --- a/lib/types/AGENTS.md +++ b/lib/types/AGENTS.md @@ -44,6 +44,8 @@ server during round participation. These types are used across `round`, `vtxo`, cap on the cumulative on-chain vbytes a recipient must publish to claim a VTXO produced by an OOR submit unilaterally. Zero means no cap enforced server-side (clients fall back to a conservative local default). + `OORCarrierPubKey *btcec.PublicKey` is the optional compressed key that + controls the operator's leased OOR carrier float VTXOs. - `Ancestry` — One rooted commitment-tree fragment contributing ancestry to a VTXO (defined in `lib/types/ancestry.go`). Fields: `TreePath *tree.Tree` (extracted root-to-leaf path), `CommitmentTxID chainhash.Hash`, `InputIndices []uint32` (Ark tx input indices this fragment serves; empty for round-direct VTXOs), `TreeDepth uint32`. Round-direct VTXOs carry a single-element slice; multi-input OOR VTXOs carry one entry per distinct (commitment tx, tree path) pair — entries may share a commitment txid when inputs sat at different leaves of one commitment tree. - `MaxAncestryTreeDepth([]Ancestry) int` — Returns the largest `TreeDepth` across a slice; drives worst-case unilateral-exit timing calculations. - `ClientBatchInfo` — Client's view of batch output info after tree construction. diff --git a/lib/types/CLAUDE.md b/lib/types/CLAUDE.md index f980d376f..5a3591605 100644 --- a/lib/types/CLAUDE.md +++ b/lib/types/CLAUDE.md @@ -44,6 +44,8 @@ server during round participation. These types are used across `round`, `vtxo`, cap on the cumulative on-chain vbytes a recipient must publish to claim a VTXO produced by an OOR submit unilaterally. Zero means no cap enforced server-side (clients fall back to a conservative local default). + `OORCarrierPubKey *btcec.PublicKey` is the optional compressed key that + controls the operator's leased OOR carrier float VTXOs. - `Ancestry` — One rooted commitment-tree fragment contributing ancestry to a VTXO (defined in `lib/types/ancestry.go`). Fields: `TreePath *tree.Tree` (extracted root-to-leaf path), `CommitmentTxID chainhash.Hash`, `InputIndices []uint32` (Ark tx input indices this fragment serves; empty for round-direct VTXOs), `TreeDepth uint32`. Round-direct VTXOs carry a single-element slice; multi-input OOR VTXOs carry one entry per distinct (commitment tx, tree path) pair — entries may share a commitment txid when inputs sat at different leaves of one commitment tree. - `MaxAncestryTreeDepth([]Ancestry) int` — Returns the largest `TreeDepth` across a slice; drives worst-case unilateral-exit timing calculations. - `ClientBatchInfo` — Client's view of batch output info after tree construction. diff --git a/lib/types/boarding.go b/lib/types/boarding.go index 82404f9dc..43a39f145 100644 --- a/lib/types/boarding.go +++ b/lib/types/boarding.go @@ -101,6 +101,11 @@ type OperatorTerms struct { // AssetRefs are the Taproot Assets the operator admits into rounds, // in tap-sdk's asset reference format. Empty means none. AssetRefs []string + + // OORCarrierPubKey is the operator's carrier-float owner public key + // advertised in GetInfo for out-of-round Taproot Asset transfers. Nil + // means the operator does not advertise an OOR carrier float. + OORCarrierPubKey *btcec.PublicKey } // MinVTXOAmountFloor returns the effective minimum for a VTXO output. The From 60ce8452db8f9db2243c3065559e48bc4d09ae82 Mon Sep 17 00:00:00 2001 From: Dario Anongba Varela Date: Thu, 26 Nov 2026 23:52:38 +0100 Subject: [PATCH 05/15] multi: add asset VTXO selection and reservation for OOR spends Add SelectAndReserveAssetSpend (in lib/actormsg, vtxo, and wallet) to select and atomically lock up to eight live asset VTXOs of a requested asset reference in largest-first order, classifying locked-liquidity shortfalls separately from balance shortfalls. Add AllowAssetTransition on round.SpendReserveEvent so plain Bitcoin spends keep failing closed with ErrAssetVTXORequiresTransition while asset-aware OOR selection transitions live asset VTXOs into SpendingState. --- lib/actormsg/AGENTS.md | 4 + lib/actormsg/CLAUDE.md | 4 + lib/actormsg/vtxo_admission.go | 58 +++++++ round/AGENTS.md | 4 +- round/CLAUDE.md | 4 +- round/vtxo_messages.go | 5 + vtxo/AGENTS.md | 10 +- vtxo/CLAUDE.md | 10 +- vtxo/asset_safety_test.go | 33 ++++ vtxo/asset_selection.go | 275 ++++++++++++++++++++++++++++++++ vtxo/asset_selection_test.go | 122 ++++++++++++++ vtxo/manager.go | 3 + vtxo/messages.go | 11 ++ vtxo/transitions.go | 9 +- wallet/AGENTS.md | 4 + wallet/CLAUDE.md | 4 + wallet/messages.go | 64 ++++++++ wallet/wallet.go | 53 ++++++ wallet/wallet_admission_test.go | 78 +++++++++ 19 files changed, 741 insertions(+), 14 deletions(-) create mode 100644 vtxo/asset_selection.go create mode 100644 vtxo/asset_selection_test.go diff --git a/lib/actormsg/AGENTS.md b/lib/actormsg/AGENTS.md index 6aa77b35c..4c893d7aa 100644 --- a/lib/actormsg/AGENTS.md +++ b/lib/actormsg/AGENTS.md @@ -13,6 +13,10 @@ package boundaries. Lives in `lib/` to break import cycles between `vtxo`, - `VTXOManagerMsg` / `VTXOManagerResp` — Marker interfaces for VTXO manager messages and responses. - `VTXOActorMsg` / `VTXOActorResp` — Marker interfaces for per-VTXO actor messages and responses. - `SelectAndReserveSpendRequest` / `SelectAndReserveSpendResponse` — Ask-message to select and lock VTXOs for OOR spend. +- `SelectAndReserveAssetSpendRequest` / `SelectedAssetVTXO` / + `SelectAndReserveAssetSpendResponse` — Ask-message to atomically select and + reserve live asset VTXOs matching one canonical `AssetRef` (up to `MaxInputs`) + for an OOR asset spend, carrying `ReserveEpoch` for epoch-fenced release. - `SelectAndReserveForfeitRequest` / `SelectAndReserveForfeitResponse` — Ask-message to atomically select and reserve VTXOs for cooperative forfeit (directed sends). Combines coin selection and PendingForfeit reservation in one step to close a race window. - `ReserveForfeitRequest` / `ReleaseForfeitRequest` — Forfeit reservation admission messages. `ReleaseForfeitRequest.RoundID` identifies the round diff --git a/lib/actormsg/CLAUDE.md b/lib/actormsg/CLAUDE.md index 6aa77b35c..4c893d7aa 100644 --- a/lib/actormsg/CLAUDE.md +++ b/lib/actormsg/CLAUDE.md @@ -13,6 +13,10 @@ package boundaries. Lives in `lib/` to break import cycles between `vtxo`, - `VTXOManagerMsg` / `VTXOManagerResp` — Marker interfaces for VTXO manager messages and responses. - `VTXOActorMsg` / `VTXOActorResp` — Marker interfaces for per-VTXO actor messages and responses. - `SelectAndReserveSpendRequest` / `SelectAndReserveSpendResponse` — Ask-message to select and lock VTXOs for OOR spend. +- `SelectAndReserveAssetSpendRequest` / `SelectedAssetVTXO` / + `SelectAndReserveAssetSpendResponse` — Ask-message to atomically select and + reserve live asset VTXOs matching one canonical `AssetRef` (up to `MaxInputs`) + for an OOR asset spend, carrying `ReserveEpoch` for epoch-fenced release. - `SelectAndReserveForfeitRequest` / `SelectAndReserveForfeitResponse` — Ask-message to atomically select and reserve VTXOs for cooperative forfeit (directed sends). Combines coin selection and PendingForfeit reservation in one step to close a race window. - `ReserveForfeitRequest` / `ReleaseForfeitRequest` — Forfeit reservation admission messages. `ReleaseForfeitRequest.RoundID` identifies the round diff --git a/lib/actormsg/vtxo_admission.go b/lib/actormsg/vtxo_admission.go index b10df1cc7..a49f7b133 100644 --- a/lib/actormsg/vtxo_admission.go +++ b/lib/actormsg/vtxo_admission.go @@ -81,6 +81,64 @@ type SelectAndReserveSpendResponse struct { // VTXOManagerResp implements the VTXOManagerResp marker interface. func (r *SelectAndReserveSpendResponse) VTXOManagerResp() {} +// SelectAndReserveAssetSpendRequest asks the VTXO manager to select live +// Taproot Asset VTXOs of one asset reference covering a target unit amount +// (bounded by MaxInputs) and reserve them for an out-of-round asset transfer. +type SelectAndReserveAssetSpendRequest struct { + actor.BaseMessage + + // AssetRef is the canonical SDK asset reference to select. + AssetRef string + + // TargetAmount is the minimum asset units the selected VTXOs must + // cover. + TargetAmount uint64 + + // MaxInputs bounds how many asset VTXOs may be merged in one transfer. + MaxInputs int +} + +// VTXOManagerMsg implements VTXOManagerMsg marker interface. +func (m *SelectAndReserveAssetSpendRequest) VTXOManagerMsg() {} + +// MessageType returns the message type for logging. +func (m *SelectAndReserveAssetSpendRequest) MessageType() string { + return "SelectAndReserveAssetSpendRequest" +} + +// SelectedAssetVTXO describes one asset-bearing VTXO selected and reserved for +// an out-of-round asset transfer. +type SelectedAssetVTXO struct { + // Outpoint is the selected VTXO's outpoint. + Outpoint wire.OutPoint + + // ReserveEpoch is the manager's monotonic reservation epoch for this + // VTXO, echoed back so release refuses superseded reservations. + ReserveEpoch uint64 + + // Amount is the Bitcoin carrier value of this VTXO in satoshis. + Amount btcutil.Amount + + // AssetAmount is the Taproot Asset unit balance carried by this VTXO. + AssetAmount uint64 + + // PkScript is the composed taproot output script for this VTXO. + PkScript []byte +} + +// SelectAndReserveAssetSpendResponse returns the asset VTXOs selected and +// reserved for an out-of-round asset transfer. +type SelectAndReserveAssetSpendResponse struct { + // SelectedVTXOs is the set of asset VTXOs reserved for this spend. + SelectedVTXOs []SelectedAssetVTXO + + // TotalAssetSelected is the sum of asset units across SelectedVTXOs. + TotalAssetSelected uint64 +} + +// VTXOManagerResp implements the VTXOManagerResp marker interface. +func (r *SelectAndReserveAssetSpendResponse) VTXOManagerResp() {} + // ReleaseSpendRequest releases VTXOs previously reserved for an OOR spend // back to LiveState. Used when the OOR operation fails or is cancelled. type ReleaseSpendRequest struct { diff --git a/round/AGENTS.md b/round/AGENTS.md index d260abaf7..9c3dcbb3b 100644 --- a/round/AGENTS.md +++ b/round/AGENTS.md @@ -106,7 +106,9 @@ state transitions and validation rules live under [Invariants](#invariants). `SpendReleasedEvent`, `SpendCompletedEvent`, `ForfeitReleasedEvent`, `ForfeitSignedEvent`, `VTXOFailedEvent`, `ResumeVTXOEvent`, `PendingForfeitEvent`, `VTXOTerminatedMsg`. - `ForfeitReleasedEvent.RoundID` identifies the round releasing the VTXO. + `ForfeitReleasedEvent.RoundID` identifies the round releasing the VTXO; + `SpendReserveEvent.AllowAssetTransition` opts into reserving an asset VTXO + for an asset-aware OOR spend while keeping plain Bitcoin spends fail-closed. ### Misc diff --git a/round/CLAUDE.md b/round/CLAUDE.md index d260abaf7..9c3dcbb3b 100644 --- a/round/CLAUDE.md +++ b/round/CLAUDE.md @@ -106,7 +106,9 @@ state transitions and validation rules live under [Invariants](#invariants). `SpendReleasedEvent`, `SpendCompletedEvent`, `ForfeitReleasedEvent`, `ForfeitSignedEvent`, `VTXOFailedEvent`, `ResumeVTXOEvent`, `PendingForfeitEvent`, `VTXOTerminatedMsg`. - `ForfeitReleasedEvent.RoundID` identifies the round releasing the VTXO. + `ForfeitReleasedEvent.RoundID` identifies the round releasing the VTXO; + `SpendReserveEvent.AllowAssetTransition` opts into reserving an asset VTXO + for an asset-aware OOR spend while keeping plain Bitcoin spends fail-closed. ### Misc diff --git a/round/vtxo_messages.go b/round/vtxo_messages.go index 09236169c..5df4ba1ff 100644 --- a/round/vtxo_messages.go +++ b/round/vtxo_messages.go @@ -127,6 +127,11 @@ func (e *ForfeitConfirmedEvent) MessageType() string { // (SpendReleasedEvent). type SpendReserveEvent struct { actor.BaseMessage + + // AllowAssetTransition opts into reserving an asset-bearing VTXO for + // an asset-aware OOR transition. Plain Bitcoin spend paths leave this + // false so LiveState fails closed with ErrAssetVTXORequiresTransition. + AllowAssetTransition bool } // VTXOActorMsg implements actormsg.VTXOActorMsg marker interface. diff --git a/vtxo/AGENTS.md b/vtxo/AGENTS.md index ee1f9f2c3..c93f31b23 100644 --- a/vtxo/AGENTS.md +++ b/vtxo/AGENTS.md @@ -24,7 +24,7 @@ when the local wallet owns the receive script. verbatim once persisted). Use `EffectivePkScript`/`EffectivePolicyTemplate` to derive the current script/policy rather than reading `PkScript` directly, since custom policies decode through `PolicyTemplate`. -- `Manager` — Actor managing per-VTXO FSM instances, lifecycle, and admission gating. Configured via `ManagerConfig`. +- `Manager` — Actor managing per-VTXO FSM instances, lifecycle, and admission gating. Configured via `ManagerConfig`. Supports `SelectAndReserveAssetSpendRequest` (via `SelectAssetVTXOCandidates`, strictly isolating live asset VTXOs matching one canonical `AssetRef` with sealed packages, largest-first up to `MaxInputs`) alongside Bitcoin spend/forfeit selection. - `ManagerConfig` — Configuration holding Store, Wallet, ChainSource, ActorSystem, ChainParams, ExpiryConfig, RoundActor ref, ChainResolver ref, `TimeoutActor`, optional `Log`, optional `LedgerSink fn.Option[ledger.Sink]`, @@ -200,9 +200,11 @@ when the local wallet owns the receive script. - **New incoming expiry is authenticated before persistence.** The thin indexer event is only a wake-up hint. `AuthenticateBatchExpiry` reconstructs - the sweep leaf, recomputes the tree-root output script, byte-matches that - output in a locally confirmed commitment transaction, and derives the - earliest `confirmation height + sweep delay` across ancestry fragments. + the sweep leaf, recomputes the tree-root output script (combining + `SweepTapscriptRoot` with `BatchAssetRoot` via `arkscript.TapBranchHash` when + present on an asset tree), byte-matches that output in a locally confirmed + commitment transaction, and derives the earliest + `confirmation height + sweep delay` across ancestry fragments. `AuthenticateBatchEvidence` derives creation height from the earliest confirmation in the same lookups, replacing the indexer hint before persistence. Legacy persisted rows retain the expiry/creation consistency diff --git a/vtxo/CLAUDE.md b/vtxo/CLAUDE.md index ee1f9f2c3..c93f31b23 100644 --- a/vtxo/CLAUDE.md +++ b/vtxo/CLAUDE.md @@ -24,7 +24,7 @@ when the local wallet owns the receive script. verbatim once persisted). Use `EffectivePkScript`/`EffectivePolicyTemplate` to derive the current script/policy rather than reading `PkScript` directly, since custom policies decode through `PolicyTemplate`. -- `Manager` — Actor managing per-VTXO FSM instances, lifecycle, and admission gating. Configured via `ManagerConfig`. +- `Manager` — Actor managing per-VTXO FSM instances, lifecycle, and admission gating. Configured via `ManagerConfig`. Supports `SelectAndReserveAssetSpendRequest` (via `SelectAssetVTXOCandidates`, strictly isolating live asset VTXOs matching one canonical `AssetRef` with sealed packages, largest-first up to `MaxInputs`) alongside Bitcoin spend/forfeit selection. - `ManagerConfig` — Configuration holding Store, Wallet, ChainSource, ActorSystem, ChainParams, ExpiryConfig, RoundActor ref, ChainResolver ref, `TimeoutActor`, optional `Log`, optional `LedgerSink fn.Option[ledger.Sink]`, @@ -200,9 +200,11 @@ when the local wallet owns the receive script. - **New incoming expiry is authenticated before persistence.** The thin indexer event is only a wake-up hint. `AuthenticateBatchExpiry` reconstructs - the sweep leaf, recomputes the tree-root output script, byte-matches that - output in a locally confirmed commitment transaction, and derives the - earliest `confirmation height + sweep delay` across ancestry fragments. + the sweep leaf, recomputes the tree-root output script (combining + `SweepTapscriptRoot` with `BatchAssetRoot` via `arkscript.TapBranchHash` when + present on an asset tree), byte-matches that output in a locally confirmed + commitment transaction, and derives the earliest + `confirmation height + sweep delay` across ancestry fragments. `AuthenticateBatchEvidence` derives creation height from the earliest confirmation in the same lookups, replacing the indexer hint before persistence. Legacy persisted rows retain the expiry/creation consistency diff --git a/vtxo/asset_safety_test.go b/vtxo/asset_safety_test.go index b164d9f1d..f318ce714 100644 --- a/vtxo/asset_safety_test.go +++ b/vtxo/asset_safety_test.go @@ -119,6 +119,39 @@ func TestAssetCriticalExpiryBypassesBitcoinFeeAssessment(t *testing.T) { require.Same(t, event, a.preflightCriticalExit(h.ctx, event)) } +// TestAssetVTXOAllowsExplicitAssetSpendReserve verifies that an asset-aware +// OOR spend reservation transitions a live asset VTXO into SpendingState, and +// that the resulting SpendingState can complete or release normally. +func TestAssetVTXOAllowsExplicitAssetSpendReserve(t *testing.T) { + t.Parallel() + + h := newVTXOTestHarness(t) + desc := h.newTestDescriptor() + root := chainhash.Hash{1} + desc.TaprootAssetRoot = &root + h.withState(&LiveState{VTXO: desc}) + + _, err := h.sendEvent(&SpendReserveEvent{AllowAssetTransition: true}) + require.NoError(t, err) + assertState[*SpendingState](h) + require.Len(t, h.outboxMessages, 1) + statusUpdate, ok := h.outboxMessages[0].(*VTXOStatusUpdate) + require.True(t, ok) + require.Equal(t, VTXOStatusSpending, statusUpdate.NewStatus) + + _, err = h.sendEvent(&SpendReleasedEvent{}) + require.NoError(t, err) + assertState[*LiveState](h) + + _, err = h.sendEvent(&SpendReserveEvent{AllowAssetTransition: true}) + require.NoError(t, err) + assertState[*SpendingState](h) + + _, err = h.sendEvent(&SpendCompletedEvent{}) + require.NoError(t, err) + assertState[*SpentState](h) +} + // TestPendingAssetVTXORejectsForfeit protects recovered pending descriptors // even when their reservation predates the current process. func TestPendingAssetVTXORejectsForfeit(t *testing.T) { diff --git a/vtxo/asset_selection.go b/vtxo/asset_selection.go new file mode 100644 index 000000000..239bfbc11 --- /dev/null +++ b/vtxo/asset_selection.go @@ -0,0 +1,275 @@ +package vtxo + +import ( + "bytes" + "context" + "fmt" + "log/slog" + "math" + "slices" + + "github.com/btcsuite/btcd/wire/v2" + fn "github.com/lightningnetwork/lnd/fn/v2" +) + +// SelectAssetVTXOCandidates picks up to maxInputs live asset VTXOs for +// assetRef using largest-first ordering until targetAmount units are covered. +// Candidates without an asset root, sealed package, or matching canonical +// assetRef are ignored so plain Bitcoin VTXOs and foreign assets are never +// mixed. +func SelectAssetVTXOCandidates(candidates []*Descriptor, assetRef string, + targetAmount uint64, maxInputs int) ([]*Descriptor, uint64, error) { + + switch { + case assetRef == "": + return nil, 0, fmt.Errorf("asset ref must be provided") + + case targetAmount == 0: + return nil, 0, fmt.Errorf("target asset amount must be " + + "positive") + + case maxInputs <= 0: + return nil, 0, fmt.Errorf("max asset inputs must be positive") + } + + matching := make([]*Descriptor, 0, len(candidates)) + for _, desc := range candidates { + if !isSpendableAssetDescriptor(desc, assetRef) { + continue + } + + matching = append(matching, desc) + } + + // Sort largest asset balance first, breaking ties deterministically by + // outpoint so selection is reproducible across runs and platforms. + slices.SortFunc(matching, compareAssetSelectionOrder) + + selected := make([]*Descriptor, 0, min(len(matching), maxInputs)) + var selectedTotal uint64 + for _, desc := range matching { + if len(selected) >= maxInputs { + break + } + if desc.TaprootAssetAmount > math.MaxUint64-selectedTotal { + return nil, 0, fmt.Errorf("selected asset amount " + + "overflows uint64") + } + + selected = append(selected, desc) + selectedTotal += desc.TaprootAssetAmount + if selectedTotal >= targetAmount { + return selected, selectedTotal, nil + } + } + + // Distinguish a shortfall caused by the per-transfer merge cap from an + // absolute balance shortfall so callers get an actionable message. + var uncappedTotal uint64 + for _, desc := range matching { + if desc.TaprootAssetAmount > math.MaxUint64-uncappedTotal { + uncappedTotal = math.MaxUint64 + + break + } + uncappedTotal += desc.TaprootAssetAmount + } + if len(matching) > maxInputs && uncappedTotal >= targetAmount { + return nil, selectedTotal, fmt.Errorf("%w: top %d %s VTXOs "+ + "cover %d of %d units (total live %d across %d VTXOs)", + ErrInsufficientSpendableFunds, maxInputs, assetRef, + selectedTotal, targetAmount, uncappedTotal, + len(matching)) + } + + return nil, selectedTotal, fmt.Errorf("%w: need %d %s units, "+ + "spendable %d", ErrInsufficientSpendableFunds, targetAmount, + assetRef, selectedTotal) +} + +// isSpendableAssetDescriptor reports whether desc is a complete asset-bearing +// VTXO matching assetRef with a sealed asset package available for transition. +func isSpendableAssetDescriptor(desc *Descriptor, assetRef string) bool { + if desc == nil { + return false + } + + return desc.TaprootAssetRoot != nil && + desc.TaprootAssetRef == assetRef && + desc.TaprootAssetAmount > 0 && + len(desc.TaprootAssetSealedPackage) > 0 +} + +// compareAssetSelectionOrder orders candidates by descending asset units and +// ascending outpoint bytes for deterministic tie-breaking. +func compareAssetSelectionOrder(a, b *Descriptor) int { + if a.TaprootAssetAmount != b.TaprootAssetAmount { + if a.TaprootAssetAmount > b.TaprootAssetAmount { + return -1 + } + + return 1 + } + + if cmp := bytes.Compare( + a.Outpoint.Hash[:], b.Outpoint.Hash[:], + ); cmp != 0 { + return cmp + } + + switch { + case a.Outpoint.Index < b.Outpoint.Index: + return -1 + + case a.Outpoint.Index > b.Outpoint.Index: + return 1 + + default: + return 0 + } +} + +// handleSelectAndReserveAssetSpend selects live Taproot Asset VTXOs for one +// asset reference and reserves them for an out-of-round asset transfer via the +// shared detached spend-reservation lifecycle. +func (m *Manager) handleSelectAndReserveAssetSpend(ctx context.Context, + req *SelectAndReserveAssetSpendRequest) fn.Result[ManagerResp] { + + if req == nil { + return fn.Err[ManagerResp]( + fmt.Errorf("asset spend request must be provided"), + ) + } + + liveDescs, err := m.cfg.Store.ListVTXOsByStatus(ctx, VTXOStatusLive) + if err != nil { + return fn.Err[ManagerResp]( + fmt.Errorf("list live asset vtxos: %w", err), + ) + } + + candidates := make([]*Descriptor, 0, len(liveDescs)) + var inMemoryReserved uint64 + for _, desc := range liveDescs { + if !isSpendableAssetDescriptor(desc, req.AssetRef) { + continue + } + if m.isReserved(desc.Outpoint) { + inMemoryReserved = saturatingAddUint64( + inMemoryReserved, desc.TaprootAssetAmount, + ) + + continue + } + + candidates = append(candidates, desc) + } + + selected, totalAsset, err := SelectAssetVTXOCandidates( + candidates, req.AssetRef, req.TargetAmount, req.MaxInputs, + ) + if err != nil { + return fn.Err[ManagerResp]( + m.classifyAssetShortfall( + ctx, req.AssetRef, req.TargetAmount, totalAsset, + inMemoryReserved, err, + ), + ) + } + + var reserved []wire.OutPoint + epochs := make(map[wire.OutPoint]uint64, len(selected)) + for _, desc := range selected { + ref, ok := m.actors[desc.Outpoint] + if !ok { + lazyRef, err := m.respawnActorFromStore( + ctx, desc.Outpoint, + ) + if err != nil { + m.rollbackSpend(ctx, reserved) + + return fn.Err[ManagerResp]( + fmt.Errorf("no actor for asset "+ + "outpoint %s: %w", + desc.Outpoint, err), + ) + } + + ref = lazyRef + } + + epoch := m.markReserved(desc.Outpoint) + epochs[desc.Outpoint] = epoch + m.detachedReserve( + ctx, ref, desc.Outpoint, epoch, &SpendReserveEvent{ + AllowAssetTransition: true, + }, "asset-spend", + ) + reserved = append(reserved, desc.Outpoint) + } + + selectedOut := make([]SelectedAssetVTXO, 0, len(selected)) + for _, desc := range selected { + selectedOut = append(selectedOut, SelectedAssetVTXO{ + Outpoint: desc.Outpoint, + ReserveEpoch: epochs[desc.Outpoint], + Amount: desc.Amount, + AssetAmount: desc.TaprootAssetAmount, + PkScript: bytes.Clone(desc.PkScript), + }) + } + + m.logger(ctx).InfoS(ctx, "Reserved asset VTXOs for OOR spend", + slog.String("asset_ref", req.AssetRef), + slog.Int("count", len(selectedOut)), + slog.Uint64("total_asset", totalAsset), + slog.Uint64("target_asset", req.TargetAmount), + ) + + return fn.Ok[ManagerResp](&SelectAndReserveAssetSpendResponse{ + SelectedVTXOs: selectedOut, + TotalAssetSelected: totalAsset, + }) +} + +// classifyAssetShortfall distinguishes temporarily locked asset liquidity from +// an actual balance shortfall so callers can retry locked-liquidity errors. +func (m *Manager) classifyAssetShortfall(ctx context.Context, assetRef string, + targetAmount, liveSpendable, inMemoryReserved uint64, + selectErr error) error { + + nonTerminal, err := m.cfg.Store.ListLiveVTXOs(ctx) + if err != nil { + return selectErr + } + + locked := inMemoryReserved + for _, desc := range nonTerminal { + if !isSpendableAssetDescriptor(desc, assetRef) { + continue + } + if desc.Status == VTXOStatusLive { + continue + } + + locked = saturatingAddUint64(locked, desc.TaprootAssetAmount) + } + + if locked > 0 && + saturatingAddUint64(liveSpendable, locked) >= targetAmount { + return fmt.Errorf("%w: need %d %s units, spendable %d, "+ + "locked %d", ErrVTXOLiquidityLocked, targetAmount, + assetRef, liveSpendable, locked) + } + + return selectErr +} + +// saturatingAddUint64 adds a and b, clamping to math.MaxUint64 on overflow. +func saturatingAddUint64(a, b uint64) uint64 { + if a > math.MaxUint64-b { + return math.MaxUint64 + } + + return a + b +} diff --git a/vtxo/asset_selection_test.go b/vtxo/asset_selection_test.go new file mode 100644 index 000000000..38cb1cd96 --- /dev/null +++ b/vtxo/asset_selection_test.go @@ -0,0 +1,122 @@ +package vtxo + +import ( + "testing" + + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +// makeAssetDescriptor creates a live test asset VTXO descriptor for assetRef +// carrying assetUnits and carrierSat. +func makeAssetDescriptor(t *testing.T, assetRef string, assetUnits uint64, + carrierSat btcutil.Amount, idx uint32) *Descriptor { + + t.Helper() + + desc := makeDescriptor(t, carrierSat, idx) + root := chainhash.HashH([]byte{byte(idx + 1), byte(assetUnits)}) + desc.TaprootAssetRoot = &root + desc.TaprootAssetRef = assetRef + desc.TaprootAssetAmount = assetUnits + desc.TaprootAssetSealedPackage = []byte("sealed-pkg-" + assetRef) + + return desc +} + +// TestSelectAssetVTXOCandidates verifies largest-first merging, asset +// isolation (ignoring plain Bitcoin, other assets, and unpackaged VTXOs), and +// the max-inputs merge cap. +func TestSelectAssetVTXOCandidates(t *testing.T) { + t.Parallel() + + const assetA = "asset-a" + const assetB = "asset-b" + + btcOnly := makeDescriptor(t, 50_000, 1) + otherAsset := makeAssetDescriptor(t, assetB, 900, 1_000, 2) + noPkg := makeAssetDescriptor(t, assetA, 800, 1_000, 3) + noPkg.TaprootAssetSealedPackage = nil + + aSmall := makeAssetDescriptor(t, assetA, 100, 1_000, 4) + aMed := makeAssetDescriptor(t, assetA, 300, 1_000, 5) + aLarge := makeAssetDescriptor(t, assetA, 500, 1_000, 6) + + candidates := []*Descriptor{ + btcOnly, otherAsset, noPkg, aSmall, aMed, aLarge, + } + + selected, total, err := SelectAssetVTXOCandidates( + candidates, assetA, 750, 8, + ) + require.NoError(t, err) + require.EqualValues(t, 800, total) + require.Len(t, selected, 2) + require.Equal(t, aLarge.Outpoint, selected[0].Outpoint) + require.Equal(t, aMed.Outpoint, selected[1].Outpoint) + + // Enforcing maxInputs = 1 fails with ErrInsufficientSpendableFunds + // even though uncapped live balance exceeds the target. + _, _, err = SelectAssetVTXOCandidates(candidates, assetA, 750, 1) + require.ErrorIs(t, err, ErrInsufficientSpendableFunds) + require.ErrorContains(t, err, "top 1") + + // Requesting more than total live balance fails. + _, _, err = SelectAssetVTXOCandidates(candidates, assetA, 1_000, 8) + require.ErrorIs(t, err, ErrInsufficientSpendableFunds) +} + +// TestManagerSelectAndReserveAssetSpend verifies that the manager selects, +// merges, and reserves matching live asset VTXOs while isolating them from +// plain Bitcoin and other assets, and classifies reserved asset VTXOs as +// locked liquidity. +func TestManagerSelectAndReserveAssetSpend(t *testing.T) { + t.Parallel() + + const assetRef = "asset-usd" + + btc := makeDescriptor(t, 100_000, 0) + a1 := makeAssetDescriptor(t, assetRef, 400, 1_000, 1) + a2 := makeAssetDescriptor(t, assetRef, 300, 1_000, 2) + other := makeAssetDescriptor(t, "asset-eur", 900, 1_000, 3) + + all := []*Descriptor{btc, a1, a2, other} + mgr, store := newTestManager(t, all) + + store.On("ListVTXOsByStatus", mock.Anything, VTXOStatusLive). + Return(all, nil).Twice() + store.On("ListLiveVTXOs", mock.Anything).Return(all, nil).Once() + + res := mgr.handleSelectAndReserveAssetSpend( + t.Context(), &SelectAndReserveAssetSpendRequest{ + AssetRef: assetRef, + TargetAmount: 650, + MaxInputs: 8, + }, + ) + require.True(t, res.IsOk(), "unexpected error: %v", res.Err()) + + respVal, _ := res.Unpack() + resp, ok := respVal.(*SelectAndReserveAssetSpendResponse) + require.True(t, ok) + require.EqualValues(t, 700, resp.TotalAssetSelected) + require.Len(t, resp.SelectedVTXOs, 2) + require.Equal(t, a1.Outpoint, resp.SelectedVTXOs[0].Outpoint) + require.Equal(t, a2.Outpoint, resp.SelectedVTXOs[1].Outpoint) + require.NotZero(t, resp.SelectedVTXOs[0].ReserveEpoch) + require.NotZero(t, resp.SelectedVTXOs[1].ReserveEpoch) + + // A second selection while both asset VTXOs are reserved in memory + // classifies the shortfall as temporarily locked liquidity. + res2 := mgr.handleSelectAndReserveAssetSpend( + t.Context(), &SelectAndReserveAssetSpendRequest{ + AssetRef: assetRef, + TargetAmount: 100, + MaxInputs: 8, + }, + ) + require.True(t, res2.IsErr()) + require.ErrorIs(t, res2.Err(), ErrVTXOLiquidityLocked) +} diff --git a/vtxo/manager.go b/vtxo/manager.go index 03048beb9..532c7e961 100644 --- a/vtxo/manager.go +++ b/vtxo/manager.go @@ -716,6 +716,9 @@ func (m *Manager) Receive(ctx context.Context, case *SelectAndReserveSpendRequest: return m.handleSelectAndReserveSpend(ctx, req) + case *SelectAndReserveAssetSpendRequest: + return m.handleSelectAndReserveAssetSpend(ctx, req) + case *ReleaseSpendRequest: return m.handleReleaseSpend(ctx, req) diff --git a/vtxo/messages.go b/vtxo/messages.go index 865dc295c..77a4b8666 100644 --- a/vtxo/messages.go +++ b/vtxo/messages.go @@ -304,6 +304,17 @@ type SelectedVTXO = actormsg.SelectedVTXO // actormsg. type SelectAndReserveSpendResponse = actormsg.SelectAndReserveSpendResponse +// SelectAndReserveAssetSpendRequest is an alias for the canonical type in +// actormsg. +type SelectAndReserveAssetSpendRequest = actormsg.SelectAndReserveAssetSpendRequest //nolint:ll + +// SelectedAssetVTXO is an alias for the canonical type in actormsg. +type SelectedAssetVTXO = actormsg.SelectedAssetVTXO + +// SelectAndReserveAssetSpendResponse is an alias for the canonical type in +// actormsg. +type SelectAndReserveAssetSpendResponse = actormsg.SelectAndReserveAssetSpendResponse //nolint:ll + // ReleaseSpendRequest is an alias for the canonical type in actormsg. type ReleaseSpendRequest = actormsg.ReleaseSpendRequest diff --git a/vtxo/transitions.go b/vtxo/transitions.go index ae1dc7f0f..006165b8a 100644 --- a/vtxo/transitions.go +++ b/vtxo/transitions.go @@ -97,7 +97,7 @@ func (s *LiveState) ProcessEvent(ctx context.Context, event VTXOEvent, return s.handleCohortRefresh(evt, env) case *SpendReserveEvent: - return s.handleSpendReserve(ctx, env) + return s.handleSpendReserve(ctx, evt, env) case *PendingForfeitEvent: return s.handlePendingForfeit(ctx, env) @@ -226,10 +226,11 @@ func (s *LiveState) handlePendingForfeit(_ context.Context, // handleSpendReserve claims this VTXO for an out-of-round (OOR) spend. The // VTXO enters SpendingState and becomes unavailable for cooperative forfeit // until the spend completes or is released. -func (s *LiveState) handleSpendReserve(_ context.Context, _ *VTXOEnvironment) ( - *VTXOStateTransition, error) { +func (s *LiveState) handleSpendReserve(_ context.Context, + evt *SpendReserveEvent, _ *VTXOEnvironment) (*VTXOStateTransition, + error) { - if s.VTXO.TaprootAssetRoot != nil { + if s.VTXO.TaprootAssetRoot != nil && !evt.AllowAssetTransition { return nil, ErrAssetVTXORequiresTransition } diff --git a/wallet/AGENTS.md b/wallet/AGENTS.md index b1e69eea9..f6f44f08c 100644 --- a/wallet/AGENTS.md +++ b/wallet/AGENTS.md @@ -42,6 +42,10 @@ refresh, leave, OOR spend, and directed send flows. fees. `DropCustomRefreshVTXOsRequest` releases the temporary signer actors when round registration never starts. - `SelectAndLockVTXOsRequest` — Ask-request to select and lock VTXOs for OOR spend. `MinChangeAmount`, when positive, asks selection to avoid a non-zero residual below that amount (exact spends still valid). +- `SelectAndLockAssetVTXOsRequest` / `SelectedAssetVTXO` / + `SelectAndLockAssetVTXOsResponse` — Ask-request forwarding to the VTXO + manager's `SelectAndReserveAssetSpendRequest` to select and reserve live + asset VTXOs matching one canonical `AssetRef` for an OOR asset send. - `LeaveVTXOsRequest` — Ask-request to select VTXOs for cooperative leave. Carries a singular `DestOutput *wire.TxOut` plus a per-outpoint `DestOutputs map[wire.OutPoint]*wire.TxOut` override map; the handler picks `DestOutputs[op]` when set and falls back to `DestOutput`. Per-input operator fees are no longer pre-quoted on the client — under the #270 seal-time fee handshake the server stamps the residual onto the IsChange=true leave output at seal time, so the wallet ships the full forfeited amount on each leave output. - `CompleteSpendVTXOsRequest` — Tell-message to finalize spend and release locks. - `UnlockVTXOsRequest` — Tell-message to release locked VTXOs on failure. diff --git a/wallet/CLAUDE.md b/wallet/CLAUDE.md index b1e69eea9..f6f44f08c 100644 --- a/wallet/CLAUDE.md +++ b/wallet/CLAUDE.md @@ -42,6 +42,10 @@ refresh, leave, OOR spend, and directed send flows. fees. `DropCustomRefreshVTXOsRequest` releases the temporary signer actors when round registration never starts. - `SelectAndLockVTXOsRequest` — Ask-request to select and lock VTXOs for OOR spend. `MinChangeAmount`, when positive, asks selection to avoid a non-zero residual below that amount (exact spends still valid). +- `SelectAndLockAssetVTXOsRequest` / `SelectedAssetVTXO` / + `SelectAndLockAssetVTXOsResponse` — Ask-request forwarding to the VTXO + manager's `SelectAndReserveAssetSpendRequest` to select and reserve live + asset VTXOs matching one canonical `AssetRef` for an OOR asset send. - `LeaveVTXOsRequest` — Ask-request to select VTXOs for cooperative leave. Carries a singular `DestOutput *wire.TxOut` plus a per-outpoint `DestOutputs map[wire.OutPoint]*wire.TxOut` override map; the handler picks `DestOutputs[op]` when set and falls back to `DestOutput`. Per-input operator fees are no longer pre-quoted on the client — under the #270 seal-time fee handshake the server stamps the residual onto the IsChange=true leave output at seal time, so the wallet ships the full forfeited amount on each leave output. - `CompleteSpendVTXOsRequest` — Tell-message to finalize spend and release locks. - `UnlockVTXOsRequest` — Tell-message to release locked VTXOs on failure. diff --git a/wallet/messages.go b/wallet/messages.go index 2f6e10848..153ad0db6 100644 --- a/wallet/messages.go +++ b/wallet/messages.go @@ -639,6 +639,70 @@ func (m *SelectAndLockVTXOsResponse) MessageType() string { // walletRespSealed implements the sealed WalletResp interface. func (m *SelectAndLockVTXOsResponse) walletRespSealed() {} +// SelectAndLockAssetVTXOsRequest asks the wallet actor to select live Taproot +// Asset VTXOs of one asset reference covering a target unit amount and lock +// them for an out-of-round asset transfer. +type SelectAndLockAssetVTXOsRequest struct { + actor.BaseMessage + + // AssetRef is the canonical SDK asset reference to select. + AssetRef string + + // TargetAmount is the minimum asset units the selected VTXOs must + // cover. + TargetAmount uint64 + + // MaxInputs bounds how many asset VTXOs may be merged in one transfer. + MaxInputs int +} + +// MessageType returns the message type identifier for logging and debugging. +func (m *SelectAndLockAssetVTXOsRequest) MessageType() string { + return "SelectAndLockAssetVTXOsRequest" +} + +// walletMsgSealed implements the sealed WalletMsg interface. +func (m *SelectAndLockAssetVTXOsRequest) walletMsgSealed() {} + +// SelectedAssetVTXO describes an asset-bearing VTXO selected and locked for an +// out-of-round asset transfer. +type SelectedAssetVTXO struct { + // Outpoint is the selected VTXO's outpoint. + Outpoint wire.OutPoint + + // ReserveEpoch is the manager reservation epoch for this VTXO. + ReserveEpoch uint64 + + // Amount is the Bitcoin carrier value of this VTXO in satoshis. + Amount btcutil.Amount + + // AssetAmount is the Taproot Asset unit balance carried by this VTXO. + AssetAmount uint64 + + // PkScript is the composed taproot output script for this VTXO. + PkScript []byte +} + +// SelectAndLockAssetVTXOsResponse returns the asset VTXOs selected and locked +// for an out-of-round asset transfer. +type SelectAndLockAssetVTXOsResponse struct { + actor.BaseMessage + + // SelectedVTXOs is the set of asset VTXOs locked for this operation. + SelectedVTXOs []SelectedAssetVTXO + + // TotalAssetSelected is the sum of asset units across SelectedVTXOs. + TotalAssetSelected uint64 +} + +// MessageType returns the message type identifier for logging and debugging. +func (m *SelectAndLockAssetVTXOsResponse) MessageType() string { + return "SelectAndLockAssetVTXOsResponse" +} + +// walletRespSealed implements the sealed WalletResp interface. +func (m *SelectAndLockAssetVTXOsResponse) walletRespSealed() {} + // UnlockVTXOsRequest releases locks on VTXOs that were previously selected // via SelectAndLockVTXOsRequest. This is used when an OOR transfer fails // or is cancelled, allowing the VTXOs to be used in future operations. diff --git a/wallet/wallet.go b/wallet/wallet.go index 415c485e3..f78f360eb 100644 --- a/wallet/wallet.go +++ b/wallet/wallet.go @@ -905,6 +905,9 @@ func (a *Ark) Receive(ctx context.Context, case *SelectAndLockVTXOsRequest: return a.handleSelectAndLockVTXOs(ctx, m) + case *SelectAndLockAssetVTXOsRequest: + return a.handleSelectAndLockAssetVTXOs(ctx, m) + case *UnlockVTXOsRequest: return a.handleUnlockVTXOs(ctx, m) @@ -2849,6 +2852,56 @@ func (a *Ark) handleSelectAndLockVTXOs(ctx context.Context, }) } +// handleSelectAndLockAssetVTXOs forwards an asset spend selection request to +// the VTXO manager, which reserves the inputs in SpendingState. +func (a *Ark) handleSelectAndLockAssetVTXOs(ctx context.Context, + req *SelectAndLockAssetVTXOsRequest) fn.Result[WalletResp] { + + a.logger(ctx).TraceS(ctx, "Selecting and locking asset VTXOs for spend", + slog.String("asset_ref", req.AssetRef), + slog.Uint64("target_asset", req.TargetAmount), + slog.Int("max_inputs", req.MaxInputs), + ) + + resp, err := a.askManager( + ctx, &actormsg.SelectAndReserveAssetSpendRequest{ + AssetRef: req.AssetRef, + TargetAmount: req.TargetAmount, + MaxInputs: req.MaxInputs, + }, + ) + if err != nil { + return fn.Err[WalletResp]( + fmt.Errorf("select and reserve asset VTXOs: %w", err), + ) + } + + //nolint:forcetypeassert + mgrResp := resp.(*actormsg.SelectAndReserveAssetSpendResponse) + + selected := make([]SelectedAssetVTXO, len(mgrResp.SelectedVTXOs)) + for i, v := range mgrResp.SelectedVTXOs { + selected[i] = SelectedAssetVTXO{ + Outpoint: v.Outpoint, + ReserveEpoch: v.ReserveEpoch, + Amount: v.Amount, + AssetAmount: v.AssetAmount, + PkScript: v.PkScript, + } + } + + a.logger(ctx).InfoS(ctx, "Asset VTXOs selected and locked", + slog.String("asset_ref", req.AssetRef), + slog.Int("count", len(selected)), + slog.Uint64("total_asset", mgrResp.TotalAssetSelected), + ) + + return fn.Ok[WalletResp](&SelectAndLockAssetVTXOsResponse{ + SelectedVTXOs: selected, + TotalAssetSelected: mgrResp.TotalAssetSelected, + }) +} + // handleUnlockVTXOs forwards a spend release request to the VTXO manager. // This transitions VTXOs from SpendingState back to LiveState when an OOR // transfer fails or is cancelled. diff --git a/wallet/wallet_admission_test.go b/wallet/wallet_admission_test.go index 59f944dfe..c788ceb41 100644 --- a/wallet/wallet_admission_test.go +++ b/wallet/wallet_admission_test.go @@ -36,6 +36,17 @@ type mockVTXOManagerBehavior struct { // selectErr when set causes SelectAndReserveSpendRequest to fail. selectErr error + // selectAssetReq is the last SelectAndReserveAssetSpendRequest + // received. + selectAssetReq *actormsg.SelectAndReserveAssetSpendRequest + + // selectAssetResp is returned for SelectAndReserveAssetSpendRequest. + selectAssetResp *actormsg.SelectAndReserveAssetSpendResponse + + // selectAssetErr when set causes SelectAndReserveAssetSpendRequest to + // fail. + selectAssetErr error + // releaseResp is returned for ReleaseSpendRequest. releaseResp *actormsg.ReleaseSpendResponse @@ -114,6 +125,17 @@ func (m *mockVTXOManagerBehavior) Receive(_ context.Context, return fn.Ok[actormsg.VTXOManagerResp](m.selectResp) + case *actormsg.SelectAndReserveAssetSpendRequest: + m.selectAssetReq = msg + + if m.selectAssetErr != nil { + return fn.Err[actormsg.VTXOManagerResp]( + m.selectAssetErr, + ) + } + + return fn.Ok[actormsg.VTXOManagerResp](m.selectAssetResp) + case *actormsg.ReleaseSpendRequest: if m.releaseErr != nil { return fn.Err[actormsg.VTXOManagerResp]( @@ -315,6 +337,62 @@ func TestSelectAndLockVTXOsInsufficientFunds(t *testing.T) { require.ErrorContains(t, result.Err(), "insufficient funds") } +// TestSelectAndLockAssetVTXOs verifies that the wallet forwards asset VTXO +// selection to the manager and translates the selected asset descriptors. +func TestSelectAndLockAssetVTXOs(t *testing.T) { + t.Parallel() + + mgr := &mockVTXOManagerBehavior{ + selectAssetResp: &actormsg.SelectAndReserveAssetSpendResponse{ + SelectedVTXOs: []actormsg.SelectedAssetVTXO{ + { + Outpoint: testOutpoint(0), + ReserveEpoch: 7, + Amount: 1_000, + AssetAmount: 600, + PkScript: []byte{ + 0x51, + 0x20, + 0x01, + }, + }, + { + Outpoint: testOutpoint(1), + ReserveEpoch: 8, + Amount: 1_000, + AssetAmount: 400, + PkScript: []byte{ + 0x51, + 0x20, + 0x02, + }, + }, + }, + TotalAssetSelected: 1_000, + }, + } + w := newTestWalletWithManager(t, mgr) + + req := &SelectAndLockAssetVTXOsRequest{ + AssetRef: "asset-usd", + TargetAmount: 850, + MaxInputs: 8, + } + result := w.Receive(t.Context(), req) + require.True(t, result.IsOk(), "expected ok, got: %v", result.Err()) + + respVal, _ := result.Unpack() + resp, ok := respVal.(*SelectAndLockAssetVTXOsResponse) + require.True(t, ok) + require.EqualValues(t, 1_000, resp.TotalAssetSelected) + require.Len(t, resp.SelectedVTXOs, 2) + require.Equal(t, uint64(7), resp.SelectedVTXOs[0].ReserveEpoch) + require.Equal(t, uint64(600), resp.SelectedVTXOs[0].AssetAmount) + require.Equal(t, "asset-usd", mgr.selectAssetReq.AssetRef) + require.EqualValues(t, 850, mgr.selectAssetReq.TargetAmount) + require.Equal(t, 8, mgr.selectAssetReq.MaxInputs) +} + // TestUnlockVTXOs verifies that the wallet forwards a spend release request // to the VTXO manager and translates the response. func TestUnlockVTXOs(t *testing.T) { From af7f231bcbeaedc687808ca090e32714c9fdc3a9 Mon Sep 17 00:00:00 2001 From: Dario Anongba Varela Date: Thu, 26 Nov 2026 23:52:38 +0100 Subject: [PATCH 06/15] multi: support signer-script scopes for composed asset queries Allow ListVTXOsByScriptsTaproot and durable serverconn queries to carry an optional SignerScript alongside each queried PkScript so clients can prove script-scope ownership using the uncomposed base receive key when querying composed Taproot Asset output scripts. --- indexer/AGENTS.md | 4 ++ indexer/CLAUDE.md | 4 ++ indexer/client.go | 30 +++++++-- indexer/client_test.go | 86 ++++++++++++++++++++++++ serverconn/AGENTS.md | 10 ++- serverconn/CLAUDE.md | 10 ++- serverconn/actor_tlv_test.go | 67 +++++++++++++++++++ serverconn/durable_unary_queries.go | 100 ++++++++++++++++++++++++++-- serverconn/types.go | 14 ++++ 9 files changed, 314 insertions(+), 11 deletions(-) diff --git a/indexer/AGENTS.md b/indexer/AGENTS.md index 130ad7278..9b2624fa4 100644 --- a/indexer/AGENTS.md +++ b/indexer/AGENTS.md @@ -27,6 +27,10 @@ proofs for proof-of-control. `ListVTXOsByScripts`. `newPolicyScope` signs the script and canonical policy under the explicit `policy_script_scope` type. It creates no registration. Legacy `script_scope` proofs keep their original wire format. + `TaprootScriptScope.SignerScript` is a local-only script key lookup override + for composed asset outputs: the query and signed proof still cover the + composed `PkScript`, while the signer key is resolved via the uncomposed + `SignerScript`. - `BuildListVTXOsByScriptsTaprootRequest(ctx, scopes, afterCursor []byte, limit, statusFilter)` / `ListVTXOsByScriptsTaproot(ctx, scopes, afterCursor []byte, limit, statusFilter)` — Build and execute taproot-scope-proofed `ListVTXOsByScripts` queries. `afterCursor` is an opaque `[]byte` keyset cursor passed through unchanged. The proof covers each pkScript using owner-key signatures gated on script scope. - `BuildGetOORSessionByTxidTaprootRequest` / `GetOORSessionByTxidTaproot` — Build and execute a taproot-proofed OOR session lookup by Ark txid. - `BuildListOORRecipientEventsByScriptTaprootRequest` / `ListOORRecipientEventsByScriptTaproot` — Build and execute a taproot-proofed listing of OOR receive events for a given pkScript. diff --git a/indexer/CLAUDE.md b/indexer/CLAUDE.md index 130ad7278..9b2624fa4 100644 --- a/indexer/CLAUDE.md +++ b/indexer/CLAUDE.md @@ -27,6 +27,10 @@ proofs for proof-of-control. `ListVTXOsByScripts`. `newPolicyScope` signs the script and canonical policy under the explicit `policy_script_scope` type. It creates no registration. Legacy `script_scope` proofs keep their original wire format. + `TaprootScriptScope.SignerScript` is a local-only script key lookup override + for composed asset outputs: the query and signed proof still cover the + composed `PkScript`, while the signer key is resolved via the uncomposed + `SignerScript`. - `BuildListVTXOsByScriptsTaprootRequest(ctx, scopes, afterCursor []byte, limit, statusFilter)` / `ListVTXOsByScriptsTaproot(ctx, scopes, afterCursor []byte, limit, statusFilter)` — Build and execute taproot-scope-proofed `ListVTXOsByScripts` queries. `afterCursor` is an opaque `[]byte` keyset cursor passed through unchanged. The proof covers each pkScript using owner-key signatures gated on script scope. - `BuildGetOORSessionByTxidTaprootRequest` / `GetOORSessionByTxidTaproot` — Build and execute a taproot-proofed OOR session lookup by Ark txid. - `BuildListOORRecipientEventsByScriptTaprootRequest` / `ListOORRecipientEventsByScriptTaproot` — Build and execute a taproot-proofed listing of OOR receive events for a given pkScript. diff --git a/indexer/client.go b/indexer/client.go index 08fc3f878..b73a6228a 100644 --- a/indexer/client.go +++ b/indexer/client.go @@ -539,6 +539,14 @@ type TaprootScriptScope struct { // a valid pay-to-taproot script (OP_1 <32-byte key>). PkScript []byte + // SignerScript optionally identifies the local receive script used to + // look up the signing key for the scope proof when the queried + // PkScript differs from the registered receive script (for example, + // when a Taproot Asset root is composed into an Ark output script). + // When empty, PkScript is used for signer key lookup. This field is + // local-only and never transmitted on the wire. + SignerScript []byte + // PolicyTemplate optionally carries the canonical policy for a // registration-free funding query. The proof commits to this exact // policy and output; empty preserves the existing scoped proof. @@ -550,6 +558,14 @@ type TaprootScriptScope struct { func (c *Client) newTaprootScope(ctx context.Context, pkScript []byte, purpose string) (*arkrpc.ScriptScope, error) { + return c.newTaprootScopeWithSigner(ctx, pkScript, nil, purpose) +} + +// newTaprootScopeWithSigner builds a ScriptScope proto for pkScript while +// looking up the proof signing key using signerScript when non-empty. +func (c *Client) newTaprootScopeWithSigner(ctx context.Context, pkScript, + signerScript []byte, purpose string) (*arkrpc.ScriptScope, error) { + if err := validateTaprootPkScript(pkScript); err != nil { return nil, err } @@ -557,9 +573,14 @@ func (c *Client) newTaprootScope(ctx context.Context, pkScript []byte, return nil, fmt.Errorf("missing purpose") } + lookupScript := pkScript + if len(signerScript) > 0 { + lookupScript = signerScript + } + now := time.Now() expiresAt := now.Add(offlineReceiveProofTTL) - signerPubKey, err := proofSignerPubKey(pkScript, c.signer) + signerPubKey, err := proofSignerPubKey(lookupScript, c.signer) if err != nil { return nil, err } @@ -586,7 +607,7 @@ func (c *Client) newTaprootScope(ctx context.Context, pkScript []byte, } sig64, err := schnorrSigOverMessage( - ctx, msgBytes, pkScript, c.signer, + ctx, msgBytes, lookupScript, c.signer, ) if err != nil { return nil, err @@ -672,8 +693,9 @@ func (c *Client) buildTaprootScopes(ctx context.Context, if len(scope.PolicyTemplate) != 0 { ss, err = c.newPolicyScope(ctx, scope, purpose) } else { - ss, err = c.newTaprootScope( - ctx, scope.PkScript, purpose, + ss, err = c.newTaprootScopeWithSigner( + ctx, scope.PkScript, scope.SignerScript, + purpose, ) } if err != nil { diff --git a/indexer/client_test.go b/indexer/client_test.go index d30211c70..7755e33ec 100644 --- a/indexer/client_test.go +++ b/indexer/client_test.go @@ -596,3 +596,89 @@ func TestPolicyScopeCommitsTemplate(t *testing.T) { }, "list_vtxo_events") require.Error(t, err) } + +// scriptAwareSigner records which lookup script was requested and only signs +// when that lookup script matches expectedScript. +type scriptAwareSigner struct { + expectedScript []byte + key *btcec.PrivateKey + seenPubScripts [][]byte + seenSigScripts [][]byte +} + +func (s *scriptAwareSigner) ProofPubKey(pkScript []byte) (*btcec.PublicKey, + error) { + + s.seenPubScripts = append(s.seenPubScripts, bytes.Clone(pkScript)) + if !bytes.Equal(pkScript, s.expectedScript) { + return nil, context.DeadlineExceeded + } + + return s.key.PubKey(), nil +} + +func (s *scriptAwareSigner) SignSchnorr(pkScript []byte, hash [32]byte) ([]byte, + error) { + + s.seenSigScripts = append(s.seenSigScripts, bytes.Clone(pkScript)) + if !bytes.Equal(pkScript, s.expectedScript) { + return nil, context.DeadlineExceeded + } + + sig, err := schnorr.Sign(s.key, hash[:]) + if err != nil { + return nil, err + } + + return sig.Serialize(), nil +} + +// TestBuildListVTXOsByScriptsTaprootRequestSignerScript verifies that a +// TaprootScriptScope with SignerScript looks up and signs with the local +// SignerScript while keeping the queried PkScript on the wire scope. +func TestBuildListVTXOsByScriptsTaprootRequestSignerScript(t *testing.T) { + t.Parallel() + + key, err := btcec.NewPrivateKey() + require.NoError(t, err) + + uncomposed := make([]byte, 34) + uncomposed[0] = 0x51 + uncomposed[1] = 0x20 + uncomposed[2] = 0xaa + + composed := make([]byte, 34) + composed[0] = 0x51 + composed[1] = 0x20 + composed[2] = 0xbb + + signer := &scriptAwareSigner{ + expectedScript: uncomposed, + key: key, + } + client := New( + &recordingRPCClient{}, signer, "test-server", "client:test", + fn.None[btclog.Logger](), + ) + + req, err := client.BuildListVTXOsByScriptsTaprootRequest( + t.Context(), + []TaprootScriptScope{{ + PkScript: composed, + SignerScript: uncomposed, + }}, + nil, 10, nil, + ) + require.NoError(t, err) + require.Len(t, req.Scripts, 1) + require.Equal(t, composed, req.Scripts[0].PkScript) + require.Equal(t, [][]byte{uncomposed}, signer.seenPubScripts) + require.Equal(t, [][]byte{uncomposed}, signer.seenSigScripts) + + proof := req.Scripts[0].GetTaprootSchnorr() + require.NotNil(t, proof) + sig, err := schnorr.ParseSignature(proof.Sig64) + require.NoError(t, err) + digest := chainhash.TaggedHash(proofTag(), proof.Message) + require.True(t, sig.Verify(digest[:], key.PubKey())) +} diff --git a/serverconn/AGENTS.md b/serverconn/AGENTS.md index 97ba3c2a3..7efbd3059 100644 --- a/serverconn/AGENTS.md +++ b/serverconn/AGENTS.md @@ -56,7 +56,15 @@ background ingress polling with event routing. - `DurableUnaryRequestBuilder` — Interface for proof-gated request-body construction. Implementations build the actual proto request (e.g., with signed proofs) at send time, not at persist time. The interface is provided via `ConnectorConfig.DurableUnaryBuilder`. - `DurableUnaryQuery` — Interface implemented by transport-native durable query messages that persist raw query parameters (not a full proto). The `ServerConnectionActor` matches any `DurableUnaryQuery` generically in its `Receive` loop and calls `buildDurableUnary` to construct a `SendUnaryRequest` on the fly, using `BuildBody`, `QueryCorrelationID`, `QueryMsgID`, `QueryIdempotencyKey`, and `ServiceMethod`. - `SendListOORRecipientEventsByScriptRequest` — TLV-durable (type `2003`) indexer query message for phase-1 OOR receive resolution. Persists PkScript, AfterEventID, Limit, CorrelationID, MsgID, and IdempotencyKey; the proof-gated proto body is built at send time by `DurableUnaryRequestBuilder.BuildListOORRecipientEventsByScriptRequest`. -- `SendListVTXOsByScriptsRequest` — TLV-durable (type `2004`) indexer query message for phase-2 OOR metadata resolution. Persists PkScripts (count-prefixed, length-prefixed list), opaque AfterCursor, Limit, CorrelationID, MsgID, and IdempotencyKey; the proof-gated proto body is built by `DurableUnaryRequestBuilder.BuildListVTXOsByScriptsRequest`. +- `SendListVTXOsByScriptsRequest` — TLV-durable (type `2004`) indexer query + message for phase-2 OOR metadata resolution. Persists PkScripts + (count-prefixed, length-prefixed list), optional parallel `SignerScripts` + (odd TLV type `9`, for composed asset outputs whose signing key is registered + under the uncomposed receive script), opaque AfterCursor, Limit, + CorrelationID, MsgID, and IdempotencyKey; the proof-gated proto body is + built by `DurableUnaryRequestBuilder.BuildListVTXOsByScriptsRequest` (or + `ScopedVTXOQueryBuilder.BuildListVTXOsByScopedScriptsRequest` when + `SignerScripts` is present). - `CorrelationKey()` on `SendClientEventRequest` — Forwards the inner `ServerMessage`'s per-key FIFO key. Uses a structural assertion on the inner message in the pre-Encode path; falls back to a `cachedCorrelationKey` diff --git a/serverconn/CLAUDE.md b/serverconn/CLAUDE.md index 97ba3c2a3..7efbd3059 100644 --- a/serverconn/CLAUDE.md +++ b/serverconn/CLAUDE.md @@ -56,7 +56,15 @@ background ingress polling with event routing. - `DurableUnaryRequestBuilder` — Interface for proof-gated request-body construction. Implementations build the actual proto request (e.g., with signed proofs) at send time, not at persist time. The interface is provided via `ConnectorConfig.DurableUnaryBuilder`. - `DurableUnaryQuery` — Interface implemented by transport-native durable query messages that persist raw query parameters (not a full proto). The `ServerConnectionActor` matches any `DurableUnaryQuery` generically in its `Receive` loop and calls `buildDurableUnary` to construct a `SendUnaryRequest` on the fly, using `BuildBody`, `QueryCorrelationID`, `QueryMsgID`, `QueryIdempotencyKey`, and `ServiceMethod`. - `SendListOORRecipientEventsByScriptRequest` — TLV-durable (type `2003`) indexer query message for phase-1 OOR receive resolution. Persists PkScript, AfterEventID, Limit, CorrelationID, MsgID, and IdempotencyKey; the proof-gated proto body is built at send time by `DurableUnaryRequestBuilder.BuildListOORRecipientEventsByScriptRequest`. -- `SendListVTXOsByScriptsRequest` — TLV-durable (type `2004`) indexer query message for phase-2 OOR metadata resolution. Persists PkScripts (count-prefixed, length-prefixed list), opaque AfterCursor, Limit, CorrelationID, MsgID, and IdempotencyKey; the proof-gated proto body is built by `DurableUnaryRequestBuilder.BuildListVTXOsByScriptsRequest`. +- `SendListVTXOsByScriptsRequest` — TLV-durable (type `2004`) indexer query + message for phase-2 OOR metadata resolution. Persists PkScripts + (count-prefixed, length-prefixed list), optional parallel `SignerScripts` + (odd TLV type `9`, for composed asset outputs whose signing key is registered + under the uncomposed receive script), opaque AfterCursor, Limit, + CorrelationID, MsgID, and IdempotencyKey; the proof-gated proto body is + built by `DurableUnaryRequestBuilder.BuildListVTXOsByScriptsRequest` (or + `ScopedVTXOQueryBuilder.BuildListVTXOsByScopedScriptsRequest` when + `SignerScripts` is present). - `CorrelationKey()` on `SendClientEventRequest` — Forwards the inner `ServerMessage`'s per-key FIFO key. Uses a structural assertion on the inner message in the pre-Encode path; falls back to a `cachedCorrelationKey` diff --git a/serverconn/actor_tlv_test.go b/serverconn/actor_tlv_test.go index e38282475..b6f5cef84 100644 --- a/serverconn/actor_tlv_test.go +++ b/serverconn/actor_tlv_test.go @@ -268,6 +268,73 @@ func TestSendListVTXOsByScriptsRequest_TLVRoundTrip(t *testing.T) { require.NotEmpty(t, decoded.IdempotencyKey) } +// TestSendListVTXOsByScriptsRequestSignerScriptsTLVRoundTrip verifies that +// optional local SignerScripts round-trip through TLV encoding and that +// mismatched lengths are rejected. +func TestSendListVTXOsByScriptsRequestSignerScriptsTLVRoundTrip(t *testing.T) { + t.Parallel() + + original := &SendListVTXOsByScriptsRequest{ + PkScripts: [][]byte{ + { + 0x51, + 0x20, + 0x01, + }, + { + 0x51, + 0x20, + 0x02, + }, + }, + SignerScripts: [][]byte{ + {}, + { + 0x51, + 0x20, + 0x99, + }, + }, + Limit: 64, + CorrelationID: "corr-asset-vtxo-query", + } + + var decoded SendListVTXOsByScriptsRequest + encoded := encodeTLVMessage(t, original) + require.NoError(t, decoded.Decode(bytes.NewReader(encoded))) + require.Equal(t, original.PkScripts, decoded.PkScripts) + require.Equal(t, original.SignerScripts, decoded.SignerScripts) + + mismatch := &SendListVTXOsByScriptsRequest{ + PkScripts: [][]byte{ + { + 0x51, + 0x20, + 0x01, + }, + }, + SignerScripts: [][]byte{ + { + 0x51, + 0x20, + 0x99, + }, + { + 0x51, + 0x20, + 0x88, + }, + }, + Limit: 64, + CorrelationID: "corr-mismatch", + } + var buf bytes.Buffer + require.ErrorContains( + t, mismatch.Encode(&buf), + "does not match pk scripts count", + ) +} + // TestSendListVTXOsByScriptsRequest_EncodeRejectsOversizedCursor verifies the // durable query encoder refuses attacker-sized opaque cursors. func TestSendListVTXOsByScriptsRequest_EncodeRejectsOversizedCursor( diff --git a/serverconn/durable_unary_queries.go b/serverconn/durable_unary_queries.go index 4344c3958..d05f23415 100644 --- a/serverconn/durable_unary_queries.go +++ b/serverconn/durable_unary_queries.go @@ -13,6 +13,7 @@ import ( mailboxconn "github.com/lightninglabs/wavelength/mailbox/conn" mailboxrpc "github.com/lightninglabs/wavelength/mailbox/rpc" "github.com/lightningnetwork/lnd/tlv" + "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/anypb" ) @@ -43,6 +44,7 @@ type ( listVTXOsMsgIDRecordTLV = tlv.TlvType5 listVTXOsIdempotencyRecordTLV = tlv.TlvType6 listVTXOsAfterCursorRecordTLV = tlv.TlvType7 + listVTXOsSignerScriptsRecordTLV = tlv.TlvType9 ) // SendListOORRecipientEventsByScriptRequest describes a durable proof-gated @@ -246,6 +248,13 @@ type SendListVTXOsByScriptsRequest struct { // PkScripts are the taproot output scripts to query. PkScripts [][]byte + // SignerScripts optionally names, parallel to PkScripts, the local + // receive script used to look up the proof signing key for each query + // scope (for example, an uncomposed Ark policy script for a composed + // Taproot Asset output). Empty entries fall back to the corresponding + // PkScript. + SignerScripts [][]byte + // AfterCursor is the exclusive lower bound for the VTXO query cursor. AfterCursor []byte @@ -287,9 +296,34 @@ func (m *SendListVTXOsByScriptsRequest) ServiceMethod() mailboxrpc.ServiceMethod func (m *SendListVTXOsByScriptsRequest) BuildBody(ctx context.Context, builder DurableUnaryRequestBuilder) (*anypb.Any, []byte, error) { - protoReq, err := builder.BuildListVTXOsByScriptsRequest( - ctx, m.PkScripts, m.AfterCursor, m.Limit, + if len(m.SignerScripts) > 0 && + len(m.SignerScripts) != len(m.PkScripts) { + return nil, nil, fmt.Errorf("signer scripts count %d does not "+ + "match pk scripts count %d", len(m.SignerScripts), + len(m.PkScripts)) + } + + var ( + protoReq proto.Message + err error ) + if len(m.SignerScripts) > 0 { + scopedBuilder, ok := builder.(ScopedVTXOQueryBuilder) + if !ok { + return nil, nil, fmt.Errorf("durable unary builder " + + "does not support scoped signer scripts") + } + + protoReq, err = scopedBuilder. + BuildListVTXOsByScopedScriptsRequest( + ctx, m.PkScripts, m.SignerScripts, + m.AfterCursor, m.Limit, + ) + } else { + protoReq, err = builder.BuildListVTXOsByScriptsRequest( + ctx, m.PkScripts, m.AfterCursor, m.Limit, + ) + } if err != nil { return nil, nil, fmt.Errorf("build vtxo query: %w", err) } @@ -353,6 +387,13 @@ func (m *SendListVTXOsByScriptsRequest) Encode(w io.Writer) error { ) } + if len(m.SignerScripts) > 0 && + len(m.SignerScripts) != len(m.PkScripts) { + return fmt.Errorf("signer scripts count %d does not match pk "+ + "scripts count %d", len(m.SignerScripts), + len(m.PkScripts)) + } + pkScriptsRaw, err := encodeLengthPrefixedBlobList(m.PkScripts) if err != nil { return err @@ -380,11 +421,25 @@ func (m *SendListVTXOsByScriptsRequest) Encode(w io.Writer) error { ), ) - return tlvutil.EncodeRecords( - w, pkScriptsRec.Record(), limitRec.Record(), + records := []tlv.Record{ + pkScriptsRec.Record(), limitRec.Record(), correlationRec.Record(), msgIDRec.Record(), idempotencyRec.Record(), afterCursorRec.Record(), - ) + } + if len(m.SignerScripts) > 0 { + signerScriptsRaw, err := encodeLengthPrefixedBlobList( + m.SignerScripts, + ) + if err != nil { + return err + } + rec := tlv.NewPrimitiveRecord[listVTXOsSignerScriptsRecordTLV]( + signerScriptsRaw, + ) + records = append(records, rec.Record()) + } + + return tlvutil.EncodeRecords(w, records...) } // Decode deserializes the message from the provided reader. @@ -408,6 +463,10 @@ func (m *SendListVTXOsByScriptsRequest) Decode(r io.Reader) error { listVTXOsIdempotencyRecordTLV, []byte, ]() + signerScriptsRec := tlv.ZeroRecordT[ + listVTXOsSignerScriptsRecordTLV, + []byte, + ]() // Bound the untrusted payload before decode so a crafted record // length cannot drive an unbounded make() in the tlv library. @@ -420,6 +479,7 @@ func (m *SendListVTXOsByScriptsRequest) Decode(r io.Reader) error { safe, pkScriptsRec.Record(), legacyCursorRec.Record(), limitRec.Record(), correlationRec.Record(), msgIDRec.Record(), idempotencyRec.Record(), afterCursorRec.Record(), + signerScriptsRec.Record(), ) if err != nil { return err @@ -430,6 +490,22 @@ func (m *SendListVTXOsByScriptsRequest) Decode(r io.Reader) error { return err } + var signerScripts [][]byte + if _, ok := parsed[signerScriptsRec.TlvType()]; ok { + signerScripts, err = decodeLengthPrefixedBlobList( + signerScriptsRec.Val, + ) + if err != nil { + return err + } + if len(signerScripts) > 0 && + len(signerScripts) != len(pkScripts) { + return fmt.Errorf("signer scripts count %d does not "+ + "match pk scripts count %d", len(signerScripts), + len(pkScripts)) + } + } + if limitRec.Val > uint64(^uint32(0)) { return fmt.Errorf("vtxo query limit overflows uint32: %d", limitRec.Val) @@ -447,6 +523,7 @@ func (m *SendListVTXOsByScriptsRequest) Decode(r io.Reader) error { } m.PkScripts = pkScripts + m.SignerScripts = signerScripts m.AfterCursor = afterCursor m.Limit = uint32(limitRec.Val) m.CorrelationID = string(correlationRec.Val) @@ -580,6 +657,14 @@ func decodeLengthPrefixedBlobList(raw []byte) ([][]byte, error) { return nil, err } + // Each blob entry consumes at least a 4-byte length prefix, so any + // count larger than remaining/4 is malformed and must fail before + // allocating. + if uint64(count) > uint64(reader.Len()/4) { + return nil, fmt.Errorf("blob list count %d exceeds payload", + count) + } + blobs := make([][]byte, 0, count) for i := uint32(0); i < count; i++ { blob, err := readLengthPrefixedBlob(reader) @@ -616,6 +701,11 @@ func readLengthPrefixedBlob(r *bytes.Reader) ([]byte, error) { return nil, err } + if uint64(size) > uint64(r.Len()) { + return nil, fmt.Errorf("blob length %d exceeds remaining %d", + size, r.Len()) + } + blob := make([]byte, size) if _, err := io.ReadFull(r, blob); err != nil { return nil, err diff --git a/serverconn/types.go b/serverconn/types.go index 3a0f1b279..4cc0649b9 100644 --- a/serverconn/types.go +++ b/serverconn/types.go @@ -89,6 +89,20 @@ type DurableUnaryRequestBuilder interface { afterCursor []byte, limit uint32) (proto.Message, error) } +// ScopedVTXOQueryBuilder is an optional extension of +// DurableUnaryRequestBuilder for queries where one or more queried output +// pkScripts (such as Taproot Asset composed scripts) resolve their local +// ownership-proof signing key through a separate uncomposed receive script. +type ScopedVTXOQueryBuilder interface { + // BuildListVTXOsByScopedScriptsRequest builds the ListVTXOsByScripts + // unary request for pkScripts while resolving local proof signing keys + // through signerScripts (where an empty entry falls back to the + // corresponding pkScript). + BuildListVTXOsByScopedScriptsRequest(ctx context.Context, pkScripts, + signerScripts [][]byte, afterCursor []byte, + limit uint32) (proto.Message, error) +} + // DurableUnaryQuery is implemented by transport-native durable query messages // that persist raw query parameters and need a DurableUnaryRequestBuilder to // construct the proof-gated proto body at send time. Implementations are From bf313534c2b655f8f5fb4506258cac23ce10f7bc Mon Sep 17 00:00:00 2001 From: Dario Anongba Varela Date: Thu, 26 Nov 2026 23:52:38 +0100 Subject: [PATCH 07/15] tapassets: add OOR asset VTXO and input proof verifiers Add NewOORProofVerifier to check unconfirmed Taproot Asset proof anchors against a VTXO's authenticated commitment tree and OOR package chain, and add VerifyOORAssetVTXO on VTXOVerifier so incoming OOR asset receives verify sealed Ark asset packages (including merged multi-input packages) before persisting them for unilateral claims and respends. --- tapassets/AGENTS.md | 12 +- tapassets/CLAUDE.md | 12 +- tapassets/oor_verifier.go | 414 +++++++++++++++++++++++++++++++++ tapassets/oor_verifier_test.go | 244 +++++++++++++++++++ 4 files changed, 676 insertions(+), 6 deletions(-) create mode 100644 tapassets/oor_verifier.go create mode 100644 tapassets/oor_verifier_test.go diff --git a/tapassets/AGENTS.md b/tapassets/AGENTS.md index b29ef38ba..2a293c747 100644 --- a/tapassets/AGENTS.md +++ b/tapassets/AGENTS.md @@ -60,14 +60,20 @@ Durable journals retain committed packages for restart recovery. unchanged. The Ark package holds every new asset VTXO's proof, so `DecodeAssetVTXOClaimInputs` reads their pieces from it. - `TreeRootAssetSource` / `TreeRootAssetInput` — The asset states held by the - batch output that the tree's root node spends. `BatchAnchorCommit.RootSource` - feeds straight into `TreeMaterializerConfig.Root`. + batch output that the tree's root node spends, plus the optional 32-byte + `BatchAssetRoot` composed beside the sweep leaf in `BatchPkScript`. + `BatchAnchorCommit.RootSource` feeds straight into + `TreeMaterializerConfig.Root`. - `TreeLeafAnchor` / `StandardVTXOLeafAnchor` — Taproot material (uncomposed pkScript, internal key, canonical tap leaves) for a leaf VTXO output, before the asset root is composed in. - `VTXOVerifier` — Implements the round package's `AssetVTXOVerifier`. It checks the sealed package of a client's asset leaf and verifies the leaf's - proof path back to the confirmed deposits. + proof path back to the confirmed deposits. `VerifyOORAssetVTXO` verifies one + output of a sealed OOR Ark package (supporting multi-output Ark transactions + and merged multi-input `CoInputPaths`) using `NewOORProofVerifier`, which + restricts unconfirmed anchor steps to transactions present in the + authenticated commitment-tree lineage and OOR packages. - `ProofChainVerifier` / `TapdProofChainVerifier` — The asset backend seam: chain verification of one confirmed proof file. tapd rejects a grouped asset whose group it does not know, and answers a valid proof of an asset diff --git a/tapassets/CLAUDE.md b/tapassets/CLAUDE.md index b29ef38ba..2a293c747 100644 --- a/tapassets/CLAUDE.md +++ b/tapassets/CLAUDE.md @@ -60,14 +60,20 @@ Durable journals retain committed packages for restart recovery. unchanged. The Ark package holds every new asset VTXO's proof, so `DecodeAssetVTXOClaimInputs` reads their pieces from it. - `TreeRootAssetSource` / `TreeRootAssetInput` — The asset states held by the - batch output that the tree's root node spends. `BatchAnchorCommit.RootSource` - feeds straight into `TreeMaterializerConfig.Root`. + batch output that the tree's root node spends, plus the optional 32-byte + `BatchAssetRoot` composed beside the sweep leaf in `BatchPkScript`. + `BatchAnchorCommit.RootSource` feeds straight into + `TreeMaterializerConfig.Root`. - `TreeLeafAnchor` / `StandardVTXOLeafAnchor` — Taproot material (uncomposed pkScript, internal key, canonical tap leaves) for a leaf VTXO output, before the asset root is composed in. - `VTXOVerifier` — Implements the round package's `AssetVTXOVerifier`. It checks the sealed package of a client's asset leaf and verifies the leaf's - proof path back to the confirmed deposits. + proof path back to the confirmed deposits. `VerifyOORAssetVTXO` verifies one + output of a sealed OOR Ark package (supporting multi-output Ark transactions + and merged multi-input `CoInputPaths`) using `NewOORProofVerifier`, which + restricts unconfirmed anchor steps to transactions present in the + authenticated commitment-tree lineage and OOR packages. - `ProofChainVerifier` / `TapdProofChainVerifier` — The asset backend seam: chain verification of one confirmed proof file. tapd rejects a grouped asset whose group it does not know, and answers a valid proof of an asset diff --git a/tapassets/oor_verifier.go b/tapassets/oor_verifier.go new file mode 100644 index 000000000..4480048ff --- /dev/null +++ b/tapassets/oor_verifier.go @@ -0,0 +1,414 @@ +package tapassets + +import ( + "bytes" + "context" + "errors" + "fmt" + "math" + "sync" + + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/wire/v2" + tapsdk "github.com/lightninglabs/tap-sdk" + "github.com/lightninglabs/tap-sdk/customanchor" + "github.com/lightninglabs/wavelength/lib/tree" + "github.com/lightninglabs/wavelength/lib/tx/arktx" + "github.com/lightninglabs/wavelength/lib/tx/psbtutil" +) + +// OORLineageAnchor identifies one confirmed commitment transaction and its +// extracted commitment-tree path contributing lineage to an asset VTXO. +type OORLineageAnchor struct { + // CommitmentTxID is the txid of the confirmed commitment transaction. + CommitmentTxID chainhash.Hash + + // TreePath is the extracted commitment-tree fragment from the batch + // root down to the leaf VTXO served by this commitment. + TreePath *tree.Tree +} + +// OORPackageTxs holds the unsigned or finalized transactions of one OOR +// package hop (its Ark transaction and checkpoint transactions). +type OORPackageTxs struct { + // ArkTx is the Ark transaction of this OOR hop. + ArkTx *wire.MsgTx + + // CheckpointTxs are the checkpoint transactions spent by ArkTx. + CheckpointTxs []*wire.MsgTx +} + +// VerifyOORAssetVTXORequest carries the authenticated Bitcoin lineage, OOR +// package chain, and sealed Ark asset package for one incoming OOR asset +// output. +type VerifyOORAssetVTXORequest struct { + // AssetRef is the canonical SDK asset reference expected in Outpoint. + AssetRef string + + // AssetAmount is the expected total asset unit balance in Outpoint. + AssetAmount uint64 + + // AssetRoot is the expected 32-byte Taproot Asset root committed in + // Outpoint. + AssetRoot chainhash.Hash + + // Outpoint is the Ark transaction output being verified. + Outpoint wire.OutPoint + + // ArkTx is the Ark transaction that creates Outpoint. + ArkTx *wire.MsgTx + + // CheckpointTxs are the checkpoint transactions spent by ArkTx. + CheckpointTxs []*wire.MsgTx + + // AncestorPackages are prior finalized OOR packages leading into + // CheckpointTxs. + AncestorPackages []OORPackageTxs + + // Lineage holds every commitment-tree fragment anchoring this VTXO. + Lineage []OORLineageAnchor + + // SealedArkPackage is the sealed tap-sdk transition package for ArkTx. + SealedArkPackage []byte +} + +var ( + // ErrInvalidOORAssetPackage marks deterministic structural, binding, or + // cryptographic asset package rejections in VerifyOORAssetVTXO so + // callers can isolate terminal per-output rejections from retryable + // chain-backend proof verification failures. + ErrInvalidOORAssetPackage = errors.New("invalid OOR asset package") + + // errProofChainBackend wraps errors returned by ProofChainVerifier so + // VerifyOORAssetVTXO leaves backend/chain failures retryable even when + // outer proof-path verification wraps them. + errProofChainBackend = errors.New("proof chain verification backend") +) + +// oorProofVerifier verifies confirmed proofs via ProofChainVerifier and binds +// every unconfirmed transition step to the authenticated commitment-tree +// lineage and OOR package transactions of the VTXO. +type oorProofVerifier struct { + chain ProofChainVerifier + transactions map[chainhash.Hash]struct{} + anchors map[tapsdk.Outpoint]struct{} + + mu sync.Mutex + chainErr error +} + +// NewOORProofVerifier returns a customanchor.ConfirmedProofVerifier that checks +// confirmed base proofs via chain and restricts every unconfirmed step to the +// transactions and outputs present in lineage and packages. +func NewOORProofVerifier(chain ProofChainVerifier, lineage []OORLineageAnchor, + packages []OORPackageTxs) (customanchor.ConfirmedProofVerifier, error) { + + if chain == nil { + return nil, fmt.Errorf("proof chain verifier is required") + } + if len(lineage) == 0 && len(packages) == 0 { + return nil, fmt.Errorf("at least one lineage anchor or OOR " + + "package is required") + } + + v := &oorProofVerifier{ + chain: chain, + transactions: make(map[chainhash.Hash]struct{}), + anchors: make(map[tapsdk.Outpoint]struct{}), + } + + for idx, anc := range lineage { + if anc.CommitmentTxID == (chainhash.Hash{}) { + return nil, fmt.Errorf("lineage %d commitment txid is "+ + "required", idx) + } + if anc.TreePath == nil || anc.TreePath.Root == nil { + return nil, fmt.Errorf("lineage %d tree path is "+ + "required", idx) + } + + v.transactions[anc.CommitmentTxID] = struct{}{} + for node := range anc.TreePath.Root.NodesIter() { + tx, err := node.ToTx() + if err != nil { + return nil, fmt.Errorf("lineage %d tree tx: %w", + idx, err) + } + v.transactions[tx.TxHash()] = struct{}{} + v.anchors[sdkOutpoint(node.Input)] = struct{}{} + + if node.IsLeaf() { + leafOP, err := node.GetNonAnchorOutpoint() + if err != nil { + return nil, fmt.Errorf("lineage %d "+ + "leaf outpoint: %w", idx, err) + } + v.anchors[sdkOutpoint(*leafOP)] = struct{}{} + } + } + } + + for idx, pkg := range packages { + if pkg.ArkTx == nil { + return nil, fmt.Errorf("oor package %d ark tx is "+ + "required", idx) + } + arkTxID := pkg.ArkTx.TxHash() + v.transactions[arkTxID] = struct{}{} + for outIdx, out := range pkg.ArkTx.TxOut { + if arktx.IsAnchorOutput(out) { + continue + } + v.anchors[sdkOutpoint(wire.OutPoint{ + Hash: arkTxID, + Index: uint32(outIdx), + })] = struct{}{} + } + + for cpIdx, cpTx := range pkg.CheckpointTxs { + if cpTx == nil { + return nil, fmt.Errorf("oor package %d "+ + "checkpoint %d is nil", idx, cpIdx) + } + cpTxID := cpTx.TxHash() + v.transactions[cpTxID] = struct{}{} + v.anchors[sdkOutpoint(wire.OutPoint{ + Hash: cpTxID, + Index: 0, + })] = struct{}{} + } + } + + return v, nil +} + +// VerifyConfirmedProof checks the confirmed deposit proof chain and derives its +// confirmed anchor inventory. +func (v *oorProofVerifier) VerifyConfirmedProof(ctx context.Context, + proofFile []byte) (*customanchor.ConfirmedProofVerification, error) { + + if err := v.chain.VerifyProofChain(ctx, proofFile); err != nil { + wrapped := fmt.Errorf("%w: %w", errProofChainBackend, err) + v.mu.Lock() + v.chainErr = wrapped + v.mu.Unlock() + + return nil, wrapped + } + + return customanchor.DeriveConfirmedProofInventory(proofFile) +} + +// takeChainErr returns and clears the most recent ProofChainVerifier error +// observed on this verifier. +func (v *oorProofVerifier) takeChainErr() error { + v.mu.Lock() + defer v.mu.Unlock() + + err := v.chainErr + v.chainErr = nil + + return err +} + +// VerifyUnconfirmedAnchor ensures every unconfirmed step anchors its asset in a +// transaction and output authenticated by the VTXO's lineage or OOR package +// chain. +func (v *oorProofVerifier) VerifyUnconfirmedAnchor(_ context.Context, + transition customanchor.UnconfirmedAnchorVerification) error { + + var tx wire.MsgTx + err := tx.Deserialize(bytes.NewReader(transition.AnchorTransaction)) + if err != nil { + return fmt.Errorf("decode step %d transaction: %w", + transition.StepIndex, err) + } + + txid := tx.TxHash() + if _, ok := v.transactions[txid]; !ok { + return fmt.Errorf("step %d transaction %v is not in the "+ + "VTXO lineage", transition.StepIndex, txid) + } + if chainhash.Hash(transition.AnchorOutpoint.Txid) != txid { + return fmt.Errorf("step %d anchor is not in its transaction", + transition.StepIndex) + } + if _, ok := v.anchors[transition.AnchorOutpoint]; !ok { + return fmt.Errorf("step %d anchor %v is not on the VTXO path", + transition.StepIndex, transition.AnchorOutpoint) + } + + return nil +} + +// VerifyOORAssetVTXO verifies that SealedArkPackage seals req.ArkTx and moves +// exactly req.AssetAmount units of req.AssetRef into req.Outpoint under +// OP_TRUE script keys committing to req.AssetRoot, with every piece's proof +// path (including merged co-input paths) verified back to confirmed issuance +// through req.Lineage and the OOR package chain. +func (v *VTXOVerifier) VerifyOORAssetVTXO(ctx context.Context, + req VerifyOORAssetVTXORequest) error { + + switch { + case v == nil || v.chain == nil: + return fmt.Errorf("proof chain verifier is required") + + case req.ArkTx == nil: + return fmt.Errorf("%w: ark transaction is required", + ErrInvalidOORAssetPackage) + + case req.Outpoint.Hash != req.ArkTx.TxHash(): + return fmt.Errorf("%w: outpoint %v does not match ark tx %v", + ErrInvalidOORAssetPackage, req.Outpoint, + req.ArkTx.TxHash()) + + case int(req.Outpoint.Index) >= len(req.ArkTx.TxOut): + return fmt.Errorf("%w: outpoint index %d out of bounds "+ + "for ark tx", ErrInvalidOORAssetPackage, + req.Outpoint.Index) + + case req.AssetAmount == 0: + return fmt.Errorf("%w: asset amount must be positive", + ErrInvalidOORAssetPackage) + + case req.AssetRoot == (chainhash.Hash{}): + return fmt.Errorf("%w: asset root must be non-zero", + ErrInvalidOORAssetPackage) + + case len(req.SealedArkPackage) == 0: + return fmt.Errorf("%w: sealed ark asset package is required", + ErrInvalidOORAssetPackage) + } + + ref, err := tapsdk.ParseAssetRef(req.AssetRef) + if err != nil { + return fmt.Errorf("%w: asset VTXO reference: %w", + ErrInvalidOORAssetPackage, err) + } + + committed, err := decodeSealedPackage(req.SealedArkPackage) + if err != nil { + return fmt.Errorf("%w: %w", ErrInvalidOORAssetPackage, err) + } + + anchor, err := psbtutil.Parse(committed.anchorPSBT) + if err != nil { + return fmt.Errorf("%w: decode sealed ark transaction: %w", + ErrInvalidOORAssetPackage, err) + } + if anchor.UnsignedTx.TxHash() != req.ArkTx.TxHash() { + return fmt.Errorf("%w: sealed package does not seal ark tx %v", + ErrInvalidOORAssetPackage, req.ArkTx.TxHash()) + } + + targetOutpoint := sdkOutpoint(req.Outpoint) + expectedRoot := tapsdk.Hash(req.AssetRoot) + + var ( + matchingOutputs []*commitOutput + total uint64 + ) + for idx := range committed.outputs { + output := &committed.outputs[idx] + if output.anchorOutpoint != targetOutpoint { + continue + } + + switch { + case !output.assetRef.Equivalent(ref): + return fmt.Errorf("%w: asset output %d holds "+ + "%s, want %s", ErrInvalidOORAssetPackage, idx, + output.assetRef, ref) + + case output.scriptMode != customanchor.AssetScriptOPTrue || + len(output.opTrueWitness) == 0: + return fmt.Errorf("%w: asset output %d is not "+ + "OP_TRUE locked", ErrInvalidOORAssetPackage, + idx) + + case output.taprootAssetRoot != expectedRoot: + return fmt.Errorf("%w: asset output %d does not "+ + "commit to the expected asset root", + ErrInvalidOORAssetPackage, idx) + + case output.amount > math.MaxUint64-total: + return fmt.Errorf("%w: asset output amount overflow", + ErrInvalidOORAssetPackage) + } + + total += output.amount + matchingOutputs = append(matchingOutputs, output) + } + + if len(matchingOutputs) == 0 { + return fmt.Errorf("%w: sealed ark package holds no asset in %v", + ErrInvalidOORAssetPackage, req.Outpoint) + } + if total != req.AssetAmount { + return fmt.Errorf("%w: sealed ark package holds %d units in "+ + "%v, want %d", ErrInvalidOORAssetPackage, total, + req.Outpoint, req.AssetAmount) + } + + packages := make([]OORPackageTxs, 0, len(req.AncestorPackages)+1) + packages = append(packages, req.AncestorPackages...) + packages = append(packages, OORPackageTxs{ + ArkTx: req.ArkTx, + CheckpointTxs: req.CheckpointTxs, + }) + + proofVerifierIface, err := NewOORProofVerifier( + v.chain, req.Lineage, packages, + ) + if err != nil { + return fmt.Errorf("%w: %w", ErrInvalidOORAssetPackage, err) + } + proofVerifier, _ := proofVerifierIface.(*oorProofVerifier) + + for idx, output := range matchingOutputs { + claimInput, err := claimInputFromOutput(committed, output) + if err != nil { + return fmt.Errorf("%w: asset output %d claim input: %w", + ErrInvalidOORAssetPackage, idx, err) + } + if err := claimInput.ProofPath.Validate(); err != nil { + return fmt.Errorf("%w: asset output %d proof path: %w", + ErrInvalidOORAssetPackage, idx, err) + } + + if proofVerifier != nil { + _ = proofVerifier.takeChainErr() + } + + summary, err := claimInput.ProofPath.Verify( + ctx, proofVerifierIface, + ) + if err != nil { + var chainErr error + if proofVerifier != nil { + chainErr = proofVerifier.takeChainErr() + } + if ctx.Err() != nil || + errors.Is(err, errProofChainBackend) || + chainErr != nil { + return fmt.Errorf("verify asset output %d "+ + "proof path: %w", idx, err) + } + + return fmt.Errorf("%w: verify asset output %d proof "+ + "path: %w", ErrInvalidOORAssetPackage, idx, err) + } + if err := checkProvenOutput(summary, output, ref); err != nil { + return fmt.Errorf("%w: asset output %d proven "+ + "output: %w", ErrInvalidOORAssetPackage, idx, + err) + } + } + + return nil +} + +var ( + _ customanchor.ConfirmedProofVerifier = (*oorProofVerifier)(nil) + _ customanchor.UnconfirmedAnchorVerifier = (*oorProofVerifier)(nil) +) diff --git a/tapassets/oor_verifier_test.go b/tapassets/oor_verifier_test.go new file mode 100644 index 000000000..2c127c0a3 --- /dev/null +++ b/tapassets/oor_verifier_test.go @@ -0,0 +1,244 @@ +package tapassets + +import ( + "bytes" + "context" + "fmt" + "testing" + + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/wire/v2" + tapsdk "github.com/lightninglabs/tap-sdk" + "github.com/lightninglabs/tap-sdk/customanchor" + "github.com/stretchr/testify/require" +) + +type acceptAllProofChainVerifier struct{} + +func (acceptAllProofChainVerifier) VerifyProofChain(_ context.Context, + _ []byte) error { + + return nil +} + +// TestNewOORProofVerifierAllowsLineageAndPackages verifies that the OOR proof +// verifier accepts commitment, tree, checkpoint, and Ark anchor transactions +// from the supplied lineage and OOR packages while rejecting unknown +// transactions and unknown anchor outputs. +func TestNewOORProofVerifierAllowsLineageAndPackages(t *testing.T) { + t.Parallel() + + f := newAssetVTXOFixture(t) + + cpTx := wire.NewMsgTx(3) + cpTx.AddTxIn(wire.NewTxIn(&f.leafOutpoint, nil, nil)) + cpTx.AddTxOut(wire.NewTxOut(1_000, []byte{0x51, 0x20, 0x01})) + + cpOP := wire.OutPoint{Hash: cpTx.TxHash(), Index: 0} + arkTx := wire.NewMsgTx(3) + arkTx.AddTxIn(wire.NewTxIn(&cpOP, nil, nil)) + arkTx.AddTxOut(wire.NewTxOut(1_000, []byte{0x51, 0x20, 0x02})) + + verifier, err := NewOORProofVerifier( + acceptAllProofChainVerifier{}, + []OORLineageAnchor{{ + CommitmentTxID: f.commitmentTx.TxHash(), + TreePath: f.path, + }}, + []OORPackageTxs{{ + ArkTx: arkTx, + CheckpointTxs: []*wire.MsgTx{cpTx}, + }}, + ) + require.NoError(t, err) + unconfVerifier, ok := verifier.(customanchor.UnconfirmedAnchorVerifier) + require.True(t, ok) + + serializeTx := func(tx *wire.MsgTx) []byte { + var buf bytes.Buffer + require.NoError(t, tx.Serialize(&buf)) + + return buf.Bytes() + } + + // Commitment batch output, leaf output, checkpoint output, and Ark + // output are all accepted. + rootAnchor := customanchor.UnconfirmedAnchorVerification{ + StepIndex: 0, + AnchorTransaction: serializeTx(f.commitmentTx), + AnchorOutpoint: sdkOutpoint(f.path.Root.Input), + } + require.NoError( + t, + unconfVerifier.VerifyUnconfirmedAnchor( + t.Context(), rootAnchor, + ), + ) + require.NoError( + t, + unconfVerifier.VerifyUnconfirmedAnchor( + t.Context(), + customanchor.UnconfirmedAnchorVerification{ + StepIndex: 1, + AnchorTransaction: serializeTx(cpTx), + AnchorOutpoint: sdkOutpoint(cpOP), + }, + ), + ) + require.NoError( + t, + unconfVerifier.VerifyUnconfirmedAnchor( + t.Context(), + customanchor.UnconfirmedAnchorVerification{ + StepIndex: 2, + AnchorTransaction: serializeTx(arkTx), + AnchorOutpoint: sdkOutpoint(wire.OutPoint{ + Hash: arkTx.TxHash(), + Index: 0, + }), + }, + ), + ) + + // An unknown transaction is rejected. + rogueTx := wire.NewMsgTx(3) + rogueTx.AddTxIn( + wire.NewTxIn( + &wire.OutPoint{ + Hash: chainhash.Hash{0x99}, + }, + nil, + nil, + ), + ) + rogueTx.AddTxOut(wire.NewTxOut(1_000, []byte{0x51, 0x20, 0x09})) + require.ErrorContains( + t, + unconfVerifier.VerifyUnconfirmedAnchor( + t.Context(), + customanchor.UnconfirmedAnchorVerification{ + StepIndex: 2, + AnchorTransaction: serializeTx(rogueTx), + AnchorOutpoint: sdkOutpoint(wire.OutPoint{ + Hash: rogueTx.TxHash(), + Index: 0, + }), + }, + ), + "not in the VTXO lineage", + ) + + // A mismatched outpoint index on an allowed transaction is rejected. + require.ErrorContains( + t, + unconfVerifier.VerifyUnconfirmedAnchor( + t.Context(), + customanchor.UnconfirmedAnchorVerification{ + StepIndex: 2, + AnchorTransaction: serializeTx(arkTx), + AnchorOutpoint: sdkOutpoint(wire.OutPoint{ + Hash: arkTx.TxHash(), + Index: 7, + }), + }, + ), + "not on the VTXO path", + ) +} + +// TestVerifyOORAssetVTXORejectsInvalidInputs checks fail-closed validation on +// VerifyOORAssetVTXO before proof verification. +func TestVerifyOORAssetVTXORejectsInvalidInputs(t *testing.T) { + t.Parallel() + + v, err := NewVTXOVerifier(acceptAllProofChainVerifier{}) + require.NoError(t, err) + + arkTx := wire.NewMsgTx(3) + arkTx.AddTxOut(wire.NewTxOut(1_000, []byte{0x51, 0x20, 0x02})) + arkOP := wire.OutPoint{Hash: arkTx.TxHash(), Index: 0} + root := chainhash.Hash{0xaa} + testRef := tapsdk.AssetRef( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + ).String() + + // Empty sealed package rejected as deterministic invalid package. + err = v.VerifyOORAssetVTXO(t.Context(), VerifyOORAssetVTXORequest{ + AssetRef: testRef, + AssetAmount: 100, + AssetRoot: root, + Outpoint: arkOP, + ArkTx: arkTx, + }) + require.ErrorIs(t, err, ErrInvalidOORAssetPackage) + require.ErrorContains(t, err, "sealed ark asset package is required") + + // Mismatched outpoint hash rejected as deterministic invalid package. + err = v.VerifyOORAssetVTXO( + t.Context(), VerifyOORAssetVTXORequest{ + AssetRef: testRef, + AssetAmount: 100, + AssetRoot: root, + Outpoint: wire.OutPoint{ + Hash: chainhash.Hash{0x01}, + Index: 0, + }, + ArkTx: arkTx, + SealedArkPackage: []byte("non-empty"), + }, + ) + require.ErrorIs(t, err, ErrInvalidOORAssetPackage) + require.ErrorContains(t, err, "does not match ark tx") + + // Out-of-bounds outpoint index rejected as deterministic invalid + // package. + err = v.VerifyOORAssetVTXO(t.Context(), VerifyOORAssetVTXORequest{ + AssetRef: testRef, + AssetAmount: 100, + AssetRoot: root, + Outpoint: wire.OutPoint{Hash: arkTx.TxHash(), Index: 3}, + ArkTx: arkTx, + SealedArkPackage: []byte("non-empty"), + }) + require.ErrorIs(t, err, ErrInvalidOORAssetPackage) + require.ErrorContains(t, err, "out of bounds") + + // Malformed sealed package bytes rejected as deterministic invalid + // package. + err = v.VerifyOORAssetVTXO(t.Context(), VerifyOORAssetVTXORequest{ + AssetRef: testRef, + AssetAmount: 100, + AssetRoot: root, + Outpoint: arkOP, + ArkTx: arkTx, + SealedArkPackage: []byte("not-a-valid-package"), + }) + require.ErrorIs(t, err, ErrInvalidOORAssetPackage) + + // Backend proof-chain failures recorded by VerifyConfirmedProof must + // NOT be classified as ErrInvalidOORAssetPackage. + failingChain := failingProofChainVerifier{ + err: fmt.Errorf("chain backend temporarily unavailable"), + } + pvIface, err := NewOORProofVerifier( + failingChain, nil, []OORPackageTxs{ + {ArkTx: arkTx}, + }, + ) + require.NoError(t, err) + _, err = pvIface.VerifyConfirmedProof(t.Context(), []byte("proof")) + require.Error(t, err) + require.NotErrorIs(t, err, ErrInvalidOORAssetPackage) + require.ErrorIs(t, err, errProofChainBackend) +} + +type failingProofChainVerifier struct { + err error +} + +func (f failingProofChainVerifier) VerifyProofChain(context.Context, + []byte) error { + + return f.err +} From 33315b1ba153d4a1abe15aa0a273fec9b8753012 Mon Sep 17 00:00:00 2001 From: Dario Anongba Varela Date: Thu, 26 Nov 2026 23:52:38 +0100 Subject: [PATCH 08/15] oor: wire prepared asset submits and incoming asset OOR receive Forward PreparedSubmitPackage through durable StartTransferRequest TLV so asset OOR sends enter the outgoing FSM with pre-committed packages, and keep VTXO.TapScript nil for asset-bearing TransferInputs across validation, snapshots, and incoming materialization. Wire incoming asset OOR metadata, composed RoutingPkScript derivation, async VerifyIncomingAssetPackage authentication outside the write lock, and sealed Ark asset package persistence on received VTXOs. Track CompletedEventIDs across incoming snapshots and queue concurrent distinct hints on parkedSelfHints so multi-output transfers to one wallet (such as asset change plus Bitcoin carrier return) materialize every owned output regardless of push ordering. --- oor/AGENTS.md | 36 +- oor/CLAUDE.md | 36 +- oor/actor_durable_message.go | 287 ++++++++++++ oor/actor_messages.go | 6 + oor/ark_recipients.go | 67 +++ oor/asset_oor_receive_test.go | 763 +++++++++++++++++++++++++++++++ oor/events.go | 4 + oor/incoming_adapter.go | 103 ++++- oor/incoming_vtxo.go | 94 +++- oor/local_persistence_handler.go | 196 +++++++- oor/outbox_messages.go | 31 +- oor/receive_snapshot.go | 157 ++++++- oor/receive_states.go | 88 +++- oor/receive_transitions.go | 101 ++-- oor/registry.go | 145 ++++-- oor/session.go | 9 +- oor/session_actor_handlers.go | 83 +++- oor/transfer_input_snapshot.go | 92 ++-- oor/transfer_inputs.go | 7 +- 19 files changed, 2141 insertions(+), 164 deletions(-) create mode 100644 oor/asset_oor_receive_test.go diff --git a/oor/AGENTS.md b/oor/AGENTS.md index 8b824611e..22b816fe1 100644 --- a/oor/AGENTS.md +++ b/oor/AGENTS.md @@ -110,17 +110,36 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/oor. 0 { + preparedSubmit, err = decodePreparedSubmitPackageWithLimits( + preparedRaw, limits, + ) + if err != nil { + return startTransferPayload{}, err + } + } + return startTransferPayload{ OperatorPubKey: operatorKey, CSVDelay: csvDelay, Inputs: inputs, Recipients: recipientsPayload, + PreparedSubmit: preparedSubmit, IdempotencyKey: string(idKey), DispatchRequestData: dispatchRequestData, AdmissionDeadlineUnixNanos: int64(deadline), }, nil } +// encodePreparedSubmitPackage serializes a PreparedSubmitPackage into bounded +// TLV records for durable actor mailbox persistence. +func encodePreparedSubmitPackage(pkg *PreparedSubmitPackage) ([]byte, error) { + if pkg == nil { + return nil, fmt.Errorf("prepared submit package must be " + + "provided") + } + + arkRaw, err := psbtutil.Serialize(pkg.ArkPSBT) + if err != nil { + return nil, fmt.Errorf("encode prepared ark psbt: %w", err) + } + + cpRaws, err := serializePSBTSlice(pkg.CheckpointPSBTs) + if err != nil { + return nil, fmt.Errorf("encode prepared checkpoint psbts: %w", + err) + } + cpListRaw, err := encodeLengthPrefixedBlobList(cpRaws) + if err != nil { + return nil, err + } + + rootBlobs := make([][]byte, len(pkg.CheckpointAssetRoots)) + for i, root := range pkg.CheckpointAssetRoots { + if root != nil { + rootBlobs[i] = append([]byte(nil), root[:]...) + } + } + rootsRaw, err := encodeLengthPrefixedBlobList(rootBlobs) + if err != nil { + return nil, err + } + + if pkg.TaprootAssetTransfer == nil { + return nil, fmt.Errorf("prepared taproot asset transfer is " + + "required") + } + xferRaw, err := pkg.TaprootAssetTransfer.MarshalBinary() + if err != nil { + return nil, fmt.Errorf("encode prepared taproot asset "+ + "transfer: %w", err) + } + + return tlvutil.EncodeRecordsToBytes( + tlv.MakePrimitiveRecord(preparedSubmitArkPSBTType, &arkRaw), + tlv.MakePrimitiveRecord( + preparedSubmitCheckpointPSBTsType, &cpListRaw, + ), + tlv.MakePrimitiveRecord( + preparedSubmitCheckpointRootsType, &rootsRaw, + ), + tlv.MakePrimitiveRecord( + preparedSubmitTaprootAssetXferType, &xferRaw, + ), + ) +} + +// decodePreparedSubmitPackageWithLimits decodes a PreparedSubmitPackage from +// TLV bytes while enforcing receive limits on checkpoints and roots. +func decodePreparedSubmitPackageWithLimits(raw []byte, + limits ReceiveLimits) (*PreparedSubmitPackage, error) { + + var ( + arkRaw []byte + cpListRaw []byte + rootsRaw []byte + xferRaw []byte + ) + + if _, err := decodeBoundedRecords( + raw, + tlv.MakePrimitiveRecord(preparedSubmitArkPSBTType, &arkRaw), + tlv.MakePrimitiveRecord( + preparedSubmitCheckpointPSBTsType, &cpListRaw, + ), + tlv.MakePrimitiveRecord( + preparedSubmitCheckpointRootsType, &rootsRaw, + ), + tlv.MakePrimitiveRecord( + preparedSubmitTaprootAssetXferType, &xferRaw, + ), + ); err != nil { + return nil, err + } + + ark, err := psbtutil.Parse(arkRaw) + if err != nil { + return nil, fmt.Errorf("decode prepared ark psbt: %w", err) + } + + checkpoints, err := decodeCheckpointPSBTsWithLimits(cpListRaw, limits) + if err != nil { + return nil, fmt.Errorf("decode prepared checkpoint psbts: %w", + err) + } + + rootBlobs, err := decodeLengthPrefixedBlobListWithLimits( + rootsRaw, limits, + ) + if err != nil { + return nil, fmt.Errorf("decode prepared checkpoint asset "+ + "roots: %w", err) + } + roots := make([]*chainhash.Hash, len(rootBlobs)) + for i, blob := range rootBlobs { + if len(blob) == 0 { + continue + } + if len(blob) != chainhash.HashSize { + return nil, fmt.Errorf("prepared checkpoint asset "+ + "root %d length %d want %d", i, len(blob), + chainhash.HashSize) + } + var h chainhash.Hash + copy(h[:], blob) + roots[i] = &h + } + + var xfer oortx.TaprootAssetTransfer + if err := xfer.UnmarshalBinary(xferRaw); err != nil { + return nil, fmt.Errorf("decode prepared taproot asset "+ + "transfer: %w", err) + } + if err := xfer.Validate(len(checkpoints)); err != nil { + return nil, fmt.Errorf("validate prepared taproot asset "+ + "transfer: %w", err) + } + + return &PreparedSubmitPackage{ + ArkPSBT: ark, + CheckpointPSBTs: checkpoints, + CheckpointAssetRoots: roots, + TaprootAssetTransfer: &xfer, + }, nil +} + // encodeLookupTransferPayload persists the stable key used to reconcile a // transfer after restart. func encodeLookupTransferPayload(idempotencyKey string) ([]byte, error) { @@ -718,6 +899,10 @@ func encodeIncomingMetadataMatch(match IncomingMetadataMatch) ([]byte, error) { if match.Metadata.ExpiryAuthenticated { expiryAuthenticated = 1 } + var assetVerified uint8 + if match.Metadata.AssetVerified { + assetVerified = 1 + } ancestryBytes, err := encodeAncestryList(match.Metadata.Ancestry) if err != nil { @@ -760,6 +945,14 @@ func encodeIncomingMetadataMatch(match IncomingMetadataMatch) ([]byte, error) { &expiryAuthenticated, ), } + if assetVerified == 1 { + records = append( + records, tlv.MakePrimitiveRecord( + incomingMetadataMatchAssetVerifiedRecordType, + &assetVerified, + ), + ) + } return tlvutil.EncodeRecordsToBytes(records...) } @@ -779,6 +972,7 @@ func decodeIncomingMetadataMatchWithLimits(raw []byte, ancestryBytes []byte operatorKey []byte expiryAuth uint8 + assetVerified uint8 ) records := []tlv.Record{ @@ -815,6 +1009,10 @@ func decodeIncomingMetadataMatchWithLimits(raw []byte, tlv.MakePrimitiveRecord( incomingMetadataMatchExpiryAuthRecordType, &expiryAuth, ), + tlv.MakePrimitiveRecord( + incomingMetadataMatchAssetVerifiedRecordType, + &assetVerified, + ), } if _, err := decodeBoundedRecords( @@ -831,6 +1029,10 @@ func decodeIncomingMetadataMatchWithLimits(raw []byte, return IncomingMetadataMatch{}, fmt.Errorf("incoming " + "metadata expiry authentication flag must be 0 or 1") } + if assetVerified > 1 { + return IncomingMetadataMatch{}, fmt.Errorf("incoming " + + "metadata asset verification flag must be 0 or 1") + } decodedBatchExpiry, err := uint32ToInt32( batchExpiry, "incoming batch expiry", @@ -875,6 +1077,7 @@ func decodeIncomingMetadataMatchWithLimits(raw []byte, CommitmentTxID: decodedCommitmentTxID, BatchExpiry: decodedBatchExpiry, ExpiryAuthenticated: expiryAuth == 1, + AssetVerified: assetVerified == 1, ChainDepth: int(decodedChainDepth), CreatedHeight: decodedCreatedHeight, OperatorKey: decodedOperatorKey, @@ -1047,6 +1250,7 @@ func encodeIncomingRecipients(recipients []ArkRecipientOutput) ([]byte, error) { []byte(nil), recipients[i].VTXOPolicyTemplate..., ), + Asset: recipients[i].Asset.Clone(), }, ) if err != nil { @@ -1087,6 +1291,7 @@ func decodeIncomingRecipientsWithLimits(raw []byte, VTXOPolicyTemplate: append( []byte(nil), payload.VTXOPolicyTemplate..., ), + Asset: payload.Asset.Clone(), }) } @@ -1122,6 +1327,27 @@ func encodeIncomingRecipientPayload(payload incomingRecipientPayload) ([]byte, ), } + if payload.Asset != nil { + if err := payload.Asset.Validate(); err != nil { + return nil, err + } + + assetRoot := payload.Asset.Root[:] + assetRef := []byte(payload.Asset.Ref) + assetAmount := payload.Asset.Amount + records = append( + records, tlv.MakePrimitiveRecord( + recipientTaprootAssetRootType, &assetRoot, + ), + tlv.MakePrimitiveRecord( + recipientTaprootAssetRefType, &assetRef, + ), + tlv.MakePrimitiveRecord( + recipientTaprootAssetAmountType, &assetAmount, + ), + ) + } + return tlvutil.EncodeRecordsToBytes(records...) } @@ -1135,6 +1361,9 @@ func decodeIncomingRecipientPayload(raw []byte) (incomingRecipientPayload, valueSat uint64 vtxoPolicyTemplate []byte outputIndex uint64 + assetRootRaw []byte + assetRefRaw []byte + assetAmount uint64 ) records := []tlv.Record{ @@ -1146,6 +1375,15 @@ func decodeIncomingRecipientPayload(raw []byte) (incomingRecipientPayload, tlv.MakePrimitiveRecord( recipientOutputIndexRecordType, &outputIndex, ), + tlv.MakePrimitiveRecord( + recipientTaprootAssetRootType, &assetRootRaw, + ), + tlv.MakePrimitiveRecord( + recipientTaprootAssetRefType, &assetRefRaw, + ), + tlv.MakePrimitiveRecord( + recipientTaprootAssetAmountType, &assetAmount, + ), } if _, err := decodeBoundedRecords( @@ -1168,11 +1406,19 @@ func decodeIncomingRecipientPayload(raw []byte) (incomingRecipientPayload, return incomingRecipientPayload{}, err } + asset, err := decodeTLVRecipientAsset( + assetRootRaw, assetRefRaw, assetAmount, + ) + if err != nil { + return incomingRecipientPayload{}, err + } + return incomingRecipientPayload{ OutputIndex: decodedOutputIndex, PkScript: pkScript, ValueSat: decodedValueSat, VTXOPolicyTemplate: vtxoPolicyTemplate, + Asset: asset, }, nil } @@ -2237,6 +2483,7 @@ func encodeEventPayload(event Event) ([]byte, error) { retryAfterNanos uint64 err error recipientPayload []byte + assetTransferRaw []byte ) switch evt := event.(type) { @@ -2340,6 +2587,15 @@ func encodeEventPayload(event Event) ([]byte, error) { return nil, err } + if evt.TaprootAssetTransfer != nil { + assetTransferRaw, err = evt.TaprootAssetTransfer. + MarshalBinary() + if err != nil { + return nil, fmt.Errorf("encode incoming event "+ + "taproot asset transfer: %w", err) + } + } + case *IncomingHandledEvent: eventKind = eventKindIncomingHandled @@ -2423,6 +2679,14 @@ func encodeEventPayload(event Event) ([]byte, error) { eventPayloadIncomingRecipientsType, &recipientPayload, ), } + if len(assetTransferRaw) > 0 { + records = append( + records, tlv.MakePrimitiveRecord( + eventPayloadTaprootAssetTransferType, + &assetTransferRaw, + ), + ) + } return tlvutil.EncodeRecordsToBytes(records...) } @@ -2447,6 +2711,7 @@ func decodeEventPayloadWithLimits(raw []byte, retryable uint8 retryAfterNanos uint64 recipientPayload []byte + assetTransferRaw []byte ) records := []tlv.Record{ @@ -2483,6 +2748,9 @@ func decodeEventPayloadWithLimits(raw []byte, tlv.MakePrimitiveRecord( eventPayloadIncomingRecipientsType, &recipientPayload, ), + tlv.MakePrimitiveRecord( + eventPayloadTaprootAssetTransferType, &assetTransferRaw, + ), } if _, err := decodeBoundedRecords( @@ -2583,11 +2851,30 @@ func decodeEventPayloadWithLimits(raw []byte, return nil, err } + var assetTransfer *oortx.TaprootAssetTransfer + if len(assetTransferRaw) > 0 { + var decoded oortx.TaprootAssetTransfer + if err := decoded.UnmarshalBinary( + assetTransferRaw, + ); err != nil { + return nil, fmt.Errorf("decode incoming event "+ + "taproot asset transfer: %w", err) + } + if err := decoded.Validate( + len(checkpoints), + ); err != nil { + return nil, fmt.Errorf("validate incoming "+ + "event taproot asset transfer: %w", err) + } + assetTransfer = &decoded + } + return &IncomingTransferEvent{ ArkPSBT: ark, FinalCheckpointPSBTs: checkpoints, AncestorPackages: ancestors, Recipients: recipients, + TaprootAssetTransfer: assetTransfer, }, nil case eventKindIncomingHandled: diff --git a/oor/actor_messages.go b/oor/actor_messages.go index c6ab21202..d0d9bb059 100644 --- a/oor/actor_messages.go +++ b/oor/actor_messages.go @@ -107,6 +107,10 @@ type StartTransferRequest struct { // Recipients are the Ark tx output scripts/amounts. Recipients []oortx.RecipientOutput + // PreparedSubmit is an optional pre-committed OOR package whose + // Taproot Asset commitments were already built outside the FSM. + PreparedSubmit *PreparedSubmitPackage + // IdempotencyKey identifies this caller intent across crashes and // retries. Empty preserves the historical deterministic-session // behavior. @@ -142,6 +146,7 @@ func (m *StartTransferRequest) Encode(w io.Writer) error { IdempotencyKey: m.IdempotencyKey, DispatchRequestData: m.DispatchRequestData, AdmissionDeadlineUnixNanos: m.AdmissionDeadlineUnixNanos, + PreparedSubmit: m.PreparedSubmit, Recipients: make( []recipientPayload, 0, len(m.Recipients), ), @@ -212,6 +217,7 @@ func (m *StartTransferRequest) Decode(r io.Reader) error { m.IdempotencyKey = payload.IdempotencyKey m.DispatchRequestData = payload.DispatchRequestData m.AdmissionDeadlineUnixNanos = payload.AdmissionDeadlineUnixNanos + m.PreparedSubmit = payload.PreparedSubmit m.Inputs = make([]TransferInput, 0, len(payload.Inputs)) for i := range payload.Inputs { diff --git a/oor/ark_recipients.go b/oor/ark_recipients.go index f3b963753..d5c367197 100644 --- a/oor/ark_recipients.go +++ b/oor/ark_recipients.go @@ -1,11 +1,15 @@ package oor import ( + "bytes" "fmt" "github.com/btcsuite/btcd/btcutil/v2" "github.com/btcsuite/btcd/psbt/v2" + "github.com/btcsuite/btcd/txscript/v2" + "github.com/lightninglabs/wavelength/lib/arkscript" "github.com/lightninglabs/wavelength/lib/tx/arktx" + oortx "github.com/lightninglabs/wavelength/lib/tx/oor" ) // ArkRecipientOutput is a non-anchor Ark tx output intended for the receiver. @@ -22,6 +26,68 @@ type ArkRecipientOutput struct { // VTXOPolicyTemplate is the serialized arkscript policy template for // the VTXO created by this output, when the server supplied it. VTXOPolicyTemplate []byte + + // Asset carries the optional Taproot Asset commitment metadata when + // this output creates an asset-bearing VTXO. + Asset *oortx.RecipientAsset +} + +// RoutingPkScript returns the uncomposed Ark receive script used to look up +// local receive-script ownership and indexer proof keys for this output. Plain +// Bitcoin outputs return PkScript unchanged; asset outputs verify that +// composing VTXOPolicyTemplate with Asset.Root produces PkScript and return +// the uncomposed policy script. +func (o ArkRecipientOutput) RoutingPkScript() ([]byte, error) { + if o.Asset == nil { + return bytes.Clone(o.PkScript), nil + } + if err := o.Asset.Validate(); err != nil { + return nil, fmt.Errorf("recipient output %d asset: %w", + o.OutputIndex, err) + } + if len(o.VTXOPolicyTemplate) == 0 { + return nil, fmt.Errorf("recipient output %d asset requires "+ + "vtxo policy template", o.OutputIndex) + } + + template, err := arkscript.DecodePolicyTemplate(o.VTXOPolicyTemplate) + if err != nil { + return nil, fmt.Errorf("decode recipient output %d policy: %w", + o.OutputIndex, err) + } + compiled, err := template.Compile() + if err != nil { + return nil, fmt.Errorf("compile recipient output %d policy: %w", + o.OutputIndex, err) + } + composed, err := arkscript.ComposeWithSiblingRoot( + compiled, o.Asset.Root, + ) + if err != nil { + return nil, fmt.Errorf("compose recipient output %d asset "+ + "root: %w", o.OutputIndex, err) + } + composedPkScript, err := txscript.PayToTaprootScript( + composed.OutputKey(), + ) + if err != nil { + return nil, fmt.Errorf("derive composed recipient output %d "+ + "pkscript: %w", o.OutputIndex, err) + } + if !bytes.Equal(composedPkScript, o.PkScript) { + return nil, fmt.Errorf("recipient output %d composed policy "+ + "does not match pkscript", o.OutputIndex) + } + + routingPkScript, err := txscript.PayToTaprootScript( + compiled.OutputKey(), + ) + if err != nil { + return nil, fmt.Errorf("derive routing recipient output %d "+ + "pkscript: %w", o.OutputIndex, err) + } + + return routingPkScript, nil } // ExtractArkRecipients returns the non-anchor outputs from a canonical Ark @@ -84,6 +150,7 @@ func CloneArkRecipients(recipients []ArkRecipientOutput) []ArkRecipientOutput { []byte(nil), recipients[i].VTXOPolicyTemplate..., ), + Asset: recipients[i].Asset.Clone(), } } diff --git a/oor/asset_oor_receive_test.go b/oor/asset_oor_receive_test.go new file mode 100644 index 000000000..e440e214d --- /dev/null +++ b/oor/asset_oor_receive_test.go @@ -0,0 +1,763 @@ +package oor + +import ( + "bytes" + "context" + "errors" + "fmt" + "testing" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/psbt/v2" + "github.com/btcsuite/btcd/txscript/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/btcsuite/btclog/v2" + "github.com/lightninglabs/wavelength/arkrpc" + "github.com/lightninglabs/wavelength/baselib/actor" + "github.com/lightninglabs/wavelength/lib/arkscript" + oortx "github.com/lightninglabs/wavelength/lib/tx/oor" + "github.com/lightninglabs/wavelength/lib/tx/psbtutil" + "github.com/lightninglabs/wavelength/vtxo" + "github.com/lightningnetwork/lnd/keychain" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" +) + +// buildTestIncomingAssetGraph constructs a valid canonical Ark PSBT and +// checkpoint PSBT paying an asset-bearing composed output to recipientKey. +func buildTestIncomingAssetGraph(t *testing.T, recipientKey *btcec.PublicKey, + operatorPriv *btcec.PrivateKey, exitDelay uint32, + assetRoot chainhash.Hash, assetRef string, assetAmount uint64) ( + *psbt.Packet, []*psbt.Packet, []byte, []byte, []byte, + *oortx.TaprootAssetTransfer) { + + t.Helper() + + operatorKey := operatorPriv.PubKey() + senderPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + + policy := arkscript.CheckpointPolicy{ + OperatorKey: operatorKey, + CSVDelay: exitDelay, + } + + inVTXO := newTestComposedAssetInput( + t, senderPriv, operatorKey, wire.OutPoint{ + Hash: chainhash.Hash{0x11}, + Index: 0, + }, + 1_000, + chainhash.Hash{0x22}, + assetRef, + assetAmount, + oortx.CarrierOriginRound, + ) + + collabLeaf, err := arkscript.MultiSigCollabTapLeaf( + senderPriv.PubKey(), operatorKey, + ) + require.NoError(t, err) + + cpArtifact, err := oortx.BuildCheckpointPSBT( + policy, oortx.CheckpointInput{ + SpentVTXO: oortx.SpentVTXORef{ + Outpoint: inVTXO.VTXO.Outpoint, + Output: wire.NewTxOut( + int64(inVTXO.VTXO.Amount), + inVTXO.VTXO.PkScript, + ), + }, + OwnerLeafScript: collabLeaf.Script, + }, + ) + require.NoError(t, err) + cpOut, err := cpArtifact.ToCheckpointOutput() + require.NoError(t, err) + + recipPolicyBytes, err := arkscript.EncodeStandardVTXOTemplate( + recipientKey, operatorKey, exitDelay, + ) + require.NoError(t, err) + recipTemplate, err := arkscript.DecodePolicyTemplate(recipPolicyBytes) + require.NoError(t, err) + recipCompiled, err := recipTemplate.Compile() + require.NoError(t, err) + routingPkScript, err := txscript.PayToTaprootScript( + recipCompiled.OutputKey(), + ) + require.NoError(t, err) + recipComposed, err := arkscript.ComposeWithSiblingRoot( + recipCompiled, assetRoot, + ) + require.NoError(t, err) + composedPkScript, err := txscript.PayToTaprootScript( + recipComposed.OutputKey(), + ) + require.NoError(t, err) + + arkPSBT, err := oortx.BuildArkPSBT( + []oortx.CheckpointOutput{cpOut}, + []oortx.RecipientOutput{{ + PkScript: composedPkScript, + Value: 1_000, + VTXOPolicyTemplate: recipPolicyBytes, + Asset: &oortx.RecipientAsset{ + Root: assetRoot, + Ref: assetRef, + Amount: assetAmount, + }, + }}, + ) + require.NoError(t, err) + + signCheckpointLegForTest(t, senderPriv, &inVTXO, cpArtifact.PSBT) + signCheckpointLegForTest(t, operatorPriv, &inVTXO, cpArtifact.PSBT) + + arkLeaf, err := oortx.BuildTaprootTapLeafScript( + cpArtifact.PSBT.Outputs[0].TaprootTapTree, collabLeaf.Script, + ) + require.NoError(t, err) + addTaprootLeafScript(&arkPSBT.Inputs[0], arkLeaf) + signArkInputLegForTest(t, senderPriv, arkPSBT, 0) + signArkInputLegForTest(t, operatorPriv, arkPSBT, 0) + + xfer := &oortx.TaprootAssetTransfer{ + Version: oortx.TaprootAssetTransferVersion, + ArkPackage: []byte("sealed-ark-asset-package"), + CheckpointPackages: [][]byte{ + []byte("sealed-cp-package"), + }, + } + + return arkPSBT, []*psbt.Packet{cpArtifact.PSBT}, recipPolicyBytes, + routingPkScript, composedPkScript, xfer +} + +// TestStartTransferRequestPreparedSubmitTLVRoundTrip verifies that +// StartTransferRequest preserves a PreparedSubmitPackage across durable +// mailbox TLV serialization, including nil float checkpoint asset root slots. +func TestStartTransferRequestPreparedSubmitTLVRoundTrip(t *testing.T) { + t.Parallel() + + operatorPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + senderPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + recipPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + floatPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + + const exitDelay = uint32(144) + assetRoot := chainhash.Hash{0xaa} + cpRoot := chainhash.Hash{0xbb} + const assetRef = "asset-usd" + + arkPSBT, cps, recipPolicy, _, composedScript, _ := + buildTestIncomingAssetGraph( + t, recipPriv.PubKey(), operatorPriv, exitDelay, + assetRoot, assetRef, 500, + ) + + floatPolicy, err := arkscript.EncodeStandardVTXOTemplate( + floatPriv.PubKey(), operatorPriv.PubKey(), exitDelay, + ) + require.NoError(t, err) + floatTemplate, err := arkscript.DecodePolicyTemplate(floatPolicy) + require.NoError(t, err) + floatPk, err := floatTemplate.PkScript() + require.NoError(t, err) + + floatCollabLeaf, err := arkscript.MultiSigCollabTapLeaf( + floatPriv.PubKey(), operatorPriv.PubKey(), + ) + require.NoError(t, err) + + floatCP, err := oortx.BuildCheckpointPSBT( + arkscript.CheckpointPolicy{ + OperatorKey: operatorPriv.PubKey(), + CSVDelay: exitDelay, + }, + oortx.CheckpointInput{ + SpentVTXO: oortx.SpentVTXORef{ + Outpoint: wire.OutPoint{ + Hash: chainhash.Hash{0x33}, + Index: 1, + }, + Output: wire.NewTxOut(2_000, floatPk), + }, + OwnerLeafScript: floatCollabLeaf.Script, + }, + ) + require.NoError(t, err) + + assetInput := newTestComposedAssetInput( + t, senderPriv, operatorPriv.PubKey(), wire.OutPoint{ + Hash: chainhash.Hash{0x11}, + Index: 0, + }, + 1_000, + chainhash.Hash{0x22}, + assetRef, + 500, + oortx.CarrierOriginRound, + ) + + orig := &StartTransferRequest{ + Policy: arkscript.CheckpointPolicy{ + OperatorKey: operatorPriv.PubKey(), + CSVDelay: exitDelay, + }, + Inputs: []TransferInput{ + assetInput, + }, + Recipients: []oortx.RecipientOutput{{ + PkScript: composedScript, + Value: 1_000, + VTXOPolicyTemplate: recipPolicy, + Asset: &oortx.RecipientAsset{ + Root: assetRoot, + Ref: assetRef, + Amount: 500, + }, + }}, + PreparedSubmit: &PreparedSubmitPackage{ + ArkPSBT: arkPSBT, + CheckpointPSBTs: []*psbt.Packet{ + cps[0], + floatCP.PSBT, + }, + CheckpointAssetRoots: []*chainhash.Hash{ + &cpRoot, nil, + }, + TaprootAssetTransfer: &oortx.TaprootAssetTransfer{ + Version: oortx.TaprootAssetTransferVersion, + ArkPackage: []byte("sealed-ark"), + CheckpointPackages: [][]byte{ + []byte("sealed-cp-0"), nil, + }, + }, + }, + IdempotencyKey: "asset-send-key-1", + } + + var buf bytes.Buffer + require.NoError(t, orig.Encode(&buf)) + + var decoded StartTransferRequest + require.NoError(t, decoded.Decode(bytes.NewReader(buf.Bytes()))) + require.NotNil(t, decoded.PreparedSubmit) + require.Equal( + t, orig.PreparedSubmit.ArkPSBT.UnsignedTx.TxHash(), + decoded.PreparedSubmit.ArkPSBT.UnsignedTx.TxHash(), + ) + require.Len(t, decoded.PreparedSubmit.CheckpointPSBTs, 2) + require.Len(t, decoded.PreparedSubmit.CheckpointAssetRoots, 2) + require.NotNil(t, decoded.PreparedSubmit.CheckpointAssetRoots[0]) + require.Equal( + t, cpRoot, *decoded.PreparedSubmit.CheckpointAssetRoots[0], + ) + require.Nil(t, decoded.PreparedSubmit.CheckpointAssetRoots[1]) + require.Equal( + t, orig.PreparedSubmit.TaprootAssetTransfer, + decoded.PreparedSubmit.TaprootAssetTransfer, + ) +} + +// TestIncomingTransferEventFromResponseAssetValidation verifies asset metadata +// parsing, composed script binding, fail-closed partial field rejection, and +// TLV round-tripping through both DriveEventRequest and IncomingSnapshot. +func TestIncomingTransferEventFromResponseAssetValidation(t *testing.T) { + t.Parallel() + + operatorPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + recipPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + + const exitDelay = uint32(144) + assetRoot := chainhash.Hash{0xcc} + const assetRef = "asset-usd" + const assetAmount = uint64(750) + + arkPSBT, cps, recipPolicy, routingScript, composedScript, xfer := + buildTestIncomingAssetGraph( + t, recipPriv.PubKey(), operatorPriv, exitDelay, + assetRoot, assetRef, assetAmount, + ) + + sessionID := SessionID(arkPSBT.UnsignedTx.TxHash()) + arkRaw, err := psbtutil.Serialize(arkPSBT) + require.NoError(t, err) + cpRaw, err := psbtutil.Serialize(cps[0]) + require.NoError(t, err) + xferRaw, err := xfer.MarshalBinary() + require.NoError(t, err) + + validEvent := &arkrpc.OORRecipientEvent{ + EventId: 42, + SessionId: sessionID[:], + OutputIndex: 0, + Value: 1_000, + RecipientPkScript: composedScript, + VtxoPolicyTemplate: recipPolicy, + ArkPsbt: arkRaw, + CheckpointPsbts: [][]byte{ + cpRaw, + }, + TaprootAssetRoot: assetRoot[:], + TaprootAssetRef: assetRef, + TaprootAssetAmount: assetAmount, + TaprootAssetTransfer: xferRaw, + } + + incoming, err := IncomingTransferEventFromResponse( + sessionID, 42, + &arkrpc.ListOORRecipientEventsByScriptResponse{ + Events: []*arkrpc.OORRecipientEvent{validEvent}, + }, + ) + require.NoError(t, err) + require.Equal(t, xfer, incoming.TaprootAssetTransfer) + require.Len(t, incoming.Recipients, 1) + require.NotNil(t, incoming.Recipients[0].Asset) + require.Equal(t, assetRoot, incoming.Recipients[0].Asset.Root) + require.Equal(t, assetRef, incoming.Recipients[0].Asset.Ref) + require.Equal(t, assetAmount, incoming.Recipients[0].Asset.Amount) + + gotRouting, err := incoming.Recipients[0].RoutingPkScript() + require.NoError(t, err) + require.Equal(t, routingScript, gotRouting) + + // Round-trip IncomingTransferEvent via DriveEventRequest TLV. + driveReq := &DriveEventRequest{ + SessionID: sessionID, + Event: incoming, + } + var driveBuf bytes.Buffer + require.NoError(t, driveReq.Encode(&driveBuf)) + var decodedDrive DriveEventRequest + require.NoError( + t, + decodedDrive.Decode( + bytes.NewReader( + driveBuf.Bytes(), + ), + ), + ) + decodedIncoming, ok := decodedDrive.Event.(*IncomingTransferEvent) + require.True(t, ok) + require.Equal(t, xfer, decodedIncoming.TaprootAssetTransfer) + require.Len(t, decodedIncoming.Recipients, 1) + require.Equal( + t, incoming.Recipients[0].Asset, + decodedIncoming.Recipients[0].Asset, + ) + + // Round-trip ReceiveNotified through IncomingSnapshot TLV. + notified := &ReceiveNotified{ + SessionID: sessionID, + ArkPSBT: arkPSBT, + FinalCheckpointPSBTs: cps, + Recipients: incoming.Recipients, + TaprootAssetTransfer: incoming.TaprootAssetTransfer, + } + snap, err := NewIncomingSnapshot(sessionID, notified) + require.NoError(t, err) + snapRaw, err := encodeIncomingSnapshot(snap) + require.NoError(t, err) + decodedSnap, err := decodeIncomingSnapshotWithLimits( + snapRaw, ReceiveLimits{}, + ) + require.NoError(t, err) + restoredState, err := IncomingStateFromSnapshot(decodedSnap) + require.NoError(t, err) + restoredNotified, ok := restoredState.(*ReceiveNotified) + require.True(t, ok) + require.Equal(t, xfer, restoredNotified.TaprootAssetTransfer) + require.Equal( + t, incoming.Recipients[0].Asset, + restoredNotified.Recipients[0].Asset, + ) + + // Partial asset fields (missing TaprootAssetTransfer) must fail closed. + missingXfer, ok := proto.Clone(validEvent).(*arkrpc.OORRecipientEvent) + require.True(t, ok) + missingXfer.TaprootAssetTransfer = nil + _, err = IncomingTransferEventFromResponse( + sessionID, 42, + &arkrpc.ListOORRecipientEventsByScriptResponse{ + Events: []*arkrpc.OORRecipientEvent{missingXfer}, + }, + ) + require.ErrorContains(t, err, "missing taproot asset transfer") + + // Tampered asset root fails composed-script binding check. + badRoot := chainhash.Hash{0xdd} + wrongRootEvent, ok := proto.Clone( + validEvent, + ).(*arkrpc.OORRecipientEvent) + require.True(t, ok) + wrongRootEvent.TaprootAssetRoot = badRoot[:] + _, err = IncomingTransferEventFromResponse( + sessionID, 42, + &arkrpc.ListOORRecipientEventsByScriptResponse{ + Events: []*arkrpc.OORRecipientEvent{wrongRootEvent}, + }, + ) + require.ErrorContains(t, err, "does not match pkscript") +} + +// TestLocalPersistenceHandlerIncomingAssetMaterialization verifies that +// AuthenticateIncomingMetadataRequest runs VerifyIncomingAssetPackage and that +// MaterializeIncomingVTXOsRequest persists TaprootAssetRoot, Ref, Amount, and +// SealedPackage on the materialized VTXO descriptor. +func TestLocalPersistenceHandlerIncomingAssetMaterialization(t *testing.T) { + t.Parallel() + + operatorPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + recipPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + + const exitDelay = uint32(144) + assetRoot := chainhash.Hash{0xee} + const assetRef = "asset-usd" + const assetAmount = uint64(600) + + arkPSBT, cps, recipPolicy, routingScript, composedScript, xfer := + buildTestIncomingAssetGraph( + t, recipPriv.PubKey(), operatorPriv, exitDelay, + assetRoot, assetRef, assetAmount, + ) + sessionID := SessionID(arkPSBT.UnsignedTx.TxHash()) + + recipients := []ArkRecipientOutput{{ + OutputIndex: 0, + Value: 1_000, + PkScript: composedScript, + VTXOPolicyTemplate: recipPolicy, + Asset: &oortx.RecipientAsset{ + Root: assetRoot, + Ref: assetRef, + Amount: assetAmount, + }, + }} + + commitmentID := chainhash.Hash{0x55} + baseMatch := IncomingMetadataMatch{ + OutputIndex: 0, + Metadata: IncomingVTXOMetadata{ + RoundID: "round-1", + CommitmentTxID: commitmentID, + ChainDepth: 1, + OperatorKey: operatorPriv.PubKey(), + Ancestry: validTestIncomingAncestry(commitmentID), + }, + } + + store := newTestVTXOStore() + pkgStore := &testPackageStore{} + var verifiedCalls int + var notified []*vtxo.Descriptor + + handler := &LocalPersistenceOutboxHandler{ + Store: store, + PackageStore: pkgStore, + OperatorKey: operatorPriv.PubKey(), + ExitDelay: exitDelay, + AuthenticateIncomingExpiry: func(_ context.Context, + _ []vtxo.Ancestry) (vtxo.AuthenticatedBatchEvidence, + error) { + + return vtxo.AuthenticatedBatchEvidence{ + BatchExpiry: 10_000, + EarliestCommitmentHeight: 100, + }, nil + }, + VerifyIncomingAssetPackage: func(_ context.Context, + req IncomingAssetVerification) error { + + verifiedCalls++ + require.Equal(t, sessionID, req.SessionID) + require.Equal(t, assetRef, req.Recipient.Asset.Ref) + require.Equal( + t, xfer.ArkPackage, + req.TaprootAssetTransfer.ArkPackage, + ) + + return nil + }, + ResolveIncomingClientKey: func(_ context.Context, + recipient ArkRecipientOutput) (keychain.KeyDescriptor, + error) { + + gotRouting, err := recipient.RoutingPkScript() + require.NoError(t, err) + require.Equal(t, routingScript, gotRouting) + + return keychain.KeyDescriptor{ + PubKey: recipPriv.PubKey(), + }, nil + }, + NotifyIncomingVTXOs: func(_ context.Context, + vtxos []*vtxo.Descriptor) error { + + notified = append(notified, vtxos...) + + return nil + }, + } + + authEvents, err := handler.Handle( + t.Context(), sessionID, &AuthenticateIncomingMetadataRequest{ + SessionID: sessionID, + Matches: []IncomingMetadataMatch{ + baseMatch, + }, + ArkPSBT: arkPSBT, + FinalCheckpointPSBTs: cps, + Recipients: recipients, + TaprootAssetTransfer: xfer, + }, + ) + require.NoError(t, err) + require.Equal(t, 1, verifiedCalls) + require.Len(t, authEvents, 1) + + resolved, ok := authEvents[0].(*IncomingMetadataResolvedEvent) + require.True(t, ok) + require.True(t, resolved.ExpiryAuthenticated) + require.Len(t, resolved.Matches, 1) + require.True(t, resolved.Matches[0].Metadata.AssetVerified) + + matEvents, err := handler.Handle( + t.Context(), sessionID, &MaterializeIncomingVTXOsRequest{ + SessionID: sessionID, + ArkPSBT: arkPSBT, + FinalCheckpointPSBTs: cps, + Recipients: recipients, + MetadataMatches: resolved.Matches, + TaprootAssetTransfer: xfer, + }, + ) + require.NoError(t, err) + require.Len(t, matEvents, 1) + require.Len(t, notified, 1) + + op := wire.OutPoint{Hash: chainhash.Hash(sessionID), Index: 0} + saved, err := store.GetVTXO(t.Context(), op) + require.NoError(t, err) + require.Nil(t, saved.TapScript) + require.NotNil(t, saved.TaprootAssetRoot) + require.Equal(t, assetRoot, *saved.TaprootAssetRoot) + require.Equal(t, assetRef, saved.TaprootAssetRef) + require.Equal(t, assetAmount, saved.TaprootAssetAmount) + require.Equal(t, xfer.ArkPackage, saved.TaprootAssetSealedPackage) + + // An asset TransferInput loaded from VTXOStore carries TapScript == nil + // and must still validate, derive its composed spend path, and preserve + // TapScript == nil across snapshot round-trip. + assetInput := TransferInput{ + VTXO: saved, + VTXOPolicyTemplate: recipPolicy, + TaprootAssetCarrierOrigin: oortx.CarrierOriginOOR, + } + require.NoError(t, assetInput.Validate()) + spendPath, err := assetInput.EffectiveSpendPath() + require.NoError(t, err) + require.NoError(t, spendPath.VerifyBindsToPkScript(composedScript)) + + inputSnap, err := assetInput.ToSnapshot() + require.NoError(t, err) + rebuilt, err := TransferInputFromSnapshot(inputSnap) + require.NoError(t, err) + require.Nil(t, rebuilt.VTXO.TapScript) + require.Equal(t, composedScript, rebuilt.VTXO.PkScript) + require.NoError(t, rebuilt.Validate()) + + // A verifier rejection marked with ErrInvalidIncomingAssetPackage fails + // terminally so the receive FSM does not retry forever. + handler.VerifyIncomingAssetPackage = func(_ context.Context, + _ IncomingAssetVerification) error { + + return fmt.Errorf("%w: bad proof", + ErrInvalidIncomingAssetPackage) + } + _, err = handler.Handle( + t.Context(), sessionID, &AuthenticateIncomingMetadataRequest{ + SessionID: sessionID, + Matches: []IncomingMetadataMatch{ + baseMatch, + }, + ArkPSBT: arkPSBT, + FinalCheckpointPSBTs: cps, + Recipients: recipients, + TaprootAssetTransfer: xfer, + }, + ) + require.Error(t, err) + var termErr *terminalOutboxError + require.True(t, errors.As(err, &termErr)) +} + +// TestMultiEventIncomingReceivePass verifies that an incoming OOR session +// records completed recipient event IDs across snapshots, allows a distinct +// recipient event for the same session (e.g. asset change plus Bitcoin carrier +// return) to run a fresh receive pass after ReceiveCompleted, postpones a +// distinct event arriving while another pass is in flight, absorbs duplicates, +// and preserves multiple parked self-hints per session in FIFO order. +func TestMultiEventIncomingReceivePass(t *testing.T) { + t.Parallel() + + operatorPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + recipPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + + arkPSBT, cps, _, routingScript, _, xfer := buildTestIncomingAssetGraph( + t, recipPriv.PubKey(), operatorPriv, 144, chainhash.Hash{0xaa}, + "asset-usd", 150, + ) + sessionID := SessionID(arkPSBT.UnsignedTx.TxHash()) + + // Walk ReceiveResolving(event 3) -> ReceiveNotified -> + // ReceiveAwaitingAck -> ReceiveCompleted{CompletedEventIDs: [3]}. + sess, err := newReceiveSessionWithState( + t.Context(), sessionID, &ReceiveResolving{ + SessionID: sessionID, + RecipientPkScript: routingScript, + RecipientEventID: 3, + }, EnvConfig{}, + ) + require.NoError(t, err) + + res := sess.FSM.AskEvent(t.Context(), &IncomingTransferEvent{ + SessionID: sessionID, + ArkPSBT: arkPSBT, + FinalCheckpointPSBTs: cps, + TaprootAssetTransfer: xfer, + }).Await(t.Context()) + require.NoError(t, res.Err()) + + st, err := sess.FSM.CurrentState() + require.NoError(t, err) + notified, ok := st.(*ReceiveNotified) + require.True(t, ok) + require.EqualValues(t, 3, notified.RecipientEventID) + + res = sess.FSM.AskEvent(t.Context(), &IncomingHandledEvent{}). + Await(t.Context()) + require.NoError(t, res.Err()) + + res = sess.FSM.AskEvent(t.Context(), &IncomingAckSentEvent{}). + Await(t.Context()) + require.NoError(t, res.Err()) + + st, err = sess.FSM.CurrentState() + require.NoError(t, err) + completed, ok := st.(*ReceiveCompleted) + require.True(t, ok) + require.Equal(t, []uint64{3}, completed.CompletedEventIDs) + require.True(t, completed.HasEventID(3)) + require.False(t, completed.HasEventID(2)) + + // Snapshot round-trip preserves CompletedEventIDs on ReceiveCompleted. + snap, err := NewIncomingSnapshot(sessionID, completed) + require.NoError(t, err) + raw, err := encodeIncomingSnapshot(snap) + require.NoError(t, err) + decodedSnap, err := decodeIncomingSnapshotWithLimits( + raw, ReceiveLimits{}, + ) + require.NoError(t, err) + restoredState, err := IncomingStateFromSnapshot(decodedSnap) + require.NoError(t, err) + restoredCompleted, ok := restoredState.(*ReceiveCompleted) + require.True(t, ok) + require.Equal(t, []uint64{3}, restoredCompleted.CompletedEventIDs) + + // On the session behavior: repeating event 3 is a no-op; a distinct + // event 2 starts a fresh ReceiveResolving pass carrying [3]; and while + // event 2 is active, a distinct event 4 postpones instead of dropping. + b := &sessionBehavior{ + sessionID: sessionID, + log: btclog.Disabled, + loaded: true, + } + b.setFSM(sess.FSM) + + dupRes := b.handleResolveIncomingTransfer( + t.Context(), &ResolveIncomingTransferRequest{ + SessionID: sessionID, + RecipientPkScript: routingScript, + RecipientEventID: 3, + }, + ) + require.NoError(t, dupRes.Err()) + st, err = b.fsm.CurrentState() + require.NoError(t, err) + _, stillCompleted := st.(*ReceiveCompleted) + require.True(t, stillCompleted) + + nextRes := b.handleResolveIncomingTransfer( + t.Context(), &ResolveIncomingTransferRequest{ + SessionID: sessionID, + RecipientPkScript: routingScript, + RecipientEventID: 2, + }, + ) + require.NoError(t, nextRes.Err()) + st, err = b.fsm.CurrentState() + require.NoError(t, err) + resolving, ok := st.(*ReceiveResolving) + require.True(t, ok) + require.EqualValues(t, 2, resolving.RecipientEventID) + require.Equal(t, []uint64{3}, resolving.CompletedEventIDs) + + busyRes := b.handleResolveIncomingTransfer( + t.Context(), &ResolveIncomingTransferRequest{ + SessionID: sessionID, + RecipientPkScript: routingScript, + RecipientEventID: 4, + }, + ) + require.ErrorIs(t, busyRes.Err(), actor.ErrPostponed) + + // Registry parkedSelfHints preserves multiple distinct recipient + // events for the same session in FIFO order and deduplicates repeats. + reg := &oorRegistryBehavior{} + reg.parkSelfHint(&ResolveIncomingTransferRequest{ + SessionID: sessionID, + RecipientPkScript: routingScript, + RecipientEventID: 2, + }) + reg.parkSelfHint(&ResolveIncomingTransferRequest{ + SessionID: sessionID, + RecipientPkScript: routingScript, + RecipientEventID: 3, + }) + reg.parkSelfHint(&ResolveIncomingTransferRequest{ + SessionID: sessionID, + RecipientPkScript: routingScript, + RecipientEventID: 2, + }) + require.Len(t, reg.parkedSelfHints[sessionID], 2) + require.EqualValues( + t, 2, reg.parkedSelfHints[sessionID][0]. + RecipientEventID, + ) + require.EqualValues( + t, 3, reg.parkedSelfHints[sessionID][1]. + RecipientEventID, + ) + + reg.unparkSelfHint(sessionID, 2) + require.Len(t, reg.parkedSelfHints[sessionID], 1) + require.EqualValues( + t, 3, reg.parkedSelfHints[sessionID][0]. + RecipientEventID, + ) +} diff --git a/oor/events.go b/oor/events.go index 74a18f9a3..b40a79ed6 100644 --- a/oor/events.go +++ b/oor/events.go @@ -182,6 +182,10 @@ type IncomingTransferEvent struct { // structural extraction from ArkPSBT for compatibility with older // servers. Recipients []ArkRecipientOutput + + // TaprootAssetTransfer carries the sealed Taproot Asset transition + // packages when this incoming transfer creates an asset VTXO. + TaprootAssetTransfer *oortx.TaprootAssetTransfer } // eventSealed marks this as implementing the sealed Event interface. diff --git a/oor/incoming_adapter.go b/oor/incoming_adapter.go index e84a09ea4..5ebf978f1 100644 --- a/oor/incoming_adapter.go +++ b/oor/incoming_adapter.go @@ -11,6 +11,7 @@ import ( "github.com/btcsuite/btcd/chainhash/v2" "github.com/btcsuite/btcd/psbt/v2" "github.com/lightninglabs/wavelength/arkrpc" + oortx "github.com/lightninglabs/wavelength/lib/tx/oor" "github.com/lightninglabs/wavelength/lib/tx/psbtutil" ) @@ -179,7 +180,9 @@ func IncomingTransferEventFromResponseWithLimits(sessionID SessionID, return nil, err } - recipients, err := incomingRecipientsFromEvent(arkPSBT, recipientEvt) + recipients, assetTransfer, err := incomingRecipientsFromEvent( + arkPSBT, recipientEvt, len(checkpoints), + ) if err != nil { return nil, err } @@ -196,21 +199,32 @@ func IncomingTransferEventFromResponseWithLimits(sessionID SessionID, FinalCheckpointPSBTs: checkpoints, AncestorPackages: ancestors, Recipients: recipients, + TaprootAssetTransfer: assetTransfer, }, nil } -// incomingRecipientsFromEvent overlays the policy metadata carried by the -// recipient event onto the structurally extracted Ark outputs. +// incomingRecipientsFromEvent overlays the policy and optional Taproot Asset +// metadata carried by the recipient event onto the structurally extracted Ark +// outputs. func incomingRecipientsFromEvent(ark *psbt.Packet, - evt *arkrpc.OORRecipientEvent) ([]ArkRecipientOutput, error) { + evt *arkrpc.OORRecipientEvent, checkpointCount int) ( + []ArkRecipientOutput, *oortx.TaprootAssetTransfer, error) { recipients, err := ExtractArkRecipients(ark) if err != nil { - return nil, err + return nil, nil, err } if evt.GetValue() > uint64(math.MaxInt64) { - return nil, fmt.Errorf("recipient event value overflows int64") + return nil, nil, fmt.Errorf("recipient event value overflows " + + "int64") + } + + asset, assetTransfer, err := parseIncomingEventAsset( + evt, checkpointCount, + ) + if err != nil { + return nil, nil, err } value := btcutil.Amount(evt.GetValue()) @@ -220,27 +234,94 @@ func incomingRecipientsFromEvent(ark *psbt.Packet, } if recipients[i].Value != value { - return nil, fmt.Errorf("recipient event value mismatch") + return nil, nil, fmt.Errorf("recipient event value " + + "mismatch") } if !bytes.Equal( recipients[i].PkScript, evt.GetRecipientPkScript(), ) { - return nil, fmt.Errorf("recipient event pkscript " + - "mismatch") + return nil, nil, fmt.Errorf("recipient event " + + "pkscript mismatch") } recipients[i].VTXOPolicyTemplate = append( []byte(nil), evt.GetVtxoPolicyTemplate()..., ) + recipients[i].Asset = asset + if asset != nil { + _, err := recipients[i].RoutingPkScript() + if err != nil { + return nil, nil, fmt.Errorf("recipient event "+ + "asset script binding: %w", err) + } + } - return recipients, nil + return recipients, assetTransfer, nil } - return nil, fmt.Errorf("recipient event output %d not found", + return nil, nil, fmt.Errorf("recipient event output %d not found", evt.GetOutputIndex()) } +// parseIncomingEventAsset extracts and validates optional Taproot Asset +// metadata and the sealed asset transfer container from one recipient event, +// enforcing all-or-none consistency. +func parseIncomingEventAsset(evt *arkrpc.OORRecipientEvent, + checkpointCount int) (*oortx.RecipientAsset, + *oortx.TaprootAssetTransfer, error) { + + rootRaw := evt.GetTaprootAssetRoot() + ref := evt.GetTaprootAssetRef() + amount := evt.GetTaprootAssetAmount() + transferRaw := evt.GetTaprootAssetTransfer() + + hasAny := len(rootRaw) > 0 || ref != "" || amount > 0 || + len(transferRaw) > 0 + if !hasAny { + return nil, nil, nil + } + + if len(rootRaw) != chainhash.HashSize { + return nil, nil, fmt.Errorf("recipient event taproot asset "+ + "root must be %d bytes, got %d", chainhash.HashSize, + len(rootRaw)) + } + if len(transferRaw) == 0 { + return nil, nil, fmt.Errorf("recipient event missing taproot " + + "asset transfer package") + } + if len(transferRaw) > maxOORMessageSize { + return nil, nil, fmt.Errorf("recipient event taproot asset "+ + "transfer %d bytes exceeds max %d", len(transferRaw), + maxOORMessageSize) + } + + var root chainhash.Hash + copy(root[:], rootRaw) + + asset := &oortx.RecipientAsset{ + Root: root, + Ref: ref, + Amount: amount, + } + if err := asset.Validate(); err != nil { + return nil, nil, fmt.Errorf("recipient event asset: %w", err) + } + + var transfer oortx.TaprootAssetTransfer + if err := transfer.UnmarshalBinary(transferRaw); err != nil { + return nil, nil, fmt.Errorf("decode recipient event taproot "+ + "asset transfer: %w", err) + } + if err := transfer.Validate(checkpointCount); err != nil { + return nil, nil, fmt.Errorf("validate recipient event taproot "+ + "asset transfer: %w", err) + } + + return asset, &transfer, nil +} + // packageArtifactsFromRPC converts RPC package artifacts into domain // artifacts after enforcing the same bounded-shape policy as checkpoint // parsing. diff --git a/oor/incoming_vtxo.go b/oor/incoming_vtxo.go index 13d6a1671..69925f4d3 100644 --- a/oor/incoming_vtxo.go +++ b/oor/incoming_vtxo.go @@ -17,6 +17,7 @@ import ( "github.com/lightninglabs/wavelength/lib/arkscript" "github.com/lightninglabs/wavelength/lib/tree" "github.com/lightninglabs/wavelength/lib/tx/arktx" + oortx "github.com/lightninglabs/wavelength/lib/tx/oor" "github.com/lightninglabs/wavelength/vtxo" "github.com/lightningnetwork/lnd/keychain" ) @@ -47,6 +48,12 @@ type IncomingVTXOMetadata struct { // VTXO data. ExpiryAuthenticated bool + // AssetVerified records that the incoming Taproot Asset package for + // this output was verified against the asset backend and authenticated + // lineage before entering the materialization DB transaction. It is + // transient receive-state, not persisted VTXO data. + AssetVerified bool + // ChainDepth is the number of OOR checkpoint hops between this // VTXO and the last on-chain commitment. This is distinct from // per-Ancestry TreeDepth, which tracks position within a single @@ -99,6 +106,15 @@ type IncomingVTXOConfig struct { // derives the standard VTXO policy from ClientKey, OperatorKey, and // ExitDelay for compatibility with older servers. PolicyTemplate []byte + + // Asset carries the optional Taproot Asset commitment metadata for an + // asset-bearing incoming output. When set, TaprootAssetSealedPackage + // and PolicyTemplate must also be supplied. + Asset *oortx.RecipientAsset + + // TaprootAssetSealedPackage is the verified sealed Ark transition + // package persisted on the materialized asset VTXO descriptor. + TaprootAssetSealedPackage []byte } // BuildIncomingVTXODescriptor constructs a VTXO descriptor for a recipient @@ -132,6 +148,23 @@ func BuildIncomingVTXODescriptor(ark *psbt.Packet, return nil, fmt.Errorf("commitment tx id must be provided") } + if cfg.Asset != nil { + if err := cfg.Asset.Validate(); err != nil { + return nil, fmt.Errorf("incoming VTXO asset: %w", err) + } + if len(cfg.TaprootAssetSealedPackage) == 0 { + return nil, fmt.Errorf("incoming asset VTXO requires " + + "sealed asset package") + } + if len(cfg.PolicyTemplate) == 0 { + return nil, fmt.Errorf("incoming asset VTXO requires " + + "vtxo policy template") + } + } else if len(cfg.TaprootAssetSealedPackage) > 0 { + return nil, fmt.Errorf("sealed asset package supplied " + + "without asset metadata") + } + err := arktx.ValidateCanonicalPSBT(ark) if err != nil { return nil, err @@ -172,7 +205,7 @@ func BuildIncomingVTXODescriptor(ark *psbt.Packet, ancestry := normalizeIncomingAncestry(cfg.Metadata) - return &vtxo.Descriptor{ + desc := &vtxo.Descriptor{ Outpoint: wire.OutPoint{ Hash: arkTxid, Index: cfg.OutputIndex, @@ -191,7 +224,19 @@ func BuildIncomingVTXODescriptor(ark *psbt.Packet, ChainDepth: cfg.Metadata.ChainDepth, CreatedHeight: cfg.Metadata.CreatedHeight, Status: vtxo.VTXOStatusLive, - }, nil + } + if cfg.Asset != nil { + root := cfg.Asset.Root + desc.TapScript = nil + desc.TaprootAssetRoot = &root + desc.TaprootAssetRef = cfg.Asset.Ref + desc.TaprootAssetAmount = cfg.Asset.Amount + desc.TaprootAssetSealedPackage = bytes.Clone( + cfg.TaprootAssetSealedPackage, + ) + } + + return desc, nil } // incomingOutputPolicy authenticates and returns the incoming output policy, @@ -208,9 +253,11 @@ func incomingOutputPolicy(pkScript []byte, cfg IncomingVTXOConfig) ([]byte, "policy: %w", err) } - if !template.MatchesPkScript(pkScript) { - return nil, nil, 0, fmt.Errorf("incoming VTXO policy " + - "does not match ark output pkscript") + err = verifyIncomingPolicyPkScript( + template, pkScript, cfg.Asset, + ) + if err != nil { + return nil, nil, 0, err } tapscript, relativeExpiry, err := incomingPolicyExitDelay( @@ -260,6 +307,43 @@ func incomingOutputPolicy(pkScript []byte, cfg IncomingVTXOConfig) ([]byte, return policyTemplate, tapscript, cfg.ExitDelay, nil } +// verifyIncomingPolicyPkScript checks that template produces pkScript, +// composing asset.Root as a sibling taproot branch when asset is non-nil. +func verifyIncomingPolicyPkScript(template *arkscript.PolicyTemplate, + pkScript []byte, asset *oortx.RecipientAsset) error { + + if asset == nil { + if !template.MatchesPkScript(pkScript) { + return fmt.Errorf("incoming VTXO policy does not " + + "match ark output pkscript") + } + + return nil + } + + compiled, err := template.Compile() + if err != nil { + return fmt.Errorf("compile incoming asset VTXO policy: %w", err) + } + composed, err := arkscript.ComposeWithSiblingRoot(compiled, asset.Root) + if err != nil { + return fmt.Errorf("compose incoming asset VTXO policy: %w", err) + } + composedPkScript, err := txscript.PayToTaprootScript( + composed.OutputKey(), + ) + if err != nil { + return fmt.Errorf("derive composed incoming asset VTXO "+ + "pkscript: %w", err) + } + if !bytes.Equal(composedPkScript, pkScript) { + return fmt.Errorf("incoming asset VTXO policy does not match " + + "composed ark output pkscript") + } + + return nil +} + // incomingPolicyExitDelay derives the earliest authenticated owner exit delay // from a matching standard or custom policy template. func incomingPolicyExitDelay(template *arkscript.PolicyTemplate, diff --git a/oor/local_persistence_handler.go b/oor/local_persistence_handler.go index 9705309a8..2165a95f6 100644 --- a/oor/local_persistence_handler.go +++ b/oor/local_persistence_handler.go @@ -13,6 +13,7 @@ import ( "github.com/btcsuite/btcd/wire/v2" "github.com/lightninglabs/wavelength/baselib/actor" "github.com/lightninglabs/wavelength/ledger" + oortx "github.com/lightninglabs/wavelength/lib/tx/oor" libtypes "github.com/lightninglabs/wavelength/lib/types" "github.com/lightninglabs/wavelength/vtxo" fn "github.com/lightningnetwork/lnd/fn/v2" @@ -25,6 +26,12 @@ var ( // materialization. ErrIncomingRecipientNotOwned = errors.New("incoming recipient not " + "owned by wallet") + + // ErrInvalidIncomingAssetPackage signals that an incoming asset OOR + // package failed cryptographic or structural asset verification and + // must fail the receive session terminally rather than retry. + ErrInvalidIncomingAssetPackage = errors.New("invalid incoming asset " + + "package") ) // IsIncomingRecipientNotOwned reports whether an error means the recipient @@ -52,6 +59,40 @@ type IncomingMetadataResolver func(ctx context.Context, sessionID SessionID, type IncomingExpiryAuthenticator func(ctx context.Context, ancestry []vtxo.Ancestry) (vtxo.AuthenticatedBatchEvidence, error) +// IncomingAssetVerification carries all authenticated lineage, OOR packages, +// and sealed Taproot Asset transition data needed to verify one incoming +// asset-bearing OOR output before persisting it on the local VTXO descriptor. +type IncomingAssetVerification struct { + // SessionID identifies the incoming OOR session (Ark txid). + SessionID SessionID + + // Recipient is the matched asset-bearing Ark output being received. + Recipient ArkRecipientOutput + + // ArkPSBT is the canonical Ark transaction PSBT. + ArkPSBT *psbt.Packet + + // FinalCheckpointPSBTs are the finalized checkpoint PSBTs for this + // transfer. + FinalCheckpointPSBTs []*psbt.Packet + + // AncestorPackages are finalized prior OOR packages for this transfer. + AncestorPackages []PackageArtifact + + // Metadata carries the authenticated commitment-tree ancestry for this + // output. + Metadata IncomingVTXOMetadata + + // TaprootAssetTransfer holds the sealed asset packages for this + // transfer, including ArkPackage. + TaprootAssetTransfer *oortx.TaprootAssetTransfer +} + +// IncomingAssetVerifier validates one incoming asset-bearing OOR output +// against the local asset backend and authenticated Bitcoin lineage. +type IncomingAssetVerifier func(ctx context.Context, + req IncomingAssetVerification) error + // IncomingMetadataRecipientFilter filters an incoming Ark package down to the // recipient outputs controlled by the local wallet. type IncomingMetadataRecipientFilter interface { @@ -125,6 +166,12 @@ type LocalPersistenceOutboxHandler struct { // materialization starts its DB transaction. AuthenticateIncomingExpiry IncomingExpiryAuthenticator + // VerifyIncomingAssetPackage validates an incoming asset OOR output's + // sealed Ark transition package before materialization persists it on + // the received VTXO descriptor. When nil, incoming asset outputs fail + // closed. + VerifyIncomingAssetPackage IncomingAssetVerifier + // NotifyIncomingVTXOs is invoked after incoming VTXOs are persisted. // Production wiring should use this to notify the VTXO manager so newly // received OOR VTXOs are actively monitored when the handler is used @@ -191,6 +238,14 @@ func (h *LocalPersistenceOutboxHandler) handleAuthenticateIncomingMetadata( "be provided") } + recipientsByIndex := make( + map[uint32]ArkRecipientOutput, len(msg.Recipients), + ) + for i := range msg.Recipients { + recipientsByIndex[msg.Recipients[i].OutputIndex] = msg. + Recipients[i] + } + matches := make([]IncomingMetadataMatch, len(msg.Matches)) copy(matches, msg.Matches) for i := range matches { @@ -215,6 +270,49 @@ func (h *LocalPersistenceOutboxHandler) handleAuthenticateIncomingMetadata( matches[i].Metadata.CreatedHeight = evidence.EarliestCommitmentHeight matches[i].Metadata.ExpiryAuthenticated = true + + recipient, hasRecipient := recipientsByIndex[matches[i]. + OutputIndex] + if !hasRecipient || recipient.Asset == nil { + continue + } + + if h.VerifyIncomingAssetPackage == nil { + return nil, &terminalOutboxError{ + cause: fmt.Errorf("incoming asset output %d "+ + "requires an asset package verifier", + recipient.OutputIndex), + } + } + if msg.TaprootAssetTransfer == nil || + len(msg.TaprootAssetTransfer.ArkPackage) == 0 { + return nil, &terminalOutboxError{ + cause: fmt.Errorf("incoming asset output %d "+ + "missing sealed ark asset package", + recipient.OutputIndex), + } + } + + err = h.VerifyIncomingAssetPackage( + ctx, IncomingAssetVerification{ + SessionID: msg.SessionID, + Recipient: recipient, + ArkPSBT: msg.ArkPSBT, + FinalCheckpointPSBTs: msg.FinalCheckpointPSBTs, + AncestorPackages: msg.AncestorPackages, + Metadata: matches[i].Metadata, + TaprootAssetTransfer: msg.TaprootAssetTransfer, + }, + ) + if err != nil { + if errors.Is(err, ErrInvalidIncomingAssetPackage) { + return nil, &terminalOutboxError{cause: err} + } + + return nil, err + } + + matches[i].Metadata.AssetVerified = true } return []Event{&IncomingMetadataResolvedEvent{ @@ -527,6 +625,13 @@ func (h *LocalPersistenceOutboxHandler) materializeIncoming(ctx context.Context, "incoming output %d", recipient.OutputIndex) } + sealedAssetPackage, err := h.ensureIncomingAssetVerified( + ctx, msg, recipient, &metadata, + ) + if err != nil { + return nil, err + } + desc, err := BuildIncomingVTXODescriptor(msg.ArkPSBT, IncomingVTXOConfig{ OutputIndex: recipient.OutputIndex, @@ -535,7 +640,9 @@ func (h *LocalPersistenceOutboxHandler) materializeIncoming(ctx context.Context, ExitDelay: h.ExitDelay, PolicyTemplate: recipient. VTXOPolicyTemplate, - Metadata: metadata, + Metadata: metadata, + Asset: recipient.Asset, + TaprootAssetSealedPackage: sealedAssetPackage, }, ) if err != nil { @@ -561,6 +668,10 @@ func (h *LocalPersistenceOutboxHandler) materializeIncoming(ctx context.Context, return nil, err } + if !descriptorsMatchAssetState(existing, desc) { + return nil, err + } + desc = existing } @@ -736,5 +847,88 @@ func (h *LocalPersistenceOutboxHandler) handleIncomingAck(ctx context.Context, return followUps, nil } +// ensureIncomingAssetVerified verifies an asset-bearing incoming output's +// sealed Ark package before materialization and returns the sealed package +// bytes. Plain Bitcoin outputs return nil, nil. +func (h *LocalPersistenceOutboxHandler) ensureIncomingAssetVerified( + ctx context.Context, msg *MaterializeIncomingVTXOsRequest, + recipient ArkRecipientOutput, metadata *IncomingVTXOMetadata) ([]byte, + error) { + + if recipient.Asset == nil { + return nil, nil + } + + if msg.TaprootAssetTransfer == nil || + len(msg.TaprootAssetTransfer.ArkPackage) == 0 { + return nil, &terminalOutboxError{ + cause: fmt.Errorf("incoming asset output %d missing "+ + "sealed ark asset package", + recipient.OutputIndex), + } + } + + if metadata.AssetVerified { + return msg.TaprootAssetTransfer.ArkPackage, nil + } + + if hasActorDBTx(ctx) { + return nil, fmt.Errorf("incoming asset output %d package was "+ + "not verified before materialization", + recipient.OutputIndex) + } + if h.VerifyIncomingAssetPackage == nil { + return nil, &terminalOutboxError{ + cause: fmt.Errorf("incoming asset output %d requires "+ + "an asset package verifier", + recipient.OutputIndex), + } + } + + verifyErr := h.VerifyIncomingAssetPackage( + ctx, IncomingAssetVerification{ + SessionID: msg.SessionID, + Recipient: recipient, + ArkPSBT: msg.ArkPSBT, + FinalCheckpointPSBTs: msg.FinalCheckpointPSBTs, + AncestorPackages: msg.AncestorPackages, + Metadata: *metadata, + TaprootAssetTransfer: msg.TaprootAssetTransfer, + }, + ) + if verifyErr != nil { + if errors.Is(verifyErr, ErrInvalidIncomingAssetPackage) { + return nil, &terminalOutboxError{ + cause: verifyErr, + } + } + + return nil, verifyErr + } + metadata.AssetVerified = true + + return msg.TaprootAssetTransfer.ArkPackage, nil +} + +// descriptorsMatchAssetState reports whether two descriptors carry identical +// Taproot Asset state so duplicate-save idempotency checks fail closed on any +// mismatch. +func descriptorsMatchAssetState(a, b *vtxo.Descriptor) bool { + if (a.TaprootAssetRoot == nil) != (b.TaprootAssetRoot == nil) { + return false + } + if a.TaprootAssetRoot != nil && + *a.TaprootAssetRoot != *b.TaprootAssetRoot { + return false + } + + return a.TaprootAssetRef == b.TaprootAssetRef && + a.TaprootAssetAmount == b.TaprootAssetAmount && + bytes.Equal( + a.TaprootAssetSealedPackage, + b.TaprootAssetSealedPackage, + ) +} + var _ OutboxHandler = (*LocalPersistenceOutboxHandler)(nil) var _ IncomingMetadataRecipientFilter = (*LocalPersistenceOutboxHandler)(nil) diff --git a/oor/outbox_messages.go b/oor/outbox_messages.go index 44d8bc8a5..c8601aff5 100644 --- a/oor/outbox_messages.go +++ b/oor/outbox_messages.go @@ -443,13 +443,36 @@ func (m *QueryIncomingMetadataRequest) outboxType() string { // outboxSealed marks this as implementing the sealed OutboxEvent interface. func (m *QueryIncomingMetadataRequest) outboxSealed() {} -// AuthenticateIncomingMetadataRequest asks the local chain boundary to -// replace indexer expiry hints with authenticated absolute expiries before +// AuthenticateIncomingMetadataRequest asks the local chain and asset +// verification boundary to replace indexer expiry hints with authenticated +// absolute expiries and verify any incoming Taproot Asset package before // materialization enters the durable database transaction. type AuthenticateIncomingMetadataRequest struct { actor.BaseMessage + // SessionID identifies the incoming transfer session. + SessionID SessionID + + // Matches carries the resolved incoming VTXO metadata per output. Matches []IncomingMetadataMatch + + // ArkPSBT is the canonical Ark transaction PSBT for this transfer. + ArkPSBT *psbt.Packet + + // FinalCheckpointPSBTs are the finalized checkpoint PSBTs for this + // transfer. + FinalCheckpointPSBTs []*psbt.Packet + + // AncestorPackages are finalized prior OOR packages for this transfer. + AncestorPackages []PackageArtifact + + // Recipients are the Ark outputs with optional policy and asset + // metadata. + Recipients []ArkRecipientOutput + + // TaprootAssetTransfer carries the sealed Taproot Asset packages when + // this transfer creates an asset VTXO. + TaprootAssetTransfer *oortx.TaprootAssetTransfer } // outboxType returns a stable identifier for this outbox message. @@ -491,6 +514,10 @@ type MaterializeIncomingVTXOsRequest struct { // AncestorPackages are finalized OOR packages needed to unroll the // incoming VTXO's OOR parent chain. AncestorPackages []PackageArtifact + + // TaprootAssetTransfer carries the sealed Taproot Asset packages when + // this transfer creates an asset VTXO. + TaprootAssetTransfer *oortx.TaprootAssetTransfer } // outboxType returns a stable identifier for this outbox message. diff --git a/oor/receive_snapshot.go b/oor/receive_snapshot.go index 2f6767921..4d37d96a7 100644 --- a/oor/receive_snapshot.go +++ b/oor/receive_snapshot.go @@ -2,10 +2,12 @@ package oor import ( "context" + "encoding/binary" "fmt" "github.com/btcsuite/btcd/psbt/v2" "github.com/lightninglabs/wavelength/baselib/tlvutil" + oortx "github.com/lightninglabs/wavelength/lib/tx/oor" "github.com/lightninglabs/wavelength/lib/tx/psbtutil" "github.com/lightningnetwork/lnd/tlv" ) @@ -23,6 +25,8 @@ const ( incomingSnapshotMetadataAttemptsType tlv.Type = 19 incomingSnapshotResolveAttemptsType tlv.Type = 21 incomingSnapshotRecipientsType tlv.Type = 23 + incomingSnapshotTaprootAssetTransferType tlv.Type = 25 + incomingSnapshotCompletedEventIDsType tlv.Type = 27 ) // IncomingPhase identifies the coarse stage of an incoming OOR receive @@ -81,6 +85,10 @@ type IncomingSnapshot struct { // metadata needed to materialize custom incoming VTXOs. Recipients []ArkRecipientOutput + // TaprootAssetTransfer carries the sealed Taproot Asset packages for an + // incoming asset OOR transfer while materialization is pending. + TaprootAssetTransfer *oortx.TaprootAssetTransfer + // FailReason is the terminal failure reason, when Phase is Failed. FailReason string @@ -89,9 +97,14 @@ type IncomingSnapshot struct { RecipientPkScript []byte // RecipientEventID is the per-script cursor hint paired with - // RecipientPkScript during resolve-pending restart. + // RecipientPkScript during resolve-pending restart and carried through + // ReceiveNotified/ReceiveAwaitingAck until ReceiveCompleted records it. RecipientEventID uint64 + // CompletedEventIDs records recipient event IDs already processed by + // this session across sequential receive passes. + CompletedEventIDs []uint64 + // MetadataAttempts is the persisted retry count for the authoritative // metadata resolution, used to bound backoff and the terminal give-up // across restarts. Only meaningful in the materialize-pending phase. @@ -128,6 +141,9 @@ func NewIncomingSnapshot(sessionID SessionID, []byte(nil), s.RecipientPkScript..., ) snap.RecipientEventID = s.RecipientEventID + snap.CompletedEventIDs = append( + []uint64(nil), s.CompletedEventIDs..., + ) snap.ResolveAttempts = s.ResolveAttempts case *ReceiveNotified: @@ -150,13 +166,25 @@ func NewIncomingSnapshot(sessionID SessionID, []PackageArtifact(nil), s.AncestorPackages..., ) snap.Recipients = CloneArkRecipients(s.Recipients) + snap.TaprootAssetTransfer = s.TaprootAssetTransfer.Clone() + snap.RecipientEventID = s.RecipientEventID + snap.CompletedEventIDs = append( + []uint64(nil), s.CompletedEventIDs..., + ) snap.MetadataAttempts = s.MetadataAttempts case *ReceiveAwaitingAck: snap.Phase = IncomingPhaseAckPending + snap.RecipientEventID = s.RecipientEventID + snap.CompletedEventIDs = append( + []uint64(nil), s.CompletedEventIDs..., + ) case *ReceiveCompleted: snap.Phase = IncomingPhaseCompleted + snap.CompletedEventIDs = append( + []uint64(nil), s.CompletedEventIDs..., + ) case *Failed: snap.Phase = IncomingPhaseFailed @@ -215,7 +243,10 @@ func IncomingStateFromSnapshot(snapshot *IncomingSnapshot) (SessionState, []byte(nil), snapshot.RecipientPkScript..., ), RecipientEventID: snapshot.RecipientEventID, - ResolveAttempts: snapshot.ResolveAttempts, + CompletedEventIDs: append( + []uint64(nil), snapshot.CompletedEventIDs..., + ), + ResolveAttempts: snapshot.ResolveAttempts, }, nil case IncomingPhaseMaterializePending: @@ -242,16 +273,30 @@ func IncomingStateFromSnapshot(snapshot *IncomingSnapshot) (SessionState, Recipients: CloneArkRecipients( snapshot.Recipients, ), + TaprootAssetTransfer: snapshot.TaprootAssetTransfer. + Clone(), + RecipientEventID: snapshot.RecipientEventID, + CompletedEventIDs: append( + []uint64(nil), snapshot.CompletedEventIDs..., + ), MetadataAttempts: snapshot.MetadataAttempts, }, nil case IncomingPhaseAckPending: return &ReceiveAwaitingAck{ - SessionID: snapshot.SessionID, + SessionID: snapshot.SessionID, + RecipientEventID: snapshot.RecipientEventID, + CompletedEventIDs: append( + []uint64(nil), snapshot.CompletedEventIDs..., + ), }, nil case IncomingPhaseCompleted: - return &ReceiveCompleted{}, nil + return &ReceiveCompleted{ + CompletedEventIDs: append( + []uint64(nil), snapshot.CompletedEventIDs..., + ), + }, nil case IncomingPhaseFailed: return &Failed{Reason: snapshot.FailReason}, nil @@ -293,6 +338,16 @@ func encodeIncomingSnapshot(snapshot *IncomingSnapshot) ([]byte, error) { return nil, err } + var assetTransferRaw []byte + if snapshot.TaprootAssetTransfer != nil { + assetTransferRaw, err = snapshot.TaprootAssetTransfer. + MarshalBinary() + if err != nil { + return nil, fmt.Errorf("encode incoming snapshot "+ + "taproot asset transfer: %w", err) + } + } + metadataAttempts := uint64(snapshot.MetadataAttempts) resolveAttempts := uint64(snapshot.ResolveAttempts) version := uint64(snapshot.Version) @@ -336,6 +391,23 @@ func encodeIncomingSnapshot(snapshot *IncomingSnapshot) ([]byte, error) { incomingSnapshotRecipientsType, &recipients, ), } + if len(assetTransferRaw) > 0 { + records = append( + records, tlv.MakePrimitiveRecord( + incomingSnapshotTaprootAssetTransferType, + &assetTransferRaw, + ), + ) + } + if len(snapshot.CompletedEventIDs) > 0 { + completedIDsRaw := encodeUint64List(snapshot.CompletedEventIDs) + records = append( + records, tlv.MakePrimitiveRecord( + incomingSnapshotCompletedEventIDsType, + &completedIDsRaw, + ), + ) + } return tlvutil.EncodeRecordsToBytes(records...) } @@ -358,6 +430,8 @@ func decodeIncomingSnapshotWithLimits(raw []byte, metadataAttempts uint64 resolveAttempts uint64 recipientsRaw []byte + assetTransferRaw []byte + completedIDsRaw []byte ) records := []tlv.Record{ @@ -399,6 +473,13 @@ func decodeIncomingSnapshotWithLimits(raw []byte, tlv.MakePrimitiveRecord( incomingSnapshotRecipientsType, &recipientsRaw, ), + tlv.MakePrimitiveRecord( + incomingSnapshotTaprootAssetTransferType, + &assetTransferRaw, + ), + tlv.MakePrimitiveRecord( + incomingSnapshotCompletedEventIDsType, &completedIDsRaw, + ), } if _, err := decodeBoundedRecords( @@ -440,6 +521,30 @@ func decodeIncomingSnapshotWithLimits(raw []byte, return nil, err } + var decodedAssetTransfer *oortx.TaprootAssetTransfer + if len(assetTransferRaw) > 0 { + var transfer oortx.TaprootAssetTransfer + if err := transfer.UnmarshalBinary( + assetTransferRaw, + ); err != nil { + return nil, fmt.Errorf("decode incoming snapshot "+ + "taproot asset transfer: %w", err) + } + if err := transfer.Validate(len(checkpoints)); err != nil { + return nil, fmt.Errorf("validate incoming snapshot "+ + "taproot asset transfer: %w", err) + } + decodedAssetTransfer = &transfer + } + + completedEventIDs, err := decodeUint64List( + completedIDsRaw, maxCompletedIncomingEventIDs, + ) + if err != nil { + return nil, fmt.Errorf("decode incoming snapshot completed "+ + "event ids: %w", err) + } + decodedVersion, err := decodeUint64ToUint8( version, "incoming snapshot version", ) @@ -456,17 +561,51 @@ func decodeIncomingSnapshotWithLimits(raw []byte, AncestorPackages: append( []PackageArtifact(nil), decodedPackages..., ), - Recipients: CloneArkRecipients(decodedRecipients), - FailReason: string(failReasonRaw), + Recipients: CloneArkRecipients(decodedRecipients), + TaprootAssetTransfer: decodedAssetTransfer, + FailReason: string(failReasonRaw), RecipientPkScript: append( []byte(nil), recipientPkScript..., ), - RecipientEventID: recipientEventID, - MetadataAttempts: uint32(metadataAttempts), - ResolveAttempts: uint32(resolveAttempts), + RecipientEventID: recipientEventID, + CompletedEventIDs: completedEventIDs, + MetadataAttempts: uint32(metadataAttempts), + ResolveAttempts: uint32(resolveAttempts), }, nil } +// encodeUint64List encodes a slice of uint64 values as big-endian 8-byte words. +func encodeUint64List(ids []uint64) []byte { + out := make([]byte, len(ids)*8) + for i, id := range ids { + binary.BigEndian.PutUint64(out[i*8:(i+1)*8], id) + } + + return out +} + +// decodeUint64List decodes big-endian 8-byte words into a bounded uint64 slice. +func decodeUint64List(raw []byte, maxCount int) ([]uint64, error) { + if len(raw) == 0 { + return nil, nil + } + if len(raw)%8 != 0 { + return nil, fmt.Errorf("byte length %d is not a multiple of 8", + len(raw)) + } + count := len(raw) / 8 + if maxCount > 0 && count > maxCount { + return nil, fmt.Errorf("count %d exceeds limit %d", count, + maxCount) + } + out := make([]uint64, count) + for i := range count { + out[i] = binary.BigEndian.Uint64(raw[i*8 : (i+1)*8]) + } + + return out, nil +} + // parseIncomingPSBTs parses the Ark and checkpoint PSBTs stored in an incoming // snapshot. func parseIncomingPSBTs(arkRaw []byte, checkpointRaws [][]byte) (*psbt.Packet, diff --git a/oor/receive_states.go b/oor/receive_states.go index 7ace70ca5..d9b72ed8a 100644 --- a/oor/receive_states.go +++ b/oor/receive_states.go @@ -3,6 +3,7 @@ package oor import ( "github.com/btcsuite/btcd/psbt/v2" "github.com/lightninglabs/wavelength/baselib/protofsm" + oortx "github.com/lightninglabs/wavelength/lib/tx/oor" ) // ReceiveState is a sealed interface for all states in the incoming transfer @@ -16,6 +17,12 @@ type ReceiveState interface { receiveStateSealed() } +// maxCompletedIncomingEventIDs bounds how many distinct recipient event IDs a +// single incoming OOR session will track and replay across sequential passes +// (for example, a sender receiving both an asset change output and a Bitcoin +// carrier-return output in the same OOR transfer). +const maxCompletedIncomingEventIDs = 64 + // ReceiveResolving indicates the client durably recorded a lightweight // incoming-transfer hint and still needs to fetch the full Ark/checkpoint // package outside the live durable actor transaction. @@ -26,6 +33,10 @@ type ReceiveResolving struct { RecipientEventID uint64 + // CompletedEventIDs carries recipient event IDs already completed by + // earlier receive passes for this session so they remain idempotent. + CompletedEventIDs []uint64 + // ResolveAttempts counts how many times the phase-1 hint resolution has // been re-issued for this session without a response. It drives the // exponential backoff and the terminal give-up in handleResolveRetry, @@ -77,6 +88,19 @@ type ReceiveNotified struct { // semantic policy metadata needed to materialize custom VTXOs. Recipients []ArkRecipientOutput + // TaprootAssetTransfer carries the sealed Taproot Asset transition + // packages for an incoming asset OOR transfer until materialization + // verifies and persists the Ark package on the received VTXO. + TaprootAssetTransfer *oortx.TaprootAssetTransfer + + // RecipientEventID identifies the recipient event currently being + // processed by this receive pass (zero for direct/legacy transitions). + RecipientEventID uint64 + + // CompletedEventIDs carries recipient event IDs already completed by + // earlier receive passes for this session. + CompletedEventIDs []uint64 + // MetadataAttempts counts how many times the authoritative metadata // resolution has failed retryably for this session. It drives the // exponential backoff and terminal give-up in handleReceiveOutboxError @@ -101,6 +125,14 @@ func (s *ReceiveNotified) receiveStateSealed() {} // client is waiting for ack transport completion. type ReceiveAwaitingAck struct { SessionID SessionID + + // RecipientEventID identifies the recipient event whose outputs were + // just materialized. + RecipientEventID uint64 + + // CompletedEventIDs carries recipient event IDs already completed by + // earlier receive passes for this session. + CompletedEventIDs []uint64 } // String returns a human-readable representation of ReceiveAwaitingAck. @@ -117,7 +149,27 @@ func (s *ReceiveAwaitingAck) IsTerminal() bool { func (s *ReceiveAwaitingAck) receiveStateSealed() {} // ReceiveCompleted is the terminal success state for an incoming transfer. -type ReceiveCompleted struct{} +type ReceiveCompleted struct { + // CompletedEventIDs records the recipient event IDs processed by this + // session so distinct owned outputs (such as asset change plus Bitcoin + // carrier return) can each run a receive pass while duplicate pushes + // stay idempotent. + CompletedEventIDs []uint64 +} + +// HasEventID reports whether eventID has already completed on this session. +func (s *ReceiveCompleted) HasEventID(eventID uint64) bool { + if s == nil || eventID == 0 { + return false + } + for _, id := range s.CompletedEventIDs { + if id == eventID { + return true + } + } + + return false +} // String returns a human-readable representation of ReceiveCompleted. func (s *ReceiveCompleted) String() string { @@ -131,3 +183,37 @@ func (s *ReceiveCompleted) IsTerminal() bool { // receiveStateSealed marks ReceiveCompleted as implementing ReceiveState. func (s *ReceiveCompleted) receiveStateSealed() {} + +// appendCompletedEventID returns a defensive copy of existing with eventID +// appended when eventID is non-zero and not already present. +func appendCompletedEventID(existing []uint64, eventID uint64) []uint64 { + out := append([]uint64(nil), existing...) + if eventID == 0 { + return out + } + for _, id := range out { + if id == eventID { + return out + } + } + + return append(out, eventID) +} + +// activeIncomingEventID returns the recipient event ID being processed by a +// non-terminal incoming receive state, or zero when unset. +func activeIncomingEventID(state SessionState) uint64 { + switch s := state.(type) { + case *ReceiveResolving: + return s.RecipientEventID + + case *ReceiveNotified: + return s.RecipientEventID + + case *ReceiveAwaitingAck: + return s.RecipientEventID + + default: + return 0 + } +} diff --git a/oor/receive_transitions.go b/oor/receive_transitions.go index 53f67d97f..2fc1a4cca 100644 --- a/oor/receive_transitions.go +++ b/oor/receive_transitions.go @@ -166,25 +166,30 @@ func handleNotifiedTimerRetry(state *ReceiveNotified) *StateTransition { return giveUp } - // Re-extract recipients to rebuild the query. The Ark PSBT was already - // validated on entry to ReceiveNotified, so this cannot fail here; on - // the off chance it does, still re-arm the give-up timer so the session - // keeps moving toward the terminal give-up. - recipients, err := ExtractArkRecipients(state.ArkPSBT) - if err != nil { - return &StateTransition{ - NextState: next, - NewEvents: fn.Some(EmittedEvent{ - Outbox: []OutboxEvent{ - &ScheduleRetryRequest{ - After: metadataRetryBackoff( - next.MetadataAttempts, - ), - Reason: notifiedGiveUpReason, - }, - }, - }), + // Preserve the policy and optional asset metadata stored on state; fall + // back to structural extraction only for legacy snapshots without + // persisted recipients. + recipients := CloneArkRecipients(state.Recipients) + if len(recipients) == 0 { + extracted, err := ExtractArkRecipients(state.ArkPSBT) + if err != nil { + retryAfter := metadataRetryBackoff( + next.MetadataAttempts, + ) + retryReq := &ScheduleRetryRequest{ + After: retryAfter, + Reason: notifiedGiveUpReason, + } + + return &StateTransition{ + NextState: next, + NewEvents: fn.Some(EmittedEvent{ + Outbox: []OutboxEvent{retryReq}, + }), + } } + + recipients = extracted } return &StateTransition{ @@ -239,8 +244,9 @@ func waitsOnGiveUpTimer(state SessionState) bool { // transitionIncomingTransfer validates and applies a fully resolved incoming // transfer event, moving the receive FSM into the notified/materialize phase. -func transitionIncomingTransfer(evt *IncomingTransferEvent) (*StateTransition, - error) { +func transitionIncomingTransfer(evt *IncomingTransferEvent, + recipientEventID uint64, + completedEventIDs []uint64) (*StateTransition, error) { if evt.ArkPSBT == nil || evt.ArkPSBT.UnsignedTx == nil { return nil, fmt.Errorf("ark psbt must be provided") @@ -278,6 +284,11 @@ func transitionIncomingTransfer(evt *IncomingTransferEvent) (*StateTransition, FinalCheckpointPSBTs: evt.FinalCheckpointPSBTs, AncestorPackages: evt.AncestorPackages, Recipients: recipients, + TaprootAssetTransfer: evt.TaprootAssetTransfer.Clone(), + RecipientEventID: recipientEventID, + CompletedEventIDs: append( + []uint64(nil), completedEventIDs..., + ), } // The metadata query (like the phase-1 hint query) has no failure @@ -312,7 +323,7 @@ func (s *ReceiveIdle) ProcessEvent(ctx context.Context, event Event, switch evt := event.(type) { case *IncomingTransferEvent: - return transitionIncomingTransfer(evt) + return transitionIncomingTransfer(evt, 0, nil) case *FailEvent: return &StateTransition{ @@ -341,7 +352,9 @@ func (s *ReceiveResolving) ProcessEvent(ctx context.Context, event Event, switch evt := event.(type) { case *IncomingTransferEvent: - return transitionIncomingTransfer(evt) + return transitionIncomingTransfer( + evt, s.RecipientEventID, s.CompletedEventIDs, + ) case *RetryDueEvent: return handleResolveRetry(s), nil @@ -462,9 +475,26 @@ func (s *ReceiveNotified) ProcessEvent(ctx context.Context, event Event, switch evt := event.(type) { case *IncomingMetadataResolvedEvent: + recipients := CloneArkRecipients(s.Recipients) + if len(recipients) == 0 { + extracted, err := ExtractArkRecipients(s.ArkPSBT) + if err != nil { + return nil, err + } + + recipients = extracted + } + if !evt.ExpiryAuthenticated { authenticate := &AuthenticateIncomingMetadataRequest{ - Matches: evt.Matches, + SessionID: s.SessionID, + Matches: evt.Matches, + ArkPSBT: s.ArkPSBT, + FinalCheckpointPSBTs: s.FinalCheckpointPSBTs, + AncestorPackages: s.AncestorPackages, + Recipients: recipients, + TaprootAssetTransfer: s.TaprootAssetTransfer. + Clone(), } return &StateTransition{ @@ -477,16 +507,6 @@ func (s *ReceiveNotified) ProcessEvent(ctx context.Context, event Event, }, nil } - recipients := CloneArkRecipients(s.Recipients) - if len(recipients) == 0 { - extracted, err := ExtractArkRecipients(s.ArkPSBT) - if err != nil { - return nil, err - } - - recipients = extracted - } - return &StateTransition{ NextState: s, NewEvents: fn.Some(EmittedEvent{ @@ -500,6 +520,9 @@ func (s *ReceiveNotified) ProcessEvent(ctx context.Context, event Event, MetadataMatches: evt.Matches, AncestorPackages: s. AncestorPackages, + TaprootAssetTransfer: s. + TaprootAssetTransfer. + Clone(), }, }, }), @@ -514,7 +537,11 @@ func (s *ReceiveNotified) ProcessEvent(ctx context.Context, event Event, return &StateTransition{ NextState: &ReceiveAwaitingAck{ - SessionID: s.SessionID, + SessionID: s.SessionID, + RecipientEventID: s.RecipientEventID, + CompletedEventIDs: append( + []uint64(nil), s.CompletedEventIDs..., + ), }, NewEvents: fn.Some(EmittedEvent{ Outbox: []OutboxEvent{ @@ -580,7 +607,11 @@ func (s *ReceiveAwaitingAck) ProcessEvent(ctx context.Context, event Event, _ = evt return &StateTransition{ - NextState: &ReceiveCompleted{}, + NextState: &ReceiveCompleted{ + CompletedEventIDs: appendCompletedEventID( + s.CompletedEventIDs, s.RecipientEventID, + ), + }, NewEvents: fn.None[EmittedEvent](), }, nil diff --git a/oor/registry.go b/oor/registry.go index a012b310d..b7a6cd149 100644 --- a/oor/registry.go +++ b/oor/registry.go @@ -40,6 +40,14 @@ var errIncomingAdmissionCapped = errors.New("incoming OOR admission " + var errSelfTransferDeferred = errors.New("outgoing session still active for " + "incoming hint") +// errIncomingSessionBusy is returned when an incoming hint for a distinct +// recipient event arrives while the same session is already resolving another +// owned output (for example, an asset change output and a Bitcoin carrier- +// return output in the same OOR transfer). The registry parks the hint and +// redrives it as soon as the active receive pass completes and reaps. +var errIncomingSessionBusy = errors.New("incoming session busy resolving " + + "another recipient event") + // ErrOutgoingAdmissionExpired is returned when a new outgoing transfer reaches // the durable admission boundary at or after its caller-supplied deadline. // Existing keyed winners are looked up before this check and remain readable. @@ -314,9 +322,10 @@ func NewOORRegistryActor(cfg OORRegistryConfig) (*OORRegistryActor, error) { map[SessionID]clientdb.OORSessionDirection, ), incoming: make(map[SessionID]struct{}), + activeIncomingEvent: make(map[SessionID]uint64), pendingOutgoingKeys: make(map[string]SessionID), parkedSelfHints: make( - map[SessionID]*ResolveIncomingTransferRequest, + map[SessionID][]*ResolveIncomingTransferRequest, ), } behavior.spawnFunc = behavior.spawn @@ -423,16 +432,17 @@ type oorRegistryBehavior struct { spawnFunc func(SessionID, clientdb.OORSessionDirection) ( *OORSessionActor, error) - // parkedSelfHints holds incoming self-transfer hints deferred because - // their session is still active as outgoing, keyed by session id so a - // repeated hint overwrites rather than accumulates. Entries are - // redriven (self-Tell) when the outgoing session's terminal - // notification reaps the child, and dropped when an admission for the - // session succeeds. The map is bounded by the number of live outgoing - // sessions: parking requires a non-terminal outgoing row in the - // durable store, so fabricated hints cannot grow it. Registry- - // goroutine-owned like active and incoming. - parkedSelfHints map[SessionID]*ResolveIncomingTransferRequest + // activeIncomingEvent tracks the RecipientEventID currently being + // driven by each resident incoming session child, so a distinct + // recipient event for the same session can be parked and immediately + // redriven when the active pass completes and reaps. + activeIncomingEvent map[SessionID]uint64 + + // parkedSelfHints holds incoming hints deferred because their session + // is still active as outgoing or currently resolving another owned + // output of the same session. Entries are deduped by RecipientEventID, + // capped per session, and popped in order when the active child reaps. + parkedSelfHints map[SessionID][]*ResolveIncomingTransferRequest // pendingHandoff carries an outgoing admission's child future from // dispatch to Receive, so the caller's promise is detached and the @@ -780,8 +790,8 @@ func (r *oorRegistryBehavior) handleStartTransfer(ctx context.Context, // immediately so its driveMachine goroutine does not linger for the // daemon's lifetime (one leak per outgoing admission otherwise). session, _, err := newSessionWithDispatchRequest( - ctx, req.Policy, req.Inputs, req.Recipients, req.IdempotencyKey, - req.DispatchRequestData, r.envConfig(), + ctx, req.Policy, req.Inputs, req.Recipients, req.PreparedSubmit, + req.IdempotencyKey, req.DispatchRequestData, r.envConfig(), ) if err != nil { return fn.Err[ActorResp](err) @@ -1239,12 +1249,31 @@ func (r *oorRegistryBehavior) handleResolveIncoming(ctx context.Context, return fn.Err[ActorResp](err) } - // Any parked copy of this hint is now superseded by the admission - // below (a redriven or redelivered duplicate forwards idempotently to - // the resident session). - delete(r.parkedSelfHints, req.SessionID) - _, existed := r.active[req.SessionID] + if existed && + r.activeDirs[req.SessionID] == + clientdb.OORSessionDirectionIncoming && + req.RecipientEventID > 0 { + + activeID := r.activeIncomingEvent[req.SessionID] + if activeID > 0 && activeID != req.RecipientEventID { + r.parkSelfHint(req) + + return fn.Err[ActorResp]( + fmt.Errorf( + "%w: %w", errIncomingSessionBusy, + actor.Postpone( + selfHintRedeliveryBackoff, + ), + ), + ) + } + } + + // Remove any parked copy of this specific hint now that it is being + // admitted, while preserving any other distinct parked hints for the + // same session. + r.unparkSelfHint(req.SessionID, req.RecipientEventID) // Bound the number of resident incoming children one daemon admits at // once. A new admission past the cap is rejected before any child is @@ -1297,6 +1326,15 @@ func (r *oorRegistryBehavior) handleResolveIncoming(ctx context.Context, } if !existed { + if req.RecipientEventID > 0 { + if r.activeIncomingEvent == nil { + r.activeIncomingEvent = make( + map[SessionID]uint64, + ) + } + r.activeIncomingEvent[req.SessionID] = req. + RecipientEventID + } r.logger(ctx).InfoS(ctx, "Admitting incoming OOR session", slog.String("session_id", req.SessionID.String()), slog.Uint64( @@ -1379,34 +1417,77 @@ func (r *oorRegistryBehavior) resolveSelfTransfer(ctx context.Context, return nil } -// parkSelfHint records a deferred self-transfer hint for the event-driven -// redrive at the outgoing session's terminal reap. Lazily initializes the map -// so directly constructed test behaviors stay valid. +// parkSelfHint records a deferred incoming hint for event-driven redrive at +// the active child's terminal reap. Distinct recipient events for the same +// session are preserved in FIFO order up to maxCompletedIncomingEventIDs so +// multi-output self-transfers (such as asset change plus Bitcoin carrier +// return) do not clobber one another. func (r *oorRegistryBehavior) parkSelfHint( req *ResolveIncomingTransferRequest) { if r.parkedSelfHints == nil { r.parkedSelfHints = make( - map[SessionID]*ResolveIncomingTransferRequest, + map[SessionID][]*ResolveIncomingTransferRequest, ) } - r.parkedSelfHints[req.SessionID] = req + queued := r.parkedSelfHints[req.SessionID] + for i := range queued { + if queued[i].RecipientEventID == req.RecipientEventID { + queued[i] = req + + return + } + } + if len(queued) >= maxCompletedIncomingEventIDs { + return + } + + r.parkedSelfHints[req.SessionID] = append(queued, req) +} + +// unparkSelfHint removes one parked hint matching recipientEventID from +// sessionID's queue, leaving any other distinct parked hints intact. +func (r *oorRegistryBehavior) unparkSelfHint(sessionID SessionID, + recipientEventID uint64) { + + queued := r.parkedSelfHints[sessionID] + if len(queued) == 0 { + return + } + + kept := queued[:0] + for _, h := range queued { + if h.RecipientEventID == recipientEventID { + continue + } + kept = append(kept, h) + } + if len(kept) == 0 { + delete(r.parkedSelfHints, sessionID) + + return + } + + r.parkedSelfHints[sessionID] = kept } -// redriveParkedSelfHint re-tells a parked self-transfer hint into the -// registry's own mailbox once its outgoing session has gone terminal. The -// hint's original durable delivery is still pending on the long self-transfer -// backoff, so a failed (or rolled-back) re-tell only costs latency, never the -// hint itself. +// redriveParkedSelfHint re-tells the next parked hint for sessionID into the +// registry's own mailbox once the active child has gone terminal. Any +// remaining distinct parked hints stay queued for subsequent terminal reaps. func (r *oorRegistryBehavior) redriveParkedSelfHint(ctx context.Context, sessionID SessionID) { - req, ok := r.parkedSelfHints[sessionID] - if !ok { + queued := r.parkedSelfHints[sessionID] + if len(queued) == 0 { return } - delete(r.parkedSelfHints, sessionID) + req := queued[0] + if len(queued) == 1 { + delete(r.parkedSelfHints, sessionID) + } else { + r.parkedSelfHints[sessionID] = queued[1:] + } if r.selfRef == nil { return @@ -1424,6 +1505,7 @@ func (r *oorRegistryBehavior) redriveParkedSelfHint(ctx context.Context, r.logger(ctx).DebugS(ctx, "Redrove parked self-transfer hint", slog.String("session_id", sessionID.String()), + slog.Uint64("recipient_event_id", req.RecipientEventID), ) } @@ -1870,6 +1952,7 @@ func (r *oorRegistryBehavior) dropChild(sessionID SessionID, delete(r.active, sessionID) delete(r.activeDirs, sessionID) delete(r.incoming, sessionID) + delete(r.activeIncomingEvent, sessionID) for key, pendingID := range r.pendingOutgoingKeys { if pendingID == sessionID { delete(r.pendingOutgoingKeys, key) diff --git a/oor/session.go b/oor/session.go index 9a2966ba0..5e0292f70 100644 --- a/oor/session.go +++ b/oor/session.go @@ -60,16 +60,16 @@ func NewSessionWithIdempotencyKey(ctx context.Context, } return newSessionWithDispatchRequest( - ctx, policy, inputs, outputs, idempotencyKey, + ctx, policy, inputs, outputs, nil, idempotencyKey, dispatchRequestData, envCfg, ) } func newSessionWithDispatchRequest(ctx context.Context, policy arkscript.CheckpointPolicy, inputs []TransferInput, - outputs []oortx.RecipientOutput, idempotencyKey string, - dispatchRequestData []byte, envCfg EnvConfig) (*Session, []OutboxEvent, - error) { + outputs []oortx.RecipientOutput, preparedSubmit *PreparedSubmitPackage, + idempotencyKey string, dispatchRequestData []byte, envCfg EnvConfig) ( + *Session, []OutboxEvent, error) { logger(ctx).DebugS(ctx, "Creating new OOR session", slog.Int("num_inputs", len(inputs)), @@ -97,6 +97,7 @@ func newSessionWithDispatchRequest(ctx context.Context, VTXOInputs: inputs, RecipientOutputs: outputs, Policy: policy, + PreparedSubmit: preparedSubmit, IdempotencyKey: idempotencyKey, DispatchRequestData: append( []byte(nil), dispatchRequestData..., diff --git a/oor/session_actor_handlers.go b/oor/session_actor_handlers.go index 1d14b6d7b..cb7aafd30 100644 --- a/oor/session_actor_handlers.go +++ b/oor/session_actor_handlers.go @@ -9,6 +9,7 @@ import ( "github.com/btcsuite/btcd/chainhash/v2" "github.com/btcsuite/btcd/wire/v2" + "github.com/lightninglabs/wavelength/baselib/actor" clientdb "github.com/lightninglabs/wavelength/db" "github.com/lightninglabs/wavelength/ledger" libtypes "github.com/lightninglabs/wavelength/lib/types" @@ -89,8 +90,8 @@ func (b *sessionBehavior) handleStartTransfer(ctx context.Context, } session, outbox, err := newSessionWithDispatchRequest( - ctx, req.Policy, req.Inputs, req.Recipients, req.IdempotencyKey, - req.DispatchRequestData, b.envConfig(), + ctx, req.Policy, req.Inputs, req.Recipients, req.PreparedSubmit, + req.IdempotencyKey, req.DispatchRequestData, b.envConfig(), ) if err != nil { return fn.Err[ActorResp](err) @@ -450,6 +451,8 @@ func (b *sessionBehavior) buildTransportMessage(ctx context.Context, } pkScripts := make([][]byte, 0, len(recipients)) + var signerScripts [][]byte + hasCustomSigner := false for i := range recipients { pkScripts = append( pkScripts, @@ -457,11 +460,31 @@ func (b *sessionBehavior) buildTransportMessage(ctx context.Context, []byte(nil), recipients[i].PkScript..., ), ) + if recipients[i].Asset != nil { + routingScript, err := recipients[i]. + RoutingPkScript() + if err != nil { + return nil, terminalOutboxErrorf( + "derive incoming asset "+ + "routing script for "+ + "output %d: %v", + recipients[i].OutputIndex, err, + ) + } + if !hasCustomSigner { + signerScripts = make( + [][]byte, len(recipients), + ) + hasCustomSigner = true + } + signerScripts[i] = routingScript + } } return &serverconn.SendListVTXOsByScriptsRequest{ - PkScripts: pkScripts, - Limit: b.cfg.Limits.MaxVTXOMatches, + PkScripts: pkScripts, + SignerScripts: signerScripts, + Limit: b.cfg.Limits.MaxVTXOMatches, CorrelationID: IncomingMetadataCorrelationID( queryReq.SessionID, ), @@ -553,10 +576,53 @@ func (b *sessionBehavior) handleResolveIncomingTransfer(ctx context.Context, ) } - // A duplicate hint for an already-admitted session is a no-op; the - // resolve query is already in flight or the session has progressed. + // Handle hints targeting an already-loaded incoming session: + // - While a pass is in flight for another recipient event of the + // same session, postpone so the new event runs once the current + // pass completes (rather than dropping it as a duplicate). + // - Once completed, allow a distinct new recipient event ID (such as + // asset change + Bitcoin carrier return in one transfer) to start a + // fresh ReceiveResolving pass while keeping previously completed + // event IDs and legacy completed snapshots idempotent. + var priorCompleted []uint64 if b.loaded && b.fsm != nil { - return fn.Ok[ActorResp](&DriveEventResponse{}) + curState, err := b.fsm.CurrentState() + if err != nil { + return fn.Err[ActorResp](err) + } + + completed, isCompleted := curState.(*ReceiveCompleted) + if !isCompleted { + activeID := activeIncomingEventID(curState) + if req.RecipientEventID > 0 && activeID > 0 && + activeID != req.RecipientEventID { + + postpone := actor.Postpone( + selfHintRedeliveryBackoff, + ) + + return fn.Err[ActorResp]( + fmt.Errorf("incoming session %s busy "+ + "with event %d: %w", + req.SessionID, activeID, + postpone), + ) + } + + return fn.Ok[ActorResp](&DriveEventResponse{}) + } + + if req.RecipientEventID == 0 || + len(completed.CompletedEventIDs) == 0 || + completed.HasEventID(req.RecipientEventID) || + len(completed.CompletedEventIDs) >= + maxCompletedIncomingEventIDs { + return fn.Ok[ActorResp](&DriveEventResponse{}) + } + + priorCompleted = append( + []uint64(nil), completed.CompletedEventIDs..., + ) } session, err := newReceiveSessionWithState( @@ -565,7 +631,8 @@ func (b *sessionBehavior) handleResolveIncomingTransfer(ctx context.Context, RecipientPkScript: append( []byte(nil), req.RecipientPkScript..., ), - RecipientEventID: req.RecipientEventID, + RecipientEventID: req.RecipientEventID, + CompletedEventIDs: priorCompleted, }, b.envConfig(), ) if err != nil { diff --git a/oor/transfer_input_snapshot.go b/oor/transfer_input_snapshot.go index 2f48768b8..b6c6efb84 100644 --- a/oor/transfer_input_snapshot.go +++ b/oor/transfer_input_snapshot.go @@ -235,46 +235,9 @@ func TransferInputFromSnapshot(snap *TransferInputSnapshot) (TransferInput, } if !snap.OperatorFunded { - clientPub, err := btcec.ParsePubKey(snap.ClientPubKey) + err := populateClientSnapshotDescriptor(desc, snap, operatorPub) if err != nil { - return TransferInput{}, fmt.Errorf("parse client "+ - "pubkey: %w", err) - } - - tapScript, err := arkscript.VTXOTapScript( - clientPub, operatorPub, snap.ExitDelay, - ) - if err != nil { - return TransferInput{}, fmt.Errorf("rebuild vtxo "+ - "tapscript: %w", err) - } - - tapKey, err := arkscript.VTXOTapKey( - clientPub, operatorPub, snap.ExitDelay, - ) - if err != nil { - return TransferInput{}, fmt.Errorf("rebuild vtxo "+ - "tapkey: %w", err) - } - - pkScript, err := txscript.PayToTaprootScript(tapKey) - if err != nil { - return TransferInput{}, fmt.Errorf("build vtxo "+ - "pkscript: %w", err) - } - - desc.ClientKey = keychain.KeyDescriptor{ - KeyLocator: keychain.KeyLocator{ - Family: keychain.KeyFamily( - snap.ClientKeyFamily, - ), - Index: snap.ClientKeyIndex, - }, - PubKey: clientPub, - } - desc.TapScript = tapScript - if len(desc.PkScript) == 0 { - desc.PkScript = pkScript + return TransferInput{}, err } } @@ -313,6 +276,57 @@ func TransferInputFromSnapshot(snap *TransferInputSnapshot) (TransferInput, return result, nil } +// populateClientSnapshotDescriptor restores the client key descriptor and, +// for non-asset inputs, the standard VTXO tapscript and fallback pkScript. +// Asset-bearing VTXOs intentionally keep TapScript nil so plain Bitcoin spend +// paths cannot derive an uncomposed control block. +func populateClientSnapshotDescriptor(desc *vtxo.Descriptor, + snap *TransferInputSnapshot, operatorPub *btcec.PublicKey) error { + + clientPub, err := btcec.ParsePubKey(snap.ClientPubKey) + if err != nil { + return fmt.Errorf("parse client pubkey: %w", err) + } + + desc.ClientKey = keychain.KeyDescriptor{ + KeyLocator: keychain.KeyLocator{ + Family: keychain.KeyFamily(snap.ClientKeyFamily), + Index: snap.ClientKeyIndex, + }, + PubKey: clientPub, + } + + if snap.TaprootAssetRoot != nil { + return nil + } + + tapScript, err := arkscript.VTXOTapScript( + clientPub, operatorPub, snap.ExitDelay, + ) + if err != nil { + return fmt.Errorf("rebuild vtxo tapscript: %w", err) + } + + tapKey, err := arkscript.VTXOTapKey( + clientPub, operatorPub, snap.ExitDelay, + ) + if err != nil { + return fmt.Errorf("rebuild vtxo tapkey: %w", err) + } + + pkScript, err := txscript.PayToTaprootScript(tapKey) + if err != nil { + return fmt.Errorf("build vtxo pkscript: %w", err) + } + + desc.TapScript = tapScript + if len(desc.PkScript) == 0 { + desc.PkScript = pkScript + } + + return nil +} + // cloneExternalSignatures deep-copies custom input external signatures. func cloneExternalSignatures( sigs []ExternalTaprootScriptSignature, diff --git a/oor/transfer_inputs.go b/oor/transfer_inputs.go index 8e655a08d..fc19d0928 100644 --- a/oor/transfer_inputs.go +++ b/oor/transfer_inputs.go @@ -134,7 +134,10 @@ func WalletInputOutpoints(inputs []TransferInput) []wire.OutPoint { // Validate performs basic structural validation. For custom spend // paths, the TapScript and ClientKey requirements are relaxed since -// the spend path carries its own signing context. For operator-funded +// the spend path carries its own signing context. For asset-bearing +// VTXOs, TapScript stays nil (the store omits plain uncomposed tapscripts +// for composed outputs) and EffectiveSpendPath derives the composed spend +// path from VTXOPolicyTemplate and TaprootAssetRoot. For operator-funded // float inputs, no local key material is carried and the lease must supply // the policy template, owner leaf policy, and operator key explicitly. func (i *TransferInput) Validate() error { @@ -152,7 +155,7 @@ func (i *TransferInput) Validate() error { return fmt.Errorf("vtxo pkScript must be provided") case !i.IsCustomSpend() && !i.OperatorFunded && - i.VTXO.TapScript == nil: + i.VTXO.TaprootAssetRoot == nil && i.VTXO.TapScript == nil: return fmt.Errorf("vtxo tapscript must be provided") case !i.IsCustomSpend() && !i.OperatorFunded && From f4eb3cddf7dd0380d0ff8551616532dba2beab56 Mon Sep 17 00:00:00 2001 From: Dario Anongba Varela Date: Thu, 26 Nov 2026 23:52:38 +0100 Subject: [PATCH 09/15] waved: implement SendAssetOOR RPC and incoming asset OOR wiring Implement daemon-only SendAssetOOR: validate allowlisted asset and operator carrier key, select and lock up to eight asset VTXOs, lease an operator carrier float via LeaseOORCarrier, plan carrier allocation (returning round-originated carriers as sender Bitcoin change), build the asset transition via tapassets.BuildOORTransfer, attach composed tapleaf scripts, and submit through the durable OOR registry. Wire incoming OOR asset verification onto the embedded asset engine, route composed asset outputs through uncomposed receive scripts for ownership lookup and signer-scoped indexer queries, and carry OORCarrierPubKey from GetInfo. --- waved/AGENTS.md | 17 + waved/CLAUDE.md | 17 + waved/asset_oor.go | 1138 ++++++++++++++++++++++++++++ waved/asset_oor_test.go | 431 +++++++++++ waved/incoming_metadata.go | 13 + waved/operator_negotiation.go | 13 + waved/operator_negotiation_test.go | 27 + waved/receive_script.go | 8 +- waved/receive_script_test.go | 78 ++ waved/rpc_auth.go | 4 +- waved/rpc_auth_test.go | 1 + waved/rpc_server.go | 5 + waved/server.go | 3 + waved/serverconn_builder.go | 37 + waved/wallet_recovery.go | 11 +- 15 files changed, 1797 insertions(+), 6 deletions(-) create mode 100644 waved/asset_oor.go create mode 100644 waved/asset_oor_test.go diff --git a/waved/AGENTS.md b/waved/AGENTS.md index 9b4e9dbb0..49c487650 100644 --- a/waved/AGENTS.md +++ b/waved/AGENTS.md @@ -771,3 +771,20 @@ even if intake requires foreground. It never reads receipts, starts pays or returns presentation proof. Zero references is ordinary maintenance. Hosts own selected-wallet enrollment independently of optional banners. See the existing background-window guide for legacy-reference and device acceptance limits. + +## Asset OOR transfers + +`RPCServer.SendAssetOOR` (daemon RPC only, guarded by `entityOOR:write`) sends +Taproot Assets out-of-round without exposing a CLI subcommand. It validates the +request and operator terms (asset admission + `OORCarrierPubKey`), reserves up +to `tapassets.MaxOORAssetInputs` live asset VTXOs via +`SelectAndLockAssetVTXOsRequest`, leases an operator carrier float via +authenticated `LeaseOORCarrier`, plans carrier allocation (`oortx.PlanAssetCarriers`), +builds the asset transitions on `s.assetClient` (`tapassets.BuildOORTransfer`) +against lineage-scoped input proof verifiers, attaches composed tapleaf scripts +onto `oor.PreparedSubmitPackage`, and hands it to `OORRegistryActor`. Incoming +asset OOR outputs resolve their signing key via uncomposed `RoutingPkScript()` +(`ResolveOwnedReceiveScriptKey` and `ScopedVTXOQueryBuilder`), verify the +sealed Ark package outside the actor DB transaction (`Server.verifyIncomingAssetOOR` +→ `tapassets.VTXOVerifier.VerifyOORAssetVTXO`), and persist `TaprootAssetSealedPackage` +on the materialized `vtxo.Descriptor` for unilateral claims and respends. diff --git a/waved/CLAUDE.md b/waved/CLAUDE.md index 9b4e9dbb0..49c487650 100644 --- a/waved/CLAUDE.md +++ b/waved/CLAUDE.md @@ -771,3 +771,20 @@ even if intake requires foreground. It never reads receipts, starts pays or returns presentation proof. Zero references is ordinary maintenance. Hosts own selected-wallet enrollment independently of optional banners. See the existing background-window guide for legacy-reference and device acceptance limits. + +## Asset OOR transfers + +`RPCServer.SendAssetOOR` (daemon RPC only, guarded by `entityOOR:write`) sends +Taproot Assets out-of-round without exposing a CLI subcommand. It validates the +request and operator terms (asset admission + `OORCarrierPubKey`), reserves up +to `tapassets.MaxOORAssetInputs` live asset VTXOs via +`SelectAndLockAssetVTXOsRequest`, leases an operator carrier float via +authenticated `LeaseOORCarrier`, plans carrier allocation (`oortx.PlanAssetCarriers`), +builds the asset transitions on `s.assetClient` (`tapassets.BuildOORTransfer`) +against lineage-scoped input proof verifiers, attaches composed tapleaf scripts +onto `oor.PreparedSubmitPackage`, and hands it to `OORRegistryActor`. Incoming +asset OOR outputs resolve their signing key via uncomposed `RoutingPkScript()` +(`ResolveOwnedReceiveScriptKey` and `ScopedVTXOQueryBuilder`), verify the +sealed Ark package outside the actor DB transaction (`Server.verifyIncomingAssetOOR` +→ `tapassets.VTXOVerifier.VerifyOORAssetVTXO`), and persist `TaprootAssetSealedPackage` +on the materialized `vtxo.Descriptor` for unilateral claims and respends. diff --git a/waved/asset_oor.go b/waved/asset_oor.go new file mode 100644 index 000000000..91a0ea76a --- /dev/null +++ b/waved/asset_oor.go @@ -0,0 +1,1138 @@ +package waved + +import ( + "bytes" + "context" + "crypto/rand" + "crypto/sha256" + "encoding/binary" + "errors" + "fmt" + "log/slog" + "math" + "time" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcec/v2/schnorr" + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/psbt/v2" + "github.com/btcsuite/btcd/wire/v2" + tapsdk "github.com/lightninglabs/tap-sdk" + "github.com/lightninglabs/tap-sdk/customanchor" + "github.com/lightninglabs/wavelength/arkrpc" + "github.com/lightninglabs/wavelength/baselib/actor" + "github.com/lightninglabs/wavelength/lib/arkscript" + oortx "github.com/lightninglabs/wavelength/lib/tx/oor" + "github.com/lightninglabs/wavelength/lib/types" + mailboxrpc "github.com/lightninglabs/wavelength/mailbox/rpc" + "github.com/lightninglabs/wavelength/metrics" + "github.com/lightninglabs/wavelength/oor" + "github.com/lightninglabs/wavelength/tapassets" + "github.com/lightninglabs/wavelength/vtxo" + "github.com/lightninglabs/wavelength/wallet" + "github.com/lightninglabs/wavelength/waverpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// verifyIncomingAssetOOR verifies one incoming Taproot Asset OOR output +// against the daemon's embedded asset engine and the output's authenticated +// Bitcoin lineage and OOR package chain before materialization stores its +// sealed Ark package. +func (s *Server) verifyIncomingAssetOOR(ctx context.Context, + req oor.IncomingAssetVerification) error { + + if s == nil || s.assetClient == nil || s.embeddedAssets == nil { + return fmt.Errorf("%w: Taproot Assets engine is not enabled", + oor.ErrInvalidIncomingAssetPackage) + } + if req.Recipient.Asset == nil { + return fmt.Errorf("%w: missing incoming recipient asset", + oor.ErrInvalidIncomingAssetPackage) + } + if req.ArkPSBT == nil || req.ArkPSBT.UnsignedTx == nil { + return fmt.Errorf("%w: missing incoming ark psbt", + oor.ErrInvalidIncomingAssetPackage) + } + if req.TaprootAssetTransfer == nil || + len(req.TaprootAssetTransfer.ArkPackage) == 0 { + return fmt.Errorf("%w: missing incoming sealed ark "+ + "asset package", oor.ErrInvalidIncomingAssetPackage) + } + + if err := trustAssetGroup( + s.embeddedAssets, req.Recipient.Asset.Ref, + ); err != nil { + return fmt.Errorf("%w: trust asset group: %w", + oor.ErrInvalidIncomingAssetPackage, err) + } + + chainVerifier, err := tapassets.NewLocalProofChainVerifier( + s.assetClient, + ) + if err != nil { + return fmt.Errorf("create proof chain verifier: %w", err) + } + vtxoVerifier, err := tapassets.NewVTXOVerifier(chainVerifier) + if err != nil { + return fmt.Errorf("create asset VTXO verifier: %w", err) + } + + lineage := lineageAnchorsFromAncestry(req.Metadata.Ancestry) + checkpointTxs, err := unsignedTxsFromPSBTs(req.FinalCheckpointPSBTs) + if err != nil { + return fmt.Errorf("%w: %w", oor.ErrInvalidIncomingAssetPackage, + err) + } + + ancestors := make( + []tapassets.OORPackageTxs, 0, len(req.AncestorPackages), + ) + for idx, pkg := range req.AncestorPackages { + if pkg.ArkPSBT == nil || pkg.ArkPSBT.UnsignedTx == nil { + return fmt.Errorf("%w: ancestor package %d "+ + "missing ark tx", + oor.ErrInvalidIncomingAssetPackage, idx) + } + ancCPs, err := unsignedTxsFromPSBTs(pkg.FinalCheckpointPSBTs) + if err != nil { + return fmt.Errorf("%w: ancestor package %d: %w", + oor.ErrInvalidIncomingAssetPackage, idx, err) + } + ancestors = append(ancestors, tapassets.OORPackageTxs{ + ArkTx: pkg.ArkPSBT.UnsignedTx, + CheckpointTxs: ancCPs, + }) + } + + arkTx := req.ArkPSBT.UnsignedTx + err = vtxoVerifier.VerifyOORAssetVTXO( + ctx, tapassets.VerifyOORAssetVTXORequest{ + AssetRef: req.Recipient.Asset.Ref, + AssetAmount: req.Recipient.Asset.Amount, + AssetRoot: req.Recipient.Asset.Root, + Outpoint: wire.OutPoint{ + Hash: arkTx.TxHash(), + Index: req.Recipient.OutputIndex, + }, + ArkTx: arkTx, + CheckpointTxs: checkpointTxs, + AncestorPackages: ancestors, + Lineage: lineage, + SealedArkPackage: req.TaprootAssetTransfer.ArkPackage, + }, + ) + if err != nil { + if ctx.Err() != nil { + return err + } + + return fmt.Errorf("%w: %w", oor.ErrInvalidIncomingAssetPackage, + err) + } + + return nil +} + +// SendAssetOOR initiates an out-of-round Taproot Asset transfer directly +// between the client and operator. It merges up to eight live asset VTXOs of +// the requested asset, leases an operator carrier float to fund the new asset +// leaves, returns round-originated carrier sats as sender Bitcoin change, and +// submits the pre-committed transfer to the durable OOR actor. +// +//nolint:funlen // Keep the asset OOR orchestration linear and auditable. +func (r *RPCServer) SendAssetOOR(ctx context.Context, + req *waverpc.SendAssetOORRequest) (*waverpc.SendAssetOORResponse, + error) { + + startTime := time.Now() + + if err := r.requireWalletReady(); err != nil { + return nil, err + } + if r.server.assetClient == nil || r.server.embeddedAssets == nil { + return nil, status.Errorf(codes.FailedPrecondition, "Taproot "+ + "Assets are not enabled on this daemon") + } + + parsedRef, err := tapsdk.ParseAssetRef(req.GetAssetRef()) + if err != nil { + return nil, status.Errorf(codes.InvalidArgument, "invalid "+ + "asset_ref: %v", err) + } + assetRef := parsedRef.String() + + if req.GetAmount() == 0 { + return nil, status.Errorf(codes.InvalidArgument, "amount "+ + "must be positive") + } + if req.GetAdmissionDeadlineUnixNanos() < 0 { + return nil, status.Errorf(codes.InvalidArgument, + "admission_deadline_unix_nanos must not be negative") + } + + if req.GetIdempotencyKey() != "" && !req.GetDryRun() { + replay, handled, err := r.replaySendAssetOORByIdempotencyKey( + ctx, req.GetIdempotencyKey(), + ) + if err != nil { + return nil, err + } + if handled { + return replay, nil + } + } + + if deadline := req.GetAdmissionDeadlineUnixNanos(); deadline > 0 && + !time.Now().Before(time.Unix(0, deadline)) { + return nil, status.Errorf(codes.FailedPrecondition, "OOR "+ + "admission deadline reached") + } + + terms, err := r.server.fetchOperatorTerms(ctx) + if err != nil { + return nil, operatorTermsError( + "unable to fetch operator terms", err, + ) + } + if terms.OORCarrierPubKey == nil { + return nil, status.Errorf(codes.FailedPrecondition, + "operator does not advertise an OOR carrier float key") + } + if !operatorAdmitsAsset(terms, assetRef) { + return nil, status.Errorf(codes.FailedPrecondition, "operator "+ + "does not admit asset %s", assetRef) + } + + outputFloor := terms.MinVTXOAmountFloor() + if outputFloor <= 0 { + return nil, status.Errorf(codes.FailedPrecondition, + "operator minimum VTXO output floor must be positive") + } + + recipientPolicy, err := resolveAssetOORRecipientPolicy(req, terms) + if err != nil { + return nil, err + } + + if req.GetDryRun() { + return r.previewSendAssetOOR( + ctx, assetRef, req.GetAmount(), outputFloor, + ) + } + + if r.server.actorSystem == nil { + return nil, status.Errorf(codes.Internal, "actor system not "+ + "initialized") + } + if r.server.vtxoStore == nil { + return nil, status.Errorf(codes.Internal, "VTXO store not "+ + "initialized") + } + + wRef, err := r.walletActor() + if err != nil { + return nil, err + } + + selectResp, err := wRef.Ask(ctx, &wallet.SelectAndLockAssetVTXOsRequest{ + AssetRef: assetRef, + TargetAmount: req.GetAmount(), + MaxInputs: tapassets.MaxOORAssetInputs, + }).Await(ctx).Unpack() + if err != nil { + return nil, status.Errorf(vtxoAdmissionCode(err), "asset VTXO "+ + "selection failed: %v", err) + } + + lockedAsset, ok := selectResp.(*wallet.SelectAndLockAssetVTXOsResponse) + if !ok { + return nil, status.Errorf(codes.Internal, "unexpected "+ + "response type: %T", selectResp) + } + + // Build a compatible SelectAndLockVTXOsResponse so error and canceled- + // await cleanup reuse the exact same unlock helpers as SendOOR. + lockedCompat := toCompatLockedVTXOs(lockedAsset) + + policy := arkscript.CheckpointPolicy{ + OperatorKey: terms.PubKey, + CSVDelay: terms.VTXOExitDelay, + } + + if err := trustAssetGroup( + r.server.embeddedAssets, assetRef, + ); err != nil { + + r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) + + return nil, status.Errorf(codes.InvalidArgument, "trust asset "+ + "group: %v", err) + } + + builtInputs, err := r.loadAssetOORInputs( + ctx, assetRef, lockedAsset.SelectedVTXOs, + ) + if err != nil { + r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) + + return nil, err + } + + assetChange := lockedAsset.TotalAssetSelected - req.GetAmount() + newAssetLeafCount := 1 + if assetChange > 0 { + newAssetLeafCount = 2 + } + + requiredLeaseSat, err := oortx.RequiredCarrierLeaseSat( + newAssetLeafCount, outputFloor, + ) + if err != nil { + r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) + + return nil, status.Errorf(codes.InvalidArgument, "required "+ + "carrier lease: %v", err) + } + + lease, err := r.leaseOORCarrier( + ctx, requiredLeaseSat, req.GetIdempotencyKey(), + ) + if err != nil { + r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) + + return nil, err + } + + floatInput, err := lease.ToTransferInput( + terms.PubKey, terms.OORCarrierPubKey, + ) + if err != nil { + r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) + + return nil, status.Errorf(codes.FailedPrecondition, "invalid "+ + "operator carrier lease: %v", err) + } + + carrierPlan, err := oortx.PlanAssetCarriers(oortx.CarrierPlanRequest{ + Inputs: builtInputs.carriers, + NewAssetLeafCount: newAssetLeafCount, + OutputFloor: outputFloor, + LeaseValue: lease.Value, + }) + if err != nil { + r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) + + return nil, status.Errorf(codes.FailedPrecondition, "plan "+ + "asset carriers: %v", err) + } + + floatCPArtifact, err := oortx.BuildCheckpointPSBT( + policy, oortx.CheckpointInput{ + SpentVTXO: oortx.SpentVTXORef{ + Outpoint: floatInput.VTXO.Outpoint, + Output: wire.NewTxOut( + int64(floatInput.VTXO.Amount), + floatInput.VTXO.PkScript, + ), + }, + OwnerLeafScript: floatInput.OwnerLeafScript, + OwnerLeafPolicy: floatInput.OwnerLeafPolicy, + }, + ) + if err != nil { + r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) + + return nil, status.Errorf(codes.Internal, "build carrier "+ + "float checkpoint: %v", err) + } + floatCPOut, err := floatCPArtifact.ToCheckpointOutput() + if err != nil { + r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) + + return nil, status.Errorf(codes.Internal, "build carrier "+ + "float checkpoint output: %v", err) + } + + assetOutputs := []tapassets.OORAssetOutput{{ + PolicyTemplate: recipientPolicy, + Amount: req.GetAmount(), + Value: carrierPlan.NewAssetLeafCarrier, + }} + if assetChange > 0 { + assetChangeRecip, err := r.buildOORChangeRecipient( + ctx, terms.PubKey, terms.VTXOExitDelay, + carrierPlan.NewAssetLeafCarrier, + ) + if err != nil { + r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) + + return nil, err + } + assetOutputs = append(assetOutputs, tapassets.OORAssetOutput{ + PolicyTemplate: assetChangeRecip.VTXOPolicyTemplate, + Amount: assetChange, + Value: carrierPlan.NewAssetLeafCarrier, + }) + } + + var plainOutputs []oortx.RecipientOutput + if carrierPlan.SenderChange > 0 { + btcChangeRecip, err := r.buildOORChangeRecipient( + ctx, terms.PubKey, terms.VTXOExitDelay, + carrierPlan.SenderChange, + ) + if err != nil { + r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) + + return nil, err + } + plainOutputs = append(plainOutputs, btcChangeRecip) + } + if carrierPlan.OperatorChange > 0 { + plainOutputs = append(plainOutputs, oortx.RecipientOutput{ + PkScript: bytes.Clone(lease.PkScript), + Value: carrierPlan.OperatorChange, + VTXOPolicyTemplate: bytes.Clone(lease.PolicyTemplate), + }) + } + + digest, err := deriveAssetOORTransferDigest( + assetRef, req.GetAmount(), recipientPolicy, + builtInputs.transferInputs, floatInput.VTXO.Outpoint, + req.GetIdempotencyKey(), + ) + if err != nil { + r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) + + return nil, status.Errorf(codes.Internal, "derive asset "+ + "transfer digest: %v", err) + } + + tapWallet := tapsdk.NewWallet( + r.server.assetClient, tapsdk.Network(r.server.cfg.Network), + ) + builtTransfer, err := tapassets.BuildOORTransfer( + ctx, tapWallet, tapassets.OORTransferRequest{ + AssetRef: parsedRef, + Digest: digest, + CheckpointPolicy: policy, + Inputs: builtInputs.assetInputs, + Checkpoints: []oortx.CheckpointOutput{floatCPOut}, + AssetOutputs: assetOutputs, + Outputs: plainOutputs, + }, + ) + if err != nil { + r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) + + code := codes.Internal + if errors.Is(err, tapassets.ErrOORProofLimit) || + errors.Is(err, tapassets.ErrOOROrderingUnresolved) { + + code = codes.FailedPrecondition + } + + return nil, status.Errorf(code, "build asset OOR transfer: %v", + err) + } + + allInputs := append( + append( + []oor.TransferInput(nil), builtInputs.transferInputs..., + ), + floatInput, + ) + cpPSBTs := make([]*psbt.Packet, 0, len(builtTransfer.Checkpoints)+1) + cpRoots := make( + []*chainhash.Hash, 0, len(builtTransfer.CheckpointAssetRoots)+1, + ) + cpPkgs := make([][]byte, 0, len(builtTransfer.CheckpointPackages)+1) + for i := range builtTransfer.Checkpoints { + cpPSBTs = append(cpPSBTs, builtTransfer.Checkpoints[i].PSBT) + root := builtTransfer.CheckpointAssetRoots[i] + cpRoots = append(cpRoots, &root) + cpPkgs = append(cpPkgs, builtTransfer.CheckpointPackages[i]) + } + cpPSBTs = append(cpPSBTs, floatCPArtifact.PSBT) + cpRoots = append(cpRoots, nil) + cpPkgs = append(cpPkgs, nil) + + prepared := &oor.PreparedSubmitPackage{ + ArkPSBT: builtTransfer.Ark, + CheckpointPSBTs: cpPSBTs, + CheckpointAssetRoots: cpRoots, + TaprootAssetTransfer: &oortx.TaprootAssetTransfer{ + Version: oortx.TaprootAssetTransferVersion, + ArkPackage: builtTransfer.ArkPackage, + CheckpointPackages: cpPkgs, + }, + } + if err := prepared.AttachTapLeafScripts(allInputs); err != nil { + r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) + + return nil, status.Errorf(codes.Internal, "attach asset OOR "+ + "tapleaf scripts: %v", err) + } + if err := prepared.Validate( + policy, allInputs, builtTransfer.Recipients, + ); err != nil { + + r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) + + return nil, status.Errorf(codes.Internal, "validate prepared "+ + "asset OOR submit: %v", err) + } + + matchedRecipient, err := findAssetOORRecipientOutput( + builtTransfer.Recipients, recipientPolicy, assetRef, + req.GetAmount(), + ) + if err != nil { + r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) + + return nil, status.Errorf(codes.Internal, "locate asset OOR "+ + "recipient output: %v", err) + } + + var dispatchRequestData []byte + if req.GetIdempotencyKey() != "" { + dispatchRequestData, err = oor.NewOutgoingReplayData( + builtTransfer.Recipients, + []oortx.RecipientOutput{matchedRecipient}, + ) + if err != nil { + r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) + + return nil, status.Errorf(codes.Internal, "build "+ + "asset OOR dispatch identity: %v", err) + } + } + + oorKey := oor.NewServiceKey() + oorRef := oorKey.Ref(r.server.actorSystem) + + oorReq := &oor.StartTransferRequest{ + Policy: policy, + Inputs: allInputs, + Recipients: builtTransfer.Recipients, + PreparedSubmit: prepared, + IdempotencyKey: req.GetIdempotencyKey(), + DispatchRequestData: dispatchRequestData, + AdmissionDeadlineUnixNanos: req. + GetAdmissionDeadlineUnixNanos(), + } + + oorCtx := actor.WithoutTx(context.WithoutCancel(ctx)) + future := oorRef.Ask(oorCtx, oorReq) + oorResp, err := future.Await(ctx).Unpack() + if err != nil { + if errors.Is(err, oor.ErrOutgoingAdmissionExpired) { + r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) + + return nil, status.Errorf(codes.FailedPrecondition, + "OOR admission deadline reached") + } + if errors.Is(err, oor.ErrIdempotencyKeyConflict) { + r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) + + return nil, status.Errorf(codes.AlreadyExists, "OOR "+ + "session already uses a different "+ + "idempotency key") + } + if isAwaitContextError(ctx, err) { + r.cleanupSubmittedOORStart( + ctx, future, lockedCompat, nil, + ) + + code := codes.Canceled + if errors.Is(err, context.DeadlineExceeded) { + code = codes.DeadlineExceeded + } + + return nil, status.Errorf(code, "asset OOR transfer "+ + "response wait: %v", err) + } + + r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) + r.server.emitMetric(ctx, &metrics.OORTransferSentMsg{ + Status: "failed", + Duration: time.Since(startTime), + }) + + return nil, status.Errorf(codes.Internal, "asset OOR transfer "+ + "failed: %v", err) + } + + resp, ok := oorResp.(*oor.StartTransferResponse) + if !ok { + r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) + + return nil, status.Errorf(codes.Internal, "unexpected "+ + "response type: %T", oorResp) + } + + if resp.Existing { + r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) + } + + var recipientOutpoint string + if !resp.Existing { + op, opErr := oortx.RecipientOutPoint( + chainhash.Hash(resp.SessionID), + builtTransfer.Recipients, matchedRecipient, + ) + if opErr == nil { + recipientOutpoint = op.String() + } + } + + r.server.log.InfoS(ctx, "Asset OOR transfer submitted", + slog.String("session_id", resp.SessionID.String()), + slog.Bool("existing_session", resp.Existing), + slog.String("asset_ref", assetRef), + slog.Uint64("asset_amount", req.GetAmount()), + slog.Uint64("asset_change_amount", assetChange), + slog.Int("selected_input_count", len(builtInputs.assetInputs)), + slog.Int64( + "sender_btc_change_sat", + int64(carrierPlan.SenderChange), + ), + slog.Int64( + "operator_float_change_sat", + int64(carrierPlan.OperatorChange), + ), + slog.Duration("duration", time.Since(startTime)), + ) + + r.server.emitMetric(ctx, &metrics.OORTransferSentMsg{ + SessionID: resp.SessionID.String(), + Status: "submitted", + Duration: time.Since(startTime), + }) + + return &waverpc.SendAssetOORResponse{ + Status: "submitted", + SessionId: resp.SessionID.String(), + RecipientOutpoint: recipientOutpoint, + SelectedInputCount: uint32(len(builtInputs.assetInputs)), + AssetChangeAmount: assetChange, + SenderBtcChangeSat: int64(carrierPlan.SenderChange), + }, nil +} + +// assetOORInputs bundles the per-input representations built from selected +// asset VTXOs for tapassets.BuildOORTransfer, carrier planning, and the OOR +// session actor. +type assetOORInputs struct { + assetInputs []tapassets.OORAssetInput + transferInputs []oor.TransferInput + carriers []oortx.CarrierInput +} + +// loadAssetOORInputs loads the full descriptors, asset pieces, proof +// verifiers, and collaborative leaves for the selected asset VTXOs. +func (r *RPCServer) loadAssetOORInputs(ctx context.Context, assetRef string, + selected []wallet.SelectedAssetVTXO) (*assetOORInputs, error) { + + out := &assetOORInputs{ + assetInputs: make( + []tapassets.OORAssetInput, 0, len(selected), + ), + transferInputs: make([]oor.TransferInput, 0, len(selected)), + carriers: make([]oortx.CarrierInput, 0, len(selected)), + } + + for _, sv := range selected { + desc, err := r.server.vtxoStore.GetVTXO(ctx, sv.Outpoint) + if err != nil { + return nil, status.Errorf(codes.Internal, "load "+ + "selected asset VTXO %s: %v", sv.Outpoint, err) + } + if desc == nil || desc.TaprootAssetRoot == nil || + desc.TaprootAssetRef != assetRef || + desc.TaprootAssetAmount == 0 || + len(desc.TaprootAssetSealedPackage) == 0 { + return nil, status.Errorf(codes.FailedPrecondition, + "selected VTXO %s has incomplete asset state", + sv.Outpoint) + } + if desc.ClientKey.PubKey == nil || desc.OperatorKey == nil { + return nil, status.Errorf(codes.FailedPrecondition, + "selected asset VTXO %s has no signing keys", + sv.Outpoint) + } + + pieces, err := tapassets.DecodeAssetVTXOClaimInputs( + desc.TaprootAssetSealedPackage, desc.Outpoint, + ) + if err != nil { + return nil, status.Errorf(codes.FailedPrecondition, + "decode asset VTXO %s package: %v", sv.Outpoint, + err) + } + + var pieceTotal uint64 + for _, piece := range pieces { + if piece.Amount > math.MaxUint64-pieceTotal { + return nil, status.Errorf(codes.Internal, + "asset VTXO %s piece amount overflow", + sv.Outpoint) + } + pieceTotal += piece.Amount + } + if pieceTotal != desc.TaprootAssetAmount { + return nil, status.Errorf(codes.FailedPrecondition, + "asset VTXO %s package has %d units, want %d", + sv.Outpoint, pieceTotal, + desc.TaprootAssetAmount) + } + + vtxoPolicy := bytes.Clone(desc.PolicyTemplate) + if len(vtxoPolicy) == 0 { + vtxoPolicy, err = arkscript.EncodeStandardVTXOTemplate( + desc.ClientKey.PubKey, desc.OperatorKey, + desc.RelativeExpiry, + ) + if err != nil { + return nil, status.Errorf(codes.Internal, + "encode standard policy for asset "+ + "VTXO %s: %v", sv.Outpoint, err) + } + } + + collabLeaf, err := arkscript.MultiSigCollabTapLeaf( + desc.ClientKey.PubKey, desc.OperatorKey, + ) + if err != nil { + return nil, status.Errorf(codes.Internal, "derive "+ + "collab leaf for asset VTXO %s: %v", + sv.Outpoint, err) + } + ownerLeafPolicy, err := arkscript.LeafTemplate{ + Node: &arkscript.Multisig{ + Keys: []*btcec.PublicKey{ + desc.ClientKey.PubKey, + desc.OperatorKey, + }, + }, + }.Encode() + if err != nil { + return nil, status.Errorf(codes.Internal, "encode "+ + "collab leaf policy for asset VTXO %s: %v", + sv.Outpoint, err) + } + + verifier, err := r.buildAssetInputProofVerifier(ctx, desc) + if err != nil { + return nil, status.Errorf(codes.Internal, "build "+ + "proof verifier for asset VTXO %s: %v", + sv.Outpoint, err) + } + + carrierOrigin := oortx.CarrierOriginRound + if desc.ChainDepth > 0 { + carrierOrigin = oortx.CarrierOriginOOR + } + + out.assetInputs = append( + out.assetInputs, tapassets.OORAssetInput{ + Checkpoint: oortx.CheckpointInput{ + SpentVTXO: oortx.SpentVTXORef{ + Outpoint: desc.Outpoint, + Output: wire.NewTxOut( + int64(desc.Amount), + desc.PkScript, + ), + }, + OwnerLeafScript: collabLeaf.Script, + OwnerLeafPolicy: ownerLeafPolicy, + }, + Pieces: pieces, + Verifier: verifier, + }, + ) + out.transferInputs = append( + out.transferInputs, oor.TransferInput{ + VTXO: desc, + OwnerLeafScript: collabLeaf.Script, + OwnerLeafPolicy: ownerLeafPolicy, + VTXOPolicyTemplate: vtxoPolicy, + ReserveEpoch: sv.ReserveEpoch, + TaprootAssetCarrierOrigin: carrierOrigin, + }, + ) + out.carriers = append(out.carriers, oortx.CarrierInput{ + Amount: desc.Amount, + Origin: carrierOrigin, + }) + } + + return out, nil +} + +// buildAssetInputProofVerifier constructs a ConfirmedProofVerifier bound to +// the daemon's embedded engine and the VTXO's persisted commitment-tree +// ancestry and local OOR package chain. +func (r *RPCServer) buildAssetInputProofVerifier(ctx context.Context, + desc *vtxo.Descriptor) (customanchor.ConfirmedProofVerifier, error) { + + chainVerifier, err := tapassets.NewLocalProofChainVerifier( + r.server.assetClient, + ) + if err != nil { + return nil, err + } + + lineage := lineageAnchorsFromAncestry(desc.Ancestry) + + var packages []tapassets.OORPackageTxs + if desc.ChainDepth > 0 { + pkgStore := r.newLocalOORArtifactStore() + if pkgStore == nil { + return nil, fmt.Errorf("OOR artifact store not " + + "initialized for OOR asset VTXO") + } + resolved, err := pkgStore.ResolveUnrollPackages( + ctx, desc.Outpoint, + ) + if err != nil { + return nil, fmt.Errorf("resolve OOR packages for "+ + "%s: %w", desc.Outpoint, err) + } + for _, bundle := range resolved.Packages { + if bundle == nil || bundle.ArkPSBT == nil || + bundle.ArkPSBT.UnsignedTx == nil { + + continue + } + cpTxs, err := unsignedTxsFromPSBTs( + bundle.FinalCheckpointPSBTs, + ) + if err != nil { + return nil, fmt.Errorf("decode checkpoint txs "+ + "for session %s: %w", bundle.SessionID, + err) + } + packages = append(packages, tapassets.OORPackageTxs{ + ArkTx: bundle.ArkPSBT.UnsignedTx, + CheckpointTxs: cpTxs, + }) + } + } + + return tapassets.NewOORProofVerifier(chainVerifier, lineage, packages) +} + +// leaseOORCarrier requests one operator carrier float VTXO lease covering +// requiredSat over the authenticated operator mailbox client. +func (r *RPCServer) leaseOORCarrier(ctx context.Context, + requiredSat btcutil.Amount, idempotencyKey string) ( + *oor.OORCarrierLease, error) { + + if r.oorCarrierLeaseOverride != nil { + return r.oorCarrierLeaseOverride( + ctx, requiredSat, idempotencyKey, + ) + } + + if r.server.ark == nil { + return nil, status.Errorf(codes.Unavailable, "authenticated "+ + "operator client not initialized") + } + + var opts []mailboxrpc.RPCOptions + if idempotencyKey != "" { + opts = append(opts, mailboxrpc.RPCOptions{ + IdempotencyKey: "asset-oor-lease:" + idempotencyKey, + }) + } + + resp, err := r.server.ark.LeaseOORCarrier( + ctx, &arkrpc.LeaseOORCarrierRequest{ + RequiredSat: int64(requiredSat), + }, opts..., + ) + if err != nil { + return nil, status.Errorf(codes.Unavailable, "lease OOR "+ + "carrier float: %v", err) + } + + outpoint, err := wire.NewOutPointFromString(resp.GetOutpoint()) + if err != nil { + return nil, status.Errorf(codes.Internal, "parse leased "+ + "carrier outpoint %q: %v", resp.GetOutpoint(), err) + } + + lease := &oor.OORCarrierLease{ + Outpoint: *outpoint, + Value: btcutil.Amount(resp.GetValueSat()), + PolicyTemplate: bytes.Clone(resp.GetVtxoPolicyTemplate()), + PkScript: bytes.Clone(resp.GetPkScript()), + ExpiresAtUnix: resp.GetExpiresAtUnix(), + } + if err := lease.Validate(); err != nil { + return nil, status.Errorf(codes.FailedPrecondition, "invalid "+ + "operator carrier lease: %v", err) + } + + return lease, nil +} + +// previewSendAssetOOR validates live asset VTXO availability without locking +// VTXOs, leasing a carrier float, or submitting a transfer. +func (r *RPCServer) previewSendAssetOOR(ctx context.Context, assetRef string, + amount uint64, outputFloor btcutil.Amount) ( + *waverpc.SendAssetOORResponse, error) { + + if r.server.vtxoStore == nil { + return nil, status.Errorf(codes.Internal, "VTXO store not "+ + "initialized") + } + + liveDescs, err := r.server.vtxoStore.ListVTXOsByStatus( + ctx, vtxo.VTXOStatusLive, + ) + if err != nil { + return nil, status.Errorf(codes.Internal, "list live VTXOs: %v", + err) + } + + selected, totalSelected, err := vtxo.SelectAssetVTXOCandidates( + liveDescs, assetRef, amount, tapassets.MaxOORAssetInputs, + ) + if err != nil { + return nil, status.Errorf(vtxoAdmissionCode(err), "asset VTXO "+ + "preview failed: %v", err) + } + + var senderBTCChange btcutil.Amount + for _, desc := range selected { + if desc.ChainDepth == 0 { + senderBTCChange += desc.Amount + } + } + if senderBTCChange > 0 && senderBTCChange < outputFloor { + return nil, status.Errorf(codes.FailedPrecondition, "sender "+ + "Bitcoin change %d sat is below output floor %d sat", + senderBTCChange, outputFloor) + } + + return &waverpc.SendAssetOORResponse{ + Status: "preview", + SelectedInputCount: uint32(len(selected)), + AssetChangeAmount: totalSelected - amount, + SenderBtcChangeSat: int64(senderBTCChange), + }, nil +} + +// replaySendAssetOORByIdempotencyKey returns an existing durable keyed session +// before selecting asset VTXOs or leasing an operator carrier float. +func (r *RPCServer) replaySendAssetOORByIdempotencyKey(ctx context.Context, + key string) (*waverpc.SendAssetOORResponse, bool, error) { + + attempt, found, err := r.findOutgoingOORSessionByIdempotencyKey( + ctx, key, + ) + if err != nil { + return nil, true, err + } + if !found { + return nil, false, nil + } + + sessionID := oor.SessionID(attempt.SessionID) + replayStatus, prePONR, err := r.outgoingOORReplayStatus(ctx, sessionID) + if err != nil { + return nil, true, err + } + if replayStatus == "failed" { + return &waverpc.SendAssetOORResponse{ + Status: replayStatus, + SessionId: sessionID.String(), + FailedBeforePonr: prePONR, + }, true, nil + } + + return &waverpc.SendAssetOORResponse{ + Status: "submitted", + SessionId: sessionID.String(), + }, true, nil +} + +// resolveAssetOORRecipientPolicy converts the SendAssetOOR destination oneof +// into a validated uncomposed Ark VTXO policy template. +func resolveAssetOORRecipientPolicy(req *waverpc.SendAssetOORRequest, + terms *types.OperatorTerms) ([]byte, error) { + + switch d := req.Destination.(type) { + case *waverpc.SendAssetOORRequest_Pubkey: + if len(d.Pubkey) == 0 { + return nil, status.Errorf(codes.InvalidArgument, + "recipient pubkey must be provided") + } + recipientKey, err := schnorr.ParsePubKey(d.Pubkey) + if err != nil { + return nil, status.Errorf(codes.InvalidArgument, + "invalid recipient pubkey: %v", err) + } + + policyBytes, err := arkscript.EncodeStandardVTXOTemplate( + recipientKey, terms.PubKey, terms.VTXOExitDelay, + ) + if err != nil { + return nil, status.Errorf(codes.Internal, "encode "+ + "recipient policy template: %v", err) + } + + return policyBytes, nil + + case *waverpc.SendAssetOORRequest_PolicyTemplate: + if len(d.PolicyTemplate) == 0 { + return nil, status.Errorf(codes.InvalidArgument, + "recipient policy_template must be provided") + } + template, err := arkscript.DecodePolicyTemplate( + d.PolicyTemplate, + ) + if err != nil { + return nil, status.Errorf(codes.InvalidArgument, + "decode recipient policy_template: %v", err) + } + if _, err := template.Compile(); err != nil { + return nil, status.Errorf(codes.InvalidArgument, + "compile recipient policy_template: %v", err) + } + + return bytes.Clone(d.PolicyTemplate), nil + + default: + return nil, status.Errorf(codes.InvalidArgument, "recipient "+ + "destination (pubkey or policy_template) is required") + } +} + +// deriveAssetOORTransferDigest derives a non-zero 32-byte digest scoping the +// OP_TRUE script keys of this transfer's asset outputs. +func deriveAssetOORTransferDigest(assetRef string, amount uint64, + recipientPolicy []byte, inputs []oor.TransferInput, + floatOutpoint wire.OutPoint, + idempotencyKey string) (tapsdk.Hash, error) { + + h := sha256.New() + _, _ = h.Write([]byte("wavelength/asset-oor/v1")) + _, _ = h.Write([]byte(assetRef)) + var buf [8]byte + binary.BigEndian.PutUint64(buf[:], amount) + _, _ = h.Write(buf[:]) + _, _ = h.Write(recipientPolicy) + for _, in := range inputs { + _, _ = h.Write(in.VTXO.Outpoint.Hash[:]) + binary.BigEndian.PutUint32(buf[:4], in.VTXO.Outpoint.Index) + _, _ = h.Write(buf[:4]) + } + _, _ = h.Write(floatOutpoint.Hash[:]) + binary.BigEndian.PutUint32(buf[:4], floatOutpoint.Index) + _, _ = h.Write(buf[:4]) + + if idempotencyKey != "" { + _, _ = h.Write([]byte(idempotencyKey)) + } else { + var nonce [16]byte + if _, err := rand.Read(nonce[:]); err != nil { + return tapsdk.Hash{}, err + } + _, _ = h.Write(nonce[:]) + } + + var digest tapsdk.Hash + copy(digest[:], h.Sum(nil)) + if digest == (tapsdk.Hash{}) { + digest[0] = 1 + } + + return digest, nil +} + +// findAssetOORRecipientOutput returns the canonical recipient output entry +// created for the requested recipient policy, asset reference, and amount. +func findAssetOORRecipientOutput(recipients []oortx.RecipientOutput, + recipientPolicy []byte, assetRef string, + amount uint64) (oortx.RecipientOutput, error) { + + for _, r := range recipients { + if r.Asset == nil { + continue + } + if r.Asset.Ref == assetRef && r.Asset.Amount == amount && + bytes.Equal(r.VTXOPolicyTemplate, recipientPolicy) { + return r, nil + } + } + + return oortx.RecipientOutput{}, fmt.Errorf("recipient asset output " + + "not found in built transfer") +} + +// toCompatLockedVTXOs adapts a SelectAndLockAssetVTXOsResponse into the +// SelectAndLockVTXOsResponse shape expected by unlockSelectedVTXOsBestEffort +// and cleanupSubmittedOORStart. +func toCompatLockedVTXOs( + locked *wallet.SelectAndLockAssetVTXOsResponse) *wallet.SelectAndLockVTXOsResponse { //nolint:ll + + if locked == nil { + return nil + } + + selected := make([]wallet.SelectedVTXO, 0, len(locked.SelectedVTXOs)) + var total btcutil.Amount + for _, sv := range locked.SelectedVTXOs { + selected = append(selected, wallet.SelectedVTXO{ + Outpoint: sv.Outpoint, + ReserveEpoch: sv.ReserveEpoch, + Amount: sv.Amount, + PkScript: sv.PkScript, + }) + total += sv.Amount + } + + return &wallet.SelectAndLockVTXOsResponse{ + SelectedVTXOs: selected, + TotalSelected: total, + } +} + +// lineageAnchorsFromAncestry converts VTXO ancestry fragments into +// tapassets.OORLineageAnchor entries for OOR proof verification. +func lineageAnchorsFromAncestry( + ancestry []vtxo.Ancestry) []tapassets.OORLineageAnchor { + + anchors := make([]tapassets.OORLineageAnchor, 0, len(ancestry)) + for _, anc := range ancestry { + if anc.CommitmentTxID == (chainhash.Hash{}) || + anc.TreePath == nil { + + continue + } + anchors = append(anchors, tapassets.OORLineageAnchor{ + CommitmentTxID: anc.CommitmentTxID, + TreePath: anc.TreePath, + }) + } + + return anchors +} + +// unsignedTxsFromPSBTs extracts unsigned transactions from a slice of PSBTs. +func unsignedTxsFromPSBTs(packets []*psbt.Packet) ([]*wire.MsgTx, error) { + txs := make([]*wire.MsgTx, 0, len(packets)) + for i, pkt := range packets { + if pkt == nil || pkt.UnsignedTx == nil { + return nil, fmt.Errorf("psbt %d has nil unsigned tx", i) + } + txs = append(txs, pkt.UnsignedTx) + } + + return txs, nil +} diff --git a/waved/asset_oor_test.go b/waved/asset_oor_test.go new file mode 100644 index 000000000..62d4fcf67 --- /dev/null +++ b/waved/asset_oor_test.go @@ -0,0 +1,431 @@ +package waved + +import ( + "bytes" + "context" + "errors" + "testing" + "time" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcec/v2/schnorr" + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/txscript/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/btcsuite/btclog/v2" + tapsdk "github.com/lightninglabs/tap-sdk" + "github.com/lightninglabs/tap-sdk/embedded" + "github.com/lightninglabs/wavelength/arkrpc" + "github.com/lightninglabs/wavelength/baselib/actor" + "github.com/lightninglabs/wavelength/db" + "github.com/lightninglabs/wavelength/indexer" + "github.com/lightninglabs/wavelength/lib/arkscript" + oortx "github.com/lightninglabs/wavelength/lib/tx/oor" + "github.com/lightninglabs/wavelength/oor" + "github.com/lightninglabs/wavelength/vtxo" + "github.com/lightninglabs/wavelength/wallet" + "github.com/lightninglabs/wavelength/waverpc" + fn "github.com/lightningnetwork/lnd/fn/v2" + "github.com/lightningnetwork/lnd/keychain" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +var testAssetOORRef = tapsdk.AssetRefFromAssetID( + tapsdk.AssetID{0x11, 0x22, 0x33}, +).String() + +// mockAssetWalletBehavior captures SelectAndLockAssetVTXOsRequest and +// UnlockVTXOsRequest messages in focused SendAssetOOR unit tests. +type mockAssetWalletBehavior struct { + selectResp *wallet.SelectAndLockAssetVTXOsResponse + selectErr error + + unlockedOutpoints []wire.OutPoint + unlockCh chan []wire.OutPoint +} + +func (m *mockAssetWalletBehavior) Receive(_ context.Context, + msg wallet.WalletMsg) fn.Result[wallet.WalletResp] { + + switch req := msg.(type) { + case *wallet.SelectAndLockAssetVTXOsRequest: + if m.selectErr != nil { + return fn.Err[wallet.WalletResp](m.selectErr) + } + + return fn.Ok[wallet.WalletResp](m.selectResp) + + case *wallet.UnlockVTXOsRequest: + m.unlockedOutpoints = append( + m.unlockedOutpoints, req.Outpoints..., + ) + if m.unlockCh != nil { + select { + case m.unlockCh <- append( + []wire.OutPoint(nil), req.Outpoints..., + ): + default: + } + } + + return fn.Ok[wallet.WalletResp](&wallet.UnlockVTXOsResponse{}) + + default: + return fn.Err[wallet.WalletResp]( + errors.New("unexpected wallet message"), + ) + } +} + +func newSendAssetOORTestRPC(t *testing.T, infoResp *arkrpc.GetInfoResponse) ( + *RPCServer, *db.VTXOPersistenceStore, *db.OORSessionRegistryStoreDB, + *mockAssetWalletBehavior) { + + t.Helper() + + vtxoStore, _, registryStore, _, _ := newSendOORTestStores(t) + sys := actor.NewActorSystem() + t.Cleanup(func() { + require.NoError(t, sys.Shutdown(context.Background())) + }) + + walletBehavior := &mockAssetWalletBehavior{ + unlockCh: make(chan []wire.OutPoint, 4), + } + wKey := actor.NewServiceKey[wallet.WalletMsg, wallet.WalletResp]( + "wallet-asset-oor-test", + ) + wRef := actor.RegisterWithSystem( + sys, "wallet-test", wKey, walletBehavior, + ) + + walletReady := make(chan struct{}) + close(walletReady) + + srv := &Server{ + log: btclog.Disabled, + cfg: DefaultConfig(), + actorSystem: sys, + walletRef: fn.Some(wRef), + walletServicesReady: walletReady, + vtxoStore: vtxoStore, + oorSessionStore: registryStore, + arkClient: &stubArkServiceClient{ + resp: infoResp, + }, + assetClient: &embedded.Client{}, + embeddedAssets: &embedded.Client{}, + } + srv.walletState.Store(int32(WalletStateReady)) + srv.arkProtocolVersion.Store(arkrpc.ArkProtocolVersionV1) + + return NewRPCServer(srv), vtxoStore, registryStore, walletBehavior +} + +// TestSendAssetOORValidationAndPreview verifies pre-flight validation, +// operator asset/float checks, and dry-run multi-input preview calculation. +func TestSendAssetOORValidationAndPreview(t *testing.T) { + t.Parallel() + + operatorPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + carrierPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + recipPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + ownerPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + + infoResp := &arkrpc.GetInfoResponse{ + Pubkey: operatorPriv.PubKey().SerializeCompressed(), + VtxoExitDelay: 144, + DustLimit: 330, + MinVtxoAmountSat: 1_000, + SelectedArkVersion: arkrpc.ArkProtocolVersionV1, + OorCarrierPubkey: carrierPriv.PubKey().SerializeCompressed(), + Assets: []*arkrpc.AssetPolicy{ + { + AssetRef: testAssetOORRef, + }, + }, + } + rpcSrv, vtxoStore, _, _ := newSendAssetOORTestRPC(t, infoResp) + + // Invalid asset_ref fails with InvalidArgument. + _, err = rpcSrv.SendAssetOOR(t.Context(), &waverpc.SendAssetOORRequest{ + AssetRef: "not-hex", + Amount: 100, + Destination: &waverpc.SendAssetOORRequest_Pubkey{ + Pubkey: schnorr.SerializePubKey(recipPriv.PubKey()), + }, + }) + require.Equal(t, codes.InvalidArgument, status.Code(err)) + + // Zero amount fails with InvalidArgument. + _, err = rpcSrv.SendAssetOOR(t.Context(), &waverpc.SendAssetOORRequest{ + AssetRef: testAssetOORRef, + Amount: 0, + Destination: &waverpc.SendAssetOORRequest_Pubkey{ + Pubkey: schnorr.SerializePubKey(recipPriv.PubKey()), + }, + }) + require.Equal(t, codes.InvalidArgument, status.Code(err)) + + // Missing destination fails with InvalidArgument. + _, err = rpcSrv.SendAssetOOR(t.Context(), &waverpc.SendAssetOORRequest{ + AssetRef: testAssetOORRef, + Amount: 100, + }) + require.Equal(t, codes.InvalidArgument, status.Code(err)) + + // Expired admission deadline fails with FailedPrecondition. + _, err = rpcSrv.SendAssetOOR(t.Context(), &waverpc.SendAssetOORRequest{ + AssetRef: testAssetOORRef, + Amount: 100, + Destination: &waverpc.SendAssetOORRequest_Pubkey{ + Pubkey: schnorr.SerializePubKey(recipPriv.PubKey()), + }, + AdmissionDeadlineUnixNanos: time. + Now(). + Add(-time.Second). + UnixNano(), + }) + require.Equal(t, codes.FailedPrecondition, status.Code(err)) + + // Persist two live asset VTXOs: one round-originated (ChainDepth 0, + // 1200 sat carrier) and one OOR-originated (ChainDepth 1, 1000 sat). + saveAssetVTXO := func(hashByte byte, amount uint64, + carrier btcutil.Amount, chainDepth int) { + + root := chainhash.Hash{hashByte, 0xaa} + policyBytes, err := arkscript.EncodeStandardVTXOTemplate( + ownerPriv.PubKey(), operatorPriv.PubKey(), 144, + ) + require.NoError(t, err) + tmpl, err := arkscript.DecodePolicyTemplate(policyBytes) + require.NoError(t, err) + compiled, err := tmpl.Compile() + require.NoError(t, err) + composed, err := arkscript.ComposeWithSiblingRoot( + compiled, root, + ) + require.NoError(t, err) + pkScript, err := txscript.PayToTaprootScript( + composed.OutputKey(), + ) + require.NoError(t, err) + + require.NoError( + t, + vtxoStore.SaveVTXO( + t.Context(), &vtxo.Descriptor{ + Outpoint: wire.OutPoint{ + Hash: chainhash.Hash{hashByte}, + Index: 0, + }, + Amount: carrier, + PolicyTemplate: policyBytes, + PkScript: pkScript, + ClientKey: keychain.KeyDescriptor{ + PubKey: ownerPriv.PubKey(), + }, + OperatorKey: operatorPriv.PubKey(), + RoundID: "round-1", + CommitmentTxID: chainhash.Hash{ + 0x99, + }, + BatchExpiry: 10_000, + RelativeExpiry: 144, + ChainDepth: chainDepth, + CreatedHeight: 100, + Status: vtxo.VTXOStatusLive, + TaprootAssetRoot: &root, + TaprootAssetRef: testAssetOORRef, + TaprootAssetAmount: amount, + TaprootAssetSealedPackage: []byte( + "sealed-pkg", + ), + }, + ), + ) + } + + saveAssetVTXO(0x01, 400, 1_200, 0) + saveAssetVTXO(0x02, 300, 1_000, 1) + + // Dry-run merges both inputs (400 + 300 = 700), leaves 150 asset + // change, and returns ONLY the round-originated 1200 sat carrier as + // sender BTC change (the OOR input's 1000 sat is operator-reclaimed). + preview, err := rpcSrv.SendAssetOOR( + t.Context(), &waverpc.SendAssetOORRequest{ + AssetRef: testAssetOORRef, + Amount: 550, + Destination: &waverpc.SendAssetOORRequest_Pubkey{ + Pubkey: schnorr.SerializePubKey( + recipPriv.PubKey(), + ), + }, + DryRun: true, + }, + ) + require.NoError(t, err) + require.Equal(t, "preview", preview.Status) + require.EqualValues(t, 2, preview.SelectedInputCount) + require.EqualValues(t, 150, preview.AssetChangeAmount) + require.EqualValues(t, 1_200, preview.SenderBtcChangeSat) + require.Empty(t, preview.SessionId) + + // When assets engine is disabled, SendAssetOOR fails closed. + rpcSrv.server.assetClient = nil + _, err = rpcSrv.SendAssetOOR(t.Context(), &waverpc.SendAssetOORRequest{ + AssetRef: testAssetOORRef, + Amount: 100, + Destination: &waverpc.SendAssetOORRequest_Pubkey{ + Pubkey: schnorr.SerializePubKey(recipPriv.PubKey()), + }, + }) + require.Equal(t, codes.FailedPrecondition, status.Code(err)) +} + +// TestSendAssetOORRollsBackSelectionOnLoadFailure verifies that when loading +// selected asset inputs fails after wallet selection, the locked outpoints are +// unlocked via UnlockVTXOsRequest. +func TestSendAssetOORRollsBackSelectionOnLoadFailure(t *testing.T) { + t.Parallel() + + operatorPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + carrierPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + recipPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + + infoResp := &arkrpc.GetInfoResponse{ + Pubkey: operatorPriv.PubKey().SerializeCompressed(), + VtxoExitDelay: 144, + DustLimit: 330, + MinVtxoAmountSat: 1_000, + SelectedArkVersion: arkrpc.ArkProtocolVersionV1, + OorCarrierPubkey: carrierPriv.PubKey().SerializeCompressed(), + Assets: []*arkrpc.AssetPolicy{ + { + AssetRef: testAssetOORRef, + }, + }, + } + rpcSrv, _, _, walletBehavior := newSendAssetOORTestRPC(t, infoResp) + + missingOP := wire.OutPoint{Hash: chainhash.Hash{0x44}, Index: 0} + walletBehavior.selectResp = &wallet.SelectAndLockAssetVTXOsResponse{ + SelectedVTXOs: []wallet.SelectedAssetVTXO{{ + Outpoint: missingOP, + ReserveEpoch: 3, + Amount: 1_000, + AssetAmount: 500, + }}, + TotalAssetSelected: 500, + } + + _, err = rpcSrv.SendAssetOOR(t.Context(), &waverpc.SendAssetOORRequest{ + AssetRef: testAssetOORRef, + Amount: 250, + Destination: &waverpc.SendAssetOORRequest_Pubkey{ + Pubkey: schnorr.SerializePubKey(recipPriv.PubKey()), + }, + }) + require.ErrorContains(t, err, "load selected asset VTXO") + + select { + case unlocked := <-walletBehavior.unlockCh: + require.Equal(t, []wire.OutPoint{missingOP}, unlocked) + + case <-time.After(5 * time.Second): + t.Fatal("expected locked asset VTXO to be unlocked on failure") + } +} + +// TestVerifyIncomingAssetOORFailsClosedWhenDisabled verifies that receiving an +// incoming asset OOR output on a daemon without an enabled asset engine fails +// closed with oor.ErrInvalidIncomingAssetPackage. +func TestVerifyIncomingAssetOORFailsClosedWhenDisabled(t *testing.T) { + t.Parallel() + + srv := &Server{} + err := srv.verifyIncomingAssetOOR( + t.Context(), oor.IncomingAssetVerification{ + Recipient: oor.ArkRecipientOutput{ + OutputIndex: 0, + Asset: &oortx.RecipientAsset{ + Root: chainhash.Hash{0x11}, + Ref: testAssetOORRef, + Amount: 100, + }, + }, + }, + ) + require.ErrorIs(t, err, oor.ErrInvalidIncomingAssetPackage) +} + +// TestServerDurableUnaryBuilderScopedScripts verifies that +// BuildListVTXOsByScopedScriptsRequest routes the composed PkScript on the +// wire while looking up the signing key via SignerScript. +func TestServerDurableUnaryBuilderScopedScripts(t *testing.T) { + t.Parallel() + + clientKey := testKeyDescriptor(t, 11) + keyPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + clientKey.PubKey = keyPriv.PubKey() + + uncomposed := make([]byte, 34) + uncomposed[0] = 0x51 + uncomposed[1] = 0x20 + uncomposed[2] = 0x11 + + composed := make([]byte, 34) + composed[0] = 0x51 + composed[1] = 0x20 + composed[2] = 0x22 + + store := &testReceiveScriptStore{ + records: []db.OwnedReceiveScriptRecord{{ + PkScript: uncomposed, + ClientKey: clientKey, + Source: db.OwnedReceiveScriptSourceWallet, + }}, + } + signer := NewOwnedReceiveScriptSigner( + store, func( + keyDesc keychain.KeyDescriptor) indexer.SchnorrSigner { + + return &testOwnedReceiveScriptSigner{ + keyDesc: keyDesc, + tagSig: make([]byte, 64), + } + }, + ) + idx := indexer.New( + nil, signer, "test-server", "client:test", + fn.None[btclog.Logger](), + ) + + builder := &serverDurableUnaryBuilder{ + server: &Server{ + indexer: idx, + }, + } + + msg, err := builder.BuildListVTXOsByScopedScriptsRequest( + t.Context(), [][]byte{composed}, [][]byte{uncomposed}, nil, 32, + ) + require.NoError(t, err) + + req, ok := msg.(*arkrpc.ListVTXOsByScriptsRequest) + require.True(t, ok) + require.Len(t, req.Scripts, 1) + require.True(t, bytes.Equal(composed, req.Scripts[0].PkScript)) + require.NotNil(t, req.Scripts[0].GetTaprootSchnorr()) +} diff --git a/waved/incoming_metadata.go b/waved/incoming_metadata.go index 90df4edbd..01a4314b9 100644 --- a/waved/incoming_metadata.go +++ b/waved/incoming_metadata.go @@ -106,6 +106,16 @@ func resolveIncomingMetadataWithRetry(ctx context.Context, idx *indexer.Client, slog.String("pk_script", fmt.Sprintf("%x", recipient.PkScript)), ) + var signerScript []byte + if recipient.Asset != nil { + var err error + signerScript, err = recipient.RoutingPkScript() + if err != nil { + return oor.IncomingVTXOMetadata{}, fmt.Errorf("derive "+ + "asset routing script: %w", err) + } + } + var cursor []byte var scanned uint64 for { @@ -123,6 +133,9 @@ func resolveIncomingMetadataWithRetry(ctx context.Context, idx *indexer.Client, []byte(nil), recipient.PkScript..., ), + SignerScript: append( + []byte(nil), signerScript..., + ), }}, cursor, pageSize, nil, opts, ) diff --git a/waved/operator_negotiation.go b/waved/operator_negotiation.go index 7c3bd9161..d51a81235 100644 --- a/waved/operator_negotiation.go +++ b/waved/operator_negotiation.go @@ -10,6 +10,7 @@ import ( "github.com/btcsuite/btcd/btcutil/v2" "github.com/lightninglabs/wavelength/arkrpc" "github.com/lightninglabs/wavelength/lib/batchschedule" + oortx "github.com/lightninglabs/wavelength/lib/tx/oor" "github.com/lightninglabs/wavelength/lib/types" mailboxconn "github.com/lightninglabs/wavelength/mailbox/conn" "github.com/lightninglabs/wavelength/serverconn" @@ -77,6 +78,17 @@ func operatorTermsFromResponse(resp *arkrpc.GetInfoResponse) ( } } + var oorCarrierPubKey *btcec.PublicKey + if len(resp.OorCarrierPubkey) > 0 { + oorCarrierPubKey, err = oortx.ParseCarrierPubKey( + resp.OorCarrierPubkey, + ) + if err != nil { + return nil, fmt.Errorf("parse oor carrier pubkey: %w", + err) + } + } + // The forfeit penalty key, sweep key and sweep delay are no longer // global operator terms; they are delivered per round in the batch // info, so GetInfo no longer carries them. @@ -97,6 +109,7 @@ func operatorTermsFromResponse(resp *arkrpc.GetInfoResponse) ( MaxOORLineageVBytes: resp.MaxOorLineageVbytes, MaxUserBalance: btcutil.Amount(resp.MaxUserBalance), AssetRefs: assetRefs, + OORCarrierPubKey: oorCarrierPubKey, }, nil } diff --git a/waved/operator_negotiation_test.go b/waved/operator_negotiation_test.go index 27fb2bda9..044e6c1ef 100644 --- a/waved/operator_negotiation_test.go +++ b/waved/operator_negotiation_test.go @@ -249,6 +249,33 @@ func TestOperatorTermsAssets(t *testing.T) { require.Empty(t, terms.AssetRefs) } +// TestOperatorTermsOORCarrierPubKey verifies parsing of the optional +// oor_carrier_pubkey field on GetInfo responses. +func TestOperatorTermsOORCarrierPubKey(t *testing.T) { + t.Parallel() + + carrierPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + + terms, err := operatorTermsFromResponse(&arkrpc.GetInfoResponse{ + Pubkey: testOperatorPubKeyBytes(t), + OorCarrierPubkey: carrierPriv.PubKey().SerializeCompressed(), + }) + require.NoError(t, err) + require.NotNil(t, terms.OORCarrierPubKey) + require.Equal( + t, carrierPriv.PubKey().SerializeCompressed(), + terms.OORCarrierPubKey.SerializeCompressed(), + ) + + // Malformed carrier pubkey fails closed. + _, err = operatorTermsFromResponse(&arkrpc.GetInfoResponse{ + Pubkey: testOperatorPubKeyBytes(t), + OorCarrierPubkey: []byte{0x01, 0x02}, + }) + require.ErrorContains(t, err, "oor carrier pubkey") +} + // TestNegotiateArkBootstrapZeroSelection proves the client refuses to bootstrap // when the operator returns a zero selection (no common version, or a // pre-versioning server). There is no legacy fallback. diff --git a/waved/receive_script.go b/waved/receive_script.go index ce2b86f6d..b33c79e28 100644 --- a/waved/receive_script.go +++ b/waved/receive_script.go @@ -125,7 +125,13 @@ func ResolveOwnedReceiveScriptKey(ctx context.Context, "script must be provided") } - rec, err := store.LookupOwnedReceiveScript(ctx, recipient.PkScript) + lookupScript, err := recipient.RoutingPkScript() + if err != nil { + return keychain.KeyDescriptor{}, fmt.Errorf("resolve routing "+ + "receive script: %w", err) + } + + rec, err := store.LookupOwnedReceiveScript(ctx, lookupScript) if err != nil { if errors.Is(err, sql.ErrNoRows) { return keychain.KeyDescriptor{}, diff --git a/waved/receive_script_test.go b/waved/receive_script_test.go index 45d539f7a..f98686a54 100644 --- a/waved/receive_script_test.go +++ b/waved/receive_script_test.go @@ -9,10 +9,14 @@ import ( "time" "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/txscript/v2" btclog "github.com/btcsuite/btclog/v2" "github.com/lightninglabs/wavelength/arkrpc" "github.com/lightninglabs/wavelength/db" "github.com/lightninglabs/wavelength/indexer" + "github.com/lightninglabs/wavelength/lib/arkscript" + oortx "github.com/lightninglabs/wavelength/lib/tx/oor" mailboxrpc "github.com/lightninglabs/wavelength/mailbox/rpc" "github.com/lightninglabs/wavelength/oor" fn "github.com/lightningnetwork/lnd/fn/v2" @@ -464,3 +468,77 @@ func TestFallbackSchnorrSignerPreservesPrimaryError(t *testing.T) { "fallback error must be reported alongside primary", ) } + +// TestResolveOwnedReceiveScriptKeyAssetComposed verifies that an incoming +// asset-bearing recipient output resolves its owning receive key via the +// uncomposed policy routing script after verifying the composed pkScript. +func TestResolveOwnedReceiveScriptKeyAssetComposed(t *testing.T) { + t.Parallel() + + clientKey := testKeyDescriptor(t, 4) + operatorPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + + policyBytes, err := arkscript.EncodeStandardVTXOTemplate( + clientKey.PubKey, operatorPriv.PubKey(), 144, + ) + require.NoError(t, err) + template, err := arkscript.DecodePolicyTemplate(policyBytes) + require.NoError(t, err) + compiled, err := template.Compile() + require.NoError(t, err) + uncomposedScript, err := txscript.PayToTaprootScript( + compiled.OutputKey(), + ) + require.NoError(t, err) + + assetRoot := chainhash.Hash{0xaa, 0xbb} + composed, err := arkscript.ComposeWithSiblingRoot(compiled, assetRoot) + require.NoError(t, err) + composedScript, err := txscript.PayToTaprootScript( + composed.OutputKey(), + ) + require.NoError(t, err) + + store := &testReceiveScriptStore{ + records: []db.OwnedReceiveScriptRecord{{ + PkScript: uncomposedScript, + ClientKey: clientKey, + Source: db.OwnedReceiveScriptSourceWallet, + }}, + } + + gotKey, err := ResolveOwnedReceiveScriptKey( + t.Context(), store, oor.ArkRecipientOutput{ + OutputIndex: 0, + Value: 1_000, + PkScript: composedScript, + VTXOPolicyTemplate: policyBytes, + Asset: &oortx.RecipientAsset{ + Root: assetRoot, + Ref: "asset-usd", + Amount: 500, + }, + }, + ) + require.NoError(t, err) + require.Equal(t, clientKey, gotKey) + + // A tampered asset root must fail rather than fall back to uncomposed + // ownership lookup. + badRoot := chainhash.Hash{0xcc} + _, err = ResolveOwnedReceiveScriptKey( + t.Context(), store, oor.ArkRecipientOutput{ + OutputIndex: 0, + Value: 1_000, + PkScript: composedScript, + VTXOPolicyTemplate: policyBytes, + Asset: &oortx.RecipientAsset{ + Root: badRoot, + Ref: "asset-usd", + Amount: 500, + }, + }, + ) + require.ErrorContains(t, err, "does not match pkscript") +} diff --git a/waved/rpc_auth.go b/waved/rpc_auth.go index f3642de61..4abbc7de0 100644 --- a/waved/rpc_auth.go +++ b/waved/rpc_auth.go @@ -138,8 +138,8 @@ func newWavedRPCPermissions() map[string][]bakery.Op { "ListOORSessions", "GetOORSession", ) grant( - daemon, entityOOR, "write", "SendOOR", "PrepareOOR", - "SignOORCustomInput", + daemon, entityOOR, "write", "SendOOR", "SendAssetOOR", + "PrepareOOR", "SignOORCustomInput", ) grant( daemon, entityOnChain, "read", "ListBoardingSweeps", diff --git a/waved/rpc_auth_test.go b/waved/rpc_auth_test.go index 97b1da6ad..da3913101 100644 --- a/waved/rpc_auth_test.go +++ b/waved/rpc_auth_test.go @@ -206,6 +206,7 @@ func TestWavedRPCPermissionsEntityMapping(t *testing.T) { fullDaemonMethod("Board"): entityOnChain, fullDaemonMethod("SendOnChain"): entityOnChain, fullDaemonMethod("SendOOR"): entityOOR, + fullDaemonMethod("SendAssetOOR"): entityOOR, fullDaemonMethod("JoinNextRound"): entityRound, fullDaemonMethod("EstimateFee"): entityFees, fullDaemonMethod("ArmVHTLCRecovery"): entityRecovery, diff --git a/waved/rpc_server.go b/waved/rpc_server.go index 2a9e1a0c4..f2b1f1e04 100644 --- a/waved/rpc_server.go +++ b/waved/rpc_server.go @@ -133,6 +133,11 @@ type RPCServer struct { // without booting the receive-script persistence stack. oorChangeRecipientOverride func(context.Context, btcutil.Amount) ( oortx.RecipientOutput, error) + + // oorCarrierLeaseOverride lets focused RPC tests supply an operator + // carrier float lease without booting a mailbox transport. + oorCarrierLeaseOverride func(context.Context, btcutil.Amount, + string) (*oor.OORCarrierLease, error) } // NewRPCServer creates a new RPCServer backed by the given Server. diff --git a/waved/server.go b/waved/server.go index ba201cfa0..141794903 100644 --- a/waved/server.go +++ b/waved/server.go @@ -4511,6 +4511,8 @@ func (s *Server) connectAndBootstrapMailbox(ctx context.Context) error { // The boarding backend is selected based on the wallet type: in lnd // mode it uses lndbackend.BoardingBackend, in lwwallet mode it uses // the lwwallet's BoardingBackendAdapter. +// +//nolint:contextcheck // wallet actor owns lifecycle after registration func (s *Server) initWalletActor(ctx context.Context, chainSourceRef actor.ActorRef[ chainsource.ChainSourceMsg, chainsource.ChainSourceResp, @@ -5102,6 +5104,7 @@ func (s *Server) initOORActor(ctx context.Context, OperatorKey: operatorTerms.PubKey, ExitDelay: operatorTerms.VTXOExitDelay, AuthenticateIncomingExpiry: s.expiryAuthenticator, + VerifyIncomingAssetPackage: s.verifyIncomingAssetOOR, NotifyIncomingVTXOs: func(ctx context.Context, descs []*vtxo.Descriptor) error { diff --git a/waved/serverconn_builder.go b/waved/serverconn_builder.go index 3d1aed650..febd1837c 100644 --- a/waved/serverconn_builder.go +++ b/waved/serverconn_builder.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/lightninglabs/wavelength/indexer" + "github.com/lightninglabs/wavelength/serverconn" "google.golang.org/protobuf/proto" ) @@ -51,3 +52,39 @@ func (b *serverDurableUnaryBuilder) BuildListVTXOsByScriptsRequest( ctx, scopes, afterCursor, limit, nil, ) } + +// BuildListVTXOsByScopedScriptsRequest builds the proof-gated indexer request +// body for one or more taproot VTXO scopes whose local proof signing key is +// resolved through an optional uncomposed signerScript. +func (b *serverDurableUnaryBuilder) BuildListVTXOsByScopedScriptsRequest( + ctx context.Context, pkScripts, signerScripts [][]byte, + afterCursor []byte, limit uint32) (proto.Message, error) { + + if b == nil || b.server == nil || b.server.indexer == nil { + return nil, fmt.Errorf("indexer client not initialized") + } + if len(signerScripts) > 0 && len(signerScripts) != len(pkScripts) { + return nil, fmt.Errorf("signer scripts count %d does not "+ + "match pk scripts count %d", len(signerScripts), + len(pkScripts)) + } + + scopes := make([]indexer.TaprootScriptScope, 0, len(pkScripts)) + for i := range pkScripts { + scope := indexer.TaprootScriptScope{ + PkScript: append([]byte(nil), pkScripts[i]...), + } + if i < len(signerScripts) && len(signerScripts[i]) > 0 { + scope.SignerScript = append( + []byte(nil), signerScripts[i]..., + ) + } + scopes = append(scopes, scope) + } + + return b.server.indexer.BuildListVTXOsByScriptsTaprootRequest( + ctx, scopes, afterCursor, limit, nil, + ) +} + +var _ serverconn.ScopedVTXOQueryBuilder = (*serverDurableUnaryBuilder)(nil) diff --git a/waved/wallet_recovery.go b/waved/wallet_recovery.go index b37dcbe68..189e9e1b7 100644 --- a/waved/wallet_recovery.go +++ b/waved/wallet_recovery.go @@ -757,6 +757,7 @@ func (r *RPCServer) recoveryOORHandler( OperatorKey: terms.PubKey, ExitDelay: terms.VTXOExitDelay, AuthenticateIncomingExpiry: r.server.expiryAuthenticator, + VerifyIncomingAssetPackage: r.server.verifyIncomingAssetOOR, // Recovery materializes receives without going through the // session actor, so the ledger emission the session behaviour @@ -870,9 +871,12 @@ func (r *RPCServer) materializeRecoveredOOREvent(ctx context.Context, return fmt.Errorf("decode incoming event: %w", err) } - recipients, err := oor.ExtractArkRecipients(incoming.ArkPSBT) - if err != nil { - return fmt.Errorf("extract recipients: %w", err) + recipients := oor.CloneArkRecipients(incoming.Recipients) + if len(recipients) == 0 { + recipients, err = oor.ExtractArkRecipients(incoming.ArkPSBT) + if err != nil { + return fmt.Errorf("extract recipients: %w", err) + } } metadataMatches := make( @@ -939,6 +943,7 @@ func (r *RPCServer) materializeRecoveredOOREvent(ctx context.Context, Recipients: recipients, MetadataMatches: metadataMatches, AncestorPackages: incoming.AncestorPackages, + TaprootAssetTransfer: incoming.TaprootAssetTransfer, }, ) if err != nil { From 4b7ab5cbabc387b433b7ccc5f684a649200bfc90 Mon Sep 17 00:00:00 2001 From: Dario Anongba Varela Date: Thu, 26 Nov 2026 23:52:38 +0100 Subject: [PATCH 10/15] systest: add real embedded-engine asset OOR merge and claim test Add TestAssetOORMergeAndClaim running two real embedded-engine waved daemons on regtest bitcoind, Esplora, and tapd: Alice merges two confirmed-round V1 asset VTXOs (400 + 300 units) via SendAssetOOR using an operator-leased carrier float, Bob authenticates batch expiry with BatchAssetRoot and verifies the merged 550-unit VTXO while Alice receives her 150-unit asset change and 2,000-sat carrier return, and Bob unilaterally exits and claims all 550 units into his embedded asset wallet. --- systest/asset_oor_test.go | 2128 +++++++++++++++++++++++++++++++++++++ systest/send_vtxo_test.go | 57 +- 2 files changed, 2166 insertions(+), 19 deletions(-) create mode 100644 systest/asset_oor_test.go diff --git a/systest/asset_oor_test.go b/systest/asset_oor_test.go new file mode 100644 index 000000000..e6dd93655 --- /dev/null +++ b/systest/asset_oor_test.go @@ -0,0 +1,2128 @@ +//go:build systest + +package systest + +import ( + "bytes" + "context" + "encoding/hex" + "errors" + "fmt" + "net" + "os" + "sort" + "sync" + "testing" + "time" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcec/v2/schnorr" + "github.com/btcsuite/btcd/btcec/v2/schnorr/musig2" + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/chaincfg/v2" + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/psbt/v2" + "github.com/btcsuite/btcd/txscript/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/btcsuite/btclog/v2" + tapsdk "github.com/lightninglabs/tap-sdk" + "github.com/lightninglabs/tap-sdk/customanchor" + tapgrpc "github.com/lightninglabs/tap-sdk/grpc" + "github.com/lightninglabs/wavelength/arkrpc" + "github.com/lightninglabs/wavelength/db" + "github.com/lightninglabs/wavelength/harness" + "github.com/lightninglabs/wavelength/lib/arkscript" + "github.com/lightninglabs/wavelength/lib/tree" + oortx "github.com/lightninglabs/wavelength/lib/tx/oor" + "github.com/lightninglabs/wavelength/lib/tx/psbtutil" + "github.com/lightninglabs/wavelength/lib/types" + mailboxpb "github.com/lightninglabs/wavelength/mailbox/pb" + "github.com/lightninglabs/wavelength/round" + "github.com/lightninglabs/wavelength/rpc/oorpb" + "github.com/lightninglabs/wavelength/serverconn" + "github.com/lightninglabs/wavelength/tapassets" + "github.com/lightninglabs/wavelength/vtxo" + "github.com/lightninglabs/wavelength/waved" + "github.com/lightninglabs/wavelength/waverpc" + "github.com/lightningnetwork/lnd/clock" + fn "github.com/lightningnetwork/lnd/fn/v2" + "github.com/lightningnetwork/lnd/keychain" + "github.com/lightningnetwork/lnd/lnrpc/walletrpc" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/anypb" +) + +const ( + // assetOORExitDelay is the short CSV exit delay used by the OOR + // unilateral-exit and claim systest so regtest mining stays fast while + // satisfying the minimum OOR checkpoint CSV delay (10 blocks). + assetOORExitDelay = uint32(10) + + // assetOORBatchSweepDelay is the operator sweep delay committed into + // the test commitment transaction's batch outputs. + assetOORBatchSweepDelay = uint32(500) + + // assetOORMinVTXOSat is the minimum VTXO value and per-leaf carrier + // budget for the test operator. + assetOORMinVTXOSat = int64(1_000) + + // assetOORFloatValueSat is the value of the operator carrier float + // VTXO leased to fund new asset leaves in the OOR transfer. + assetOORFloatValueSat = int64(10_000) + + // assetOORLeaf0Units and assetOORLeaf1Units are Alice's two input + // asset VTXOs merged by SendAssetOOR. + assetOORLeaf0Units = uint64(400) + assetOORLeaf1Units = uint64(300) + + // assetOORSendUnits is the amount Alice sends to Bob, forcing a merge + // of both leaves (400 + 300 -> 550 to Bob + 150 asset change). + assetOORSendUnits = uint64(550) +) + +// TestAssetOORMergeAndClaim exercises the real embedded Taproot Assets OOR +// lifecycle end to end on regtest: Alice merges two confirmed-round asset +// VTXOs (400 + 300 units) via SendAssetOOR using an operator-leased carrier +// float, Bob receives and verifies the merged 550-unit VTXO (persisting its +// sealed Ark asset package) while Alice receives her 150-unit asset change +// and 2,000-sat carrier return, and Bob finally unrolls and claims all 550 +// units unilaterally on-chain into his real embedded asset wallet. +func TestAssetOORMergeAndClaim(t *testing.T) { + ParallelN(t) + + h := NewSysTestHarness(t, func(opts *harness.Options) { + opts.StartTapd = true + }) + h.Harness.FundOperatorLND(btcutil.SatoshiPerBitcoin) + + issuer := newAssetTestTapd(t, h) + ref := mintV1AssetTestAsset( + t, h, issuer, assetOORLeaf0Units+assetOORLeaf1Units, + ) + + op := newAssetOORTestOperator(t, ref) + + aliceDir := t.TempDir() + bobDir := t.TempDir() + alice := startEmbeddedAssetDaemonAt(t, h, aliceDir, op.mailboxAddr) + bob := startEmbeddedAssetDaemonAt(t, h, bobDir, op.mailboxAddr) + + // Give Bob extra confirmed wallet UTXOs so parallel CPFP bumps across + // his multi-input unroll DAG do not wait on change from a single UTXO. + fundDaemonWalletExtraUTXOs(t, h, bob, 3) + + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Minute) + defer cancel() + + // Allocate two receive scripts on Alice (so her wallet owns both real + // leaf keys) and one receive script on Bob (also registering Bob's + // routing script with the fake operator). + aliceRecv0, err := alice.client.NewReceiveScript( + ctx, &waverpc.NewReceiveScriptRequest{ + Label: "alice-leaf-0", + }, + ) + require.NoError(t, err) + aliceRecv1, err := alice.client.NewReceiveScript( + ctx, &waverpc.NewReceiveScriptRequest{ + Label: "alice-leaf-1", + }, + ) + require.NoError(t, err) + bobRecv, err := bob.client.NewReceiveScript( + ctx, &waverpc.NewReceiveScriptRequest{ + Label: "bob-recv", + }, + ) + require.NoError(t, err) + + // Stop Alice briefly so we can inspect her persisted receive-key + // descriptors and seed two real asset VTXOs backed by a real confirmed + // commitment transaction and signed asset tree. + alice.stop() + + aliceKey0 := lookupOwnedReceiveKey( + t, alice.cfg, aliceRecv0.PkScriptHex, + ) + aliceKey1 := lookupOwnedReceiveKey( + t, alice.cfg, aliceRecv1.PkScriptHex, + ) + + roundFixture := buildRealAssetOORRoundFixture( + t, h, issuer, ref, op, aliceKey0, aliceKey1, + ) + op.installRoundFixture(roundFixture) + + seedRealAssetVTXOs(t, alice.cfg, op, roundFixture) + + // Restart Alice so her VTXO manager loads both real live asset VTXOs. + alice = startEmbeddedAssetDaemonAt(t, h, aliceDir, op.mailboxAddr) + + require.Eventually(t, func() bool { + return len(listAllVTXOs(t, alice.client)) == 2 + }, 30*time.Second, 200*time.Millisecond, + "Alice never loaded seeded asset VTXOs") + + // Alice merges both asset VTXOs (400 + 300) and sends 550 units to Bob. + bobPubkeyBytes, err := hex.DecodeString(bobRecv.PubkeyXonlyHex) + require.NoError(t, err) + + sendResp, err := alice.client.SendAssetOOR( + ctx, &waverpc.SendAssetOORRequest{ + Destination: &waverpc.SendAssetOORRequest_Pubkey{ + Pubkey: bobPubkeyBytes, + }, + AssetRef: ref.String(), + Amount: assetOORSendUnits, + }, + ) + require.NoError(t, err) + require.Equal(t, "submitted", sendResp.Status) + require.EqualValues(t, 2, sendResp.SelectedInputCount) + require.EqualValues( + t, assetOORLeaf0Units+assetOORLeaf1Units-assetOORSendUnits, + sendResp.AssetChangeAmount, + ) + require.EqualValues( + t, 2*assetOORMinVTXOSat, sendResp.SenderBtcChangeSat, + ) + require.False(t, sendResp.FailedBeforePonr) + require.NotEmpty(t, sendResp.RecipientOutpoint) + + bobOutpoint, err := wire.NewOutPointFromString( + sendResp.RecipientOutpoint, + ) + require.NoError(t, err) + + // Wait for Bob to receive, authenticate, verify on his real embedded + // engine, and materialize the merged 550-unit asset VTXO. + var bobVTXO *waverpc.VTXO + require.Eventually(t, func() bool { + v := findVTXOByOutpoint( + listAllVTXOs(t, bob.client), *bobOutpoint, + ) + if v == nil || v.Status != waverpc.VTXOStatus_VTXO_STATUS_LIVE { + return false + } + bobVTXO = v + + return true + }, time.Minute, 250*time.Millisecond, + "Bob never materialized incoming merged asset VTXO %s", + bobOutpoint) + + require.EqualValues(t, assetOORMinVTXOSat, bobVTXO.AmountSat) + require.EqualValues(t, assetOORSendUnits, bobVTXO.AssetAmount) + require.Equal(t, ref.String(), bobVTXO.AssetRef) + require.NotEmpty(t, bobVTXO.AssetRoot) + + // Also verify Alice's two old asset VTXOs are spent and she received + // both her 150-unit asset change VTXO and her 2,000-sat BTC carrier + // return VTXO. + require.Eventually(t, func() bool { + listCtx, listCancel := context.WithTimeout( + t.Context(), 5*time.Second, + ) + defer listCancel() + + resp, err := alice.client.ListVTXOs( + listCtx, &waverpc.ListVTXOsRequest{ + Statuses: []waverpc.VTXOStatus{ + waverpc.VTXOStatus_VTXO_STATUS_LIVE, + waverpc.VTXOStatus_VTXO_STATUS_SPENT, + }, + }, + ) + if err != nil { + return false + } + + var ( + spentOld int + liveAssetChg bool + liveBTCChg bool + ) + leaf0OP := roundFixture.leaf0.Outpoint.String() + leaf1OP := roundFixture.leaf1.Outpoint.String() + for _, v := range resp.Vtxos { + switch { + case v.Outpoint == leaf0OP || v.Outpoint == leaf1OP: + if v.Status == + waverpc.VTXOStatus_VTXO_STATUS_SPENT { + + spentOld++ + } + + case v.Status == waverpc.VTXOStatus_VTXO_STATUS_LIVE && + v.AssetAmount == 150 && + v.AmountSat == assetOORMinVTXOSat: + + liveAssetChg = true + + case v.Status == waverpc.VTXOStatus_VTXO_STATUS_LIVE && + v.AssetAmount == 0 && + v.AmountSat == 2*assetOORMinVTXOSat: + + liveBTCChg = true + } + } + + return spentOld == 2 && liveAssetChg && liveBTCChg + }, time.Minute, 250*time.Millisecond, + "Alice did not settle spent inputs and change VTXOs") + + // Trigger a real unilateral exit on Bob's merged OOR asset VTXO. Bob's + // unroll subsystem broadcasts the asset tree, float tree, all three + // checkpoints, and the Ark tx, waits for CSV maturity, and invokes + // assetVTXOClaimer on Bob's real embedded asset engine. + unrollResp, err := bob.client.Unroll(ctx, &waverpc.UnrollRequest{ + Outpoint: bobOutpoint.String(), + }) + require.NoError(t, err) + require.NotEmpty(t, unrollResp.ActorId) + + // Drive block production on regtest as Bob's unroll broadcasts each + // tier of the DAG, matures the CSV exit delay, and finalizes the claim. + require.Eventually(t, func() bool { + h.Harness.Generate(1) + + return embeddedAssetUnits(t, bob.client, ref) == + assetOORSendUnits + }, 3*time.Minute, 2*time.Second, + "Bob never unilaterally claimed 550 merged asset units") +} + +// assetOORLeafSpec holds one real materialized asset leaf ready to seed into +// Alice's database and index on the fake operator. +type assetOORLeafSpec struct { + Outpoint wire.OutPoint + Amount btcutil.Amount + PolicyTemplate []byte + PkScript []byte + ClientKey keychain.KeyDescriptor + TapScript *vtxo.Descriptor + AssetRoot chainhash.Hash + AssetAmount uint64 + SealedPackage []byte + TreePath *tree.Tree +} + +// assetOORRoundFixture holds the real confirmed commitment tx, signed asset +// tree, and signed carrier float tree for the systest. +type assetOORRoundFixture struct { + roundID round.RoundID + ref tapsdk.AssetRef + commitTx *wire.MsgTx + commitTxID chainhash.Hash + commitHeight int32 + batchExpiry int32 + sweepLeaf txscript.TapLeaf + sweepRoot chainhash.Hash + assetTree *tree.Tree + floatTree *tree.Tree + leaf0 assetOORLeafSpec + leaf1 assetOORLeafSpec + floatOutpoint wire.OutPoint + floatPolicy []byte + floatPkScript []byte + floatValueSat int64 + floatTreePath *tree.Tree + assetTreePath0 *tree.Tree + assetTreePath1 *tree.Tree +} + +// indexedOOROutput records one finalized OOR recipient output indexed by the +// fake operator for ListVTXOsByScripts and ListOORRecipientEventsByScript. +type indexedOOROutput struct { + sessionID chainhash.Hash + eventID uint64 + outputIndex uint32 + value uint64 + composedPkScript []byte + routingPkScript []byte + policyTemplate []byte + assetRoot []byte + assetRef string + assetAmount uint64 + arkPSBT []byte + checkpointPSBTs [][]byte + assetTransfer []byte + ancestryPaths []*arkrpc.AncestryPath +} + +// submittedOORSession stores the submit request and cosigned Ark PSBT between +// SubmitPackage and FinalizePackage. +type submittedOORSession struct { + req *oorpb.SubmitPackageRequest + cosignedArk []byte +} + +// assetOORTestOperator wraps fakeMailboxServer with real Taproot OOR +// cosigning, carrier float leasing, receive-script registration, and indexer +// queries so two real waved instances can execute an end-to-end asset OOR +// transfer without mocking any daemon subsystem. +type assetOORTestOperator struct { + t *testing.T + ref tapsdk.AssetRef + operatorKey *btcec.PrivateKey + carrierKey *btcec.PrivateKey + mailboxAddr string + mailbox *fakeMailboxServer + + mu sync.Mutex + fixture *assetOORRoundFixture + registeredByHex map[string]string + submittedByID map[chainhash.Hash]*submittedOORSession + indexedOutputs []indexedOOROutput + nextEventID uint64 +} + +// newAssetOORTestOperator starts a fake operator configured for asset OOR +// transfers with a short exit delay and a carrier float key. +func newAssetOORTestOperator(t *testing.T, + ref tapsdk.AssetRef) *assetOORTestOperator { + + t.Helper() + + operatorPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + carrierPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + + operatorInfo := &arkrpc.GetInfoResponse{ + Pubkey: operatorPriv.PubKey().SerializeCompressed(), + BoardingExitDelay: assetOORExitDelay, + VtxoExitDelay: assetOORExitDelay, + DustLimit: testDustLimitSat, + MinVtxoAmountSat: assetOORMinVTXOSat, + MinOperatorFee: testOperatorFeeSat, + MinConfirmations: 1, + SelectedArkVersion: arkrpc.ArkProtocolVersionV1, + ArkVersionPolicies: []*arkrpc.ArkVersionPolicy{{ + Version: arkrpc.ArkProtocolVersionV1, + State: arkrpc.ArkVersionPolicy_STATE_ACTIVE, + }}, + Assets: []*arkrpc.AssetPolicy{{ + AssetRef: ref.String(), + }}, + OorCarrierPubkey: carrierPriv.PubKey().SerializeCompressed(), + } + + mailboxAddr, mailbox, stopMailbox := startFakeMailboxServer( + t, + serverconn.PubKeyMailboxID( + operatorPriv.PubKey(), + ), + operatorInfo, + ) + t.Cleanup(stopMailbox) + mailbox.setFeeQuote(&arkrpc.EstimateFeeResponse{ + TotalFeeSat: testOperatorFeeSat, + }) + + op := &assetOORTestOperator{ + t: t, + ref: ref, + operatorKey: operatorPriv, + carrierKey: carrierPriv, + mailboxAddr: mailboxAddr, + mailbox: mailbox, + registeredByHex: make(map[string]string), + submittedByID: make(map[chainhash.Hash]*submittedOORSession), + } + + mailbox.mu.Lock() + mailbox.envelopeHandler = op.handleEnvelope + mailbox.mu.Unlock() + + return op +} + +// installRoundFixture attaches the confirmed commitment and trees to the fake +// operator so LeaseOORCarrier and ListVTXOsByScripts return real ancestry. +func (o *assetOORTestOperator) installRoundFixture(f *assetOORRoundFixture) { + o.mu.Lock() + defer o.mu.Unlock() + + o.fixture = f +} + +// handleEnvelope intercepts operator and indexer mailbox RPCs required for an +// end-to-end asset OOR send and receive. +func (o *assetOORTestOperator) handleEnvelope(ctx context.Context, + env *mailboxpb.Envelope) (bool, error) { + + _ = ctx + if env.Rpc == nil { + return false, nil + } + + switch { + case env.Rpc.Service == "arkrpc.ArkService" && + env.Rpc.Method == "LeaseOORCarrier": + return true, o.handleLeaseOORCarrier(env) + + case env.Rpc.Service == "arkrpc.IndexerService" && + env.Rpc.Method == "RegisterReceiveScript": + return true, o.handleRegisterReceiveScript(env) + + case env.Rpc.Service == "arkrpc.IndexerService" && + env.Rpc.Method == "ListOORRecipientEventsByScript": + return true, o.handleListOORRecipientEventsByScript(env) + + case env.Rpc.Service == "arkrpc.IndexerService" && + env.Rpc.Method == "ListVTXOsByScripts": + return true, o.handleListVTXOsByScripts(env) + + case env.Rpc.Service == oorpb.ServiceName && + env.Rpc.Method == oorpb.MethodSubmitPackage: + return true, o.handleSubmitPackage(env) + + case env.Rpc.Service == oorpb.ServiceName && + env.Rpc.Method == oorpb.MethodFinalizePackage: + return true, o.handleFinalizePackage(env) + + case env.Rpc.Service == oorpb.ServiceName && + env.Rpc.Method == oorpb.MethodIncomingAck: + return true, nil + + default: + return false, nil + } +} + +// replyUnary enqueues a KIND_RESPONSE mailbox envelope back to the caller. +func (o *assetOORTestOperator) replyUnary(env *mailboxpb.Envelope, + sender string, msg proto.Message) error { + + body, err := anypb.New(msg) + if err != nil { + return fmt.Errorf("wrap response %T: %w", msg, err) + } + + recipient := env.Rpc.ReplyTo + if recipient == "" { + recipient = env.Sender + } + + o.mailbox.enqueueEnvelope(&mailboxpb.Envelope{ + ProtocolVersion: env.ProtocolVersion, + ArkProtocolVersion: env.ArkProtocolVersion, + Sender: sender, + Recipient: recipient, + CreatedAtUnixMs: time.Now().UnixMilli(), + Body: body, + Rpc: &mailboxpb.RpcMeta{ + Kind: mailboxpb.RpcMeta_KIND_RESPONSE, + Service: env.Rpc.Service, + Method: env.Rpc.Method, + CorrelationId: env.Rpc.CorrelationId, + }, + }) + + return nil +} + +// handleRegisterReceiveScript records the daemon mailbox owning each +// registered uncomposed receive script so IncomingOOREvent can be pushed. +func (o *assetOORTestOperator) handleRegisterReceiveScript( + env *mailboxpb.Envelope) error { + + var req arkrpc.RegisterReceiveScriptRequest + if err := env.Body.UnmarshalTo(&req); err != nil { + return fmt.Errorf("decode RegisterReceiveScript: %w", err) + } + + o.mu.Lock() + o.registeredByHex[hex.EncodeToString(req.PkScript)] = env.Sender + o.mu.Unlock() + + return o.replyUnary( + env, serverconn.IndexerMailboxID, + &arkrpc.RegisterReceiveScriptResponse{}, + ) +} + +// handleLeaseOORCarrier leases the fixture's confirmed carrier float VTXO. +func (o *assetOORTestOperator) handleLeaseOORCarrier( + env *mailboxpb.Envelope) error { + + var req arkrpc.LeaseOORCarrierRequest + if err := env.Body.UnmarshalTo(&req); err != nil { + return fmt.Errorf("decode LeaseOORCarrier: %w", err) + } + + o.mu.Lock() + f := o.fixture + o.mu.Unlock() + if f == nil { + return fmt.Errorf("round fixture not installed") + } + + resp := &arkrpc.LeaseOORCarrierResponse{ + Outpoint: f.floatOutpoint.String(), + ValueSat: f.floatValueSat, + VtxoPolicyTemplate: bytes.Clone(f.floatPolicy), + PkScript: bytes.Clone(f.floatPkScript), + ExpiresAtUnix: time.Now().Add(5 * time.Minute).Unix(), + } + + return o.replyUnary(env, o.mailbox.operatorMailbox, resp) +} + +// handleSubmitPackage cosigns every checkpoint and Ark input with the operator +// key, signs the leased carrier float checkpoint and Ark input with the +// carrier key, and returns SubmitPackageResponse. +func (o *assetOORTestOperator) handleSubmitPackage( + env *mailboxpb.Envelope) error { + + var req oorpb.SubmitPackageRequest + if err := env.Body.UnmarshalTo(&req); err != nil { + return fmt.Errorf("decode SubmitPackage: %w", err) + } + + arkPkt, err := psbtutil.Parse(req.ArkPsbt) + if err != nil { + return fmt.Errorf("parse submit ark psbt: %w", err) + } + checkpoints := make([]*psbt.Packet, len(req.CheckpointPsbts)) + for i, raw := range req.CheckpointPsbts { + cp, err := psbtutil.Parse(raw) + if err != nil { + return fmt.Errorf("parse submit checkpoint %d: %w", i, + err) + } + checkpoints[i] = cp + } + + if _, err := oortx.ValidateSubmitPackage( + arkPkt, checkpoints, + ); err != nil { + return fmt.Errorf("validate submit package: %w", err) + } + + o.mu.Lock() + f := o.fixture + o.mu.Unlock() + if f == nil { + return fmt.Errorf("round fixture not installed") + } + + // Attach the spent VTXO's collaborative tapleaf (composed when asset- + // bearing) and sign every checkpoint with the operator key; sign the + // carrier float checkpoint with both carrier and operator keys. + if len(req.SigningDescriptors) != len(checkpoints) { + return fmt.Errorf("signing descriptor count %d != checkpoint "+ + "count %d", len(req.SigningDescriptors), + len(checkpoints)) + } + + var floatCheckpointTxID chainhash.Hash + for i, cp := range checkpoints { + if err := attachCheckpointCollabLeaf( + cp, req.SigningDescriptors[i], + ); err != nil { + return fmt.Errorf("attach checkpoint %d leaf: %w", i, + err) + } + + isFloat := cp.UnsignedTx.TxIn[0].PreviousOutPoint == + f.floatOutpoint + if err := signTaprootScriptInput( + cp, 0, o.operatorKey, + ); err != nil { + return fmt.Errorf("operator sign checkpoint %d: %w", i, + err) + } + if isFloat { + if err := signTaprootScriptInput( + cp, 0, o.carrierKey, + ); err != nil { + return fmt.Errorf("carrier sign float "+ + "checkpoint %d: %w", i, err) + } + floatCheckpointTxID = cp.UnsignedTx.TxHash() + } + } + + // Sign every Ark input with the operator key; also sign the carrier + // float Ark input with the carrier key. + for i := range arkPkt.UnsignedTx.TxIn { + if err := signTaprootScriptInput( + arkPkt, i, o.operatorKey, + ); err != nil { + return fmt.Errorf("operator sign ark input %d: %w", i, + err) + } + if arkPkt.UnsignedTx.TxIn[i].PreviousOutPoint.Hash == + floatCheckpointTxID { + + if err := signTaprootScriptInput( + arkPkt, i, o.carrierKey, + ); err != nil { + return fmt.Errorf("carrier sign float ark "+ + "input %d: %w", i, err) + } + } + } + + arkRaw, err := psbtutil.Serialize(arkPkt) + if err != nil { + return fmt.Errorf("serialize cosigned ark: %w", err) + } + cpRaws := make([][]byte, len(checkpoints)) + for i, cp := range checkpoints { + raw, err := psbtutil.Serialize(cp) + if err != nil { + return fmt.Errorf("serialize cosigned cp %d: %w", i, + err) + } + cpRaws[i] = raw + } + + sessionID := arkPkt.UnsignedTx.TxHash() + clonedReq, ok := proto.Clone(&req).(*oorpb.SubmitPackageRequest) + if !ok { + return fmt.Errorf("clone submit request failed") + } + o.mu.Lock() + o.submittedByID[sessionID] = &submittedOORSession{ + req: clonedReq, + cosignedArk: bytes.Clone(arkRaw), + } + o.mu.Unlock() + + resp := &oorpb.SubmitPackageResponse{ + Result: &oorpb.SubmitPackageResponse_Success{ + Success: &oorpb.SubmitPackageSuccess{ + SessionId: sessionID[:], + CoSignedArkPsbt: arkRaw, + CoSignedCheckpointPsbts: cpRaws, + }, + }, + } + + return o.replyUnary(env, o.mailbox.operatorMailbox, resp) +} + +// handleFinalizePackage validates the client-finalized checkpoints and Ark +// PSBT, indexes each recipient output, replies FinalizePackageResponse, and +// pushes IncomingOOREvent notifications to every registered recipient daemon. +func (o *assetOORTestOperator) handleFinalizePackage( + env *mailboxpb.Envelope) error { + + var req oorpb.FinalizePackageRequest + if err := env.Body.UnmarshalTo(&req); err != nil { + return fmt.Errorf("decode FinalizePackage: %w", err) + } + if len(req.SessionId) != chainhash.HashSize { + return fmt.Errorf("invalid finalize session id length %d", + len(req.SessionId)) + } + var sessionID chainhash.Hash + copy(sessionID[:], req.SessionId) + + o.mu.Lock() + submitted := o.submittedByID[sessionID] + f := o.fixture + o.mu.Unlock() + if submitted == nil || f == nil { + return fmt.Errorf("unknown OOR session %s", sessionID) + } + + arkPkt, err := psbtutil.Parse(submitted.cosignedArk) + if err != nil { + return fmt.Errorf("parse cosigned ark psbt: %w", err) + } + checkpoints := make([]*psbt.Packet, len(req.FinalCheckpointPsbts)) + for i, raw := range req.FinalCheckpointPsbts { + cp, err := psbtutil.Parse(raw) + if err != nil { + return fmt.Errorf("parse finalize checkpoint %d: %w", i, + err) + } + checkpoints[i] = cp + } + + if err := oortx.ValidateFinalizePackageSigned( + arkPkt, checkpoints, + ); err != nil { + return fmt.Errorf("validate finalize package signed: %w", err) + } + + submitReq := submitted.req + + // Build ancestry paths spanning both the asset tree (with + // BatchAssetRoot) and the operator carrier float tree. + assetAncestry, err := buildProtoAncestryPath( + f.assetTree, f.commitTxID, f.commitHeight, + o.operatorKey.PubKey(), assetOORBatchSweepDelay, []uint32{0, 1}, + ) + if err != nil { + return fmt.Errorf("build asset ancestry path: %w", err) + } + floatAncestry, err := buildProtoAncestryPath( + f.floatTree, f.commitTxID, f.commitHeight, + o.operatorKey.PubKey(), assetOORBatchSweepDelay, []uint32{2}, + ) + if err != nil { + return fmt.Errorf("build float ancestry path: %w", err) + } + ancestryPaths := []*arkrpc.AncestryPath{assetAncestry, floatAncestry} + + type pendingPush struct { + mailboxID string + event *arkrpc.IncomingOOREvent + } + var pushes []pendingPush + + o.mu.Lock() + for outIdx, rec := range submitReq.RecipientOutputs { + if outIdx >= len(arkPkt.UnsignedTx.TxOut) { + o.mu.Unlock() + + return fmt.Errorf("recipient output %d out of range", + outIdx) + } + + // Derive the uncomposed routing script from the policy + // template so registered receive scripts match both asset and + // plain Bitcoin outputs. + routingScript := bytes.Clone(rec.PkScript) + if len(rec.VtxoPolicyTemplate) > 0 { + tmpl, err := arkscript.DecodePolicyTemplate( + rec.VtxoPolicyTemplate, + ) + if err != nil { + o.mu.Unlock() + + return fmt.Errorf("decode recipient %d "+ + "policy: %w", outIdx, err) + } + routingScript, err = tmpl.PkScript() + if err != nil { + o.mu.Unlock() + + return fmt.Errorf("derive recipient %d "+ + "routing script: %w", outIdx, err) + } + } + + o.nextEventID++ + eventID := o.nextEventID + + var assetTransfer []byte + if len(rec.TaprootAssetRoot) > 0 { + assetTransfer = bytes.Clone( + submitReq.TaprootAssetTransfer, + ) + } + + out := indexedOOROutput{ + sessionID: sessionID, + eventID: eventID, + outputIndex: uint32(outIdx), + value: uint64(rec.ValueSat), + composedPkScript: bytes.Clone(rec.PkScript), + routingPkScript: routingScript, + policyTemplate: bytes.Clone(rec.VtxoPolicyTemplate), + assetRoot: bytes.Clone(rec.TaprootAssetRoot), + assetRef: rec.TaprootAssetRef, + assetAmount: rec.TaprootAssetAmount, + arkPSBT: bytes.Clone(submitted.cosignedArk), + checkpointPSBTs: cloneByteSlices( + req.FinalCheckpointPsbts, + ), + assetTransfer: assetTransfer, + ancestryPaths: ancestryPaths, + } + o.indexedOutputs = append(o.indexedOutputs, out) + + if mbID, ok := o.registeredByHex[hex.EncodeToString( + routingScript, + )]; ok { + + pushes = append(pushes, pendingPush{ + mailboxID: mbID, + event: &arkrpc.IncomingOOREvent{ + RecipientPkScript: routingScript, + RecipientEventId: eventID, + SessionId: sessionID[:], + OutputIndex: uint32(outIdx), + Value: uint64(rec.ValueSat), + }, + }) + } + } + o.mu.Unlock() + + // Acknowledge finalization to Alice first, then deliver push hints to + // each registered recipient daemon. + if err := o.replyUnary( + env, o.mailbox.operatorMailbox, + &oorpb.FinalizePackageResponse{ + SessionId: sessionID[:], + }, + ); err != nil { + return err + } + + for _, push := range pushes { + body, err := anypb.New(push.event) + if err != nil { + return fmt.Errorf("wrap IncomingOOREvent: %w", err) + } + o.mailbox.enqueueEnvelope(&mailboxpb.Envelope{ + ProtocolVersion: env.ProtocolVersion, + ArkProtocolVersion: env.ArkProtocolVersion, + Sender: serverconn.IndexerMailboxID, + Recipient: push.mailboxID, + CreatedAtUnixMs: time.Now().UnixMilli(), + Body: body, + Rpc: &mailboxpb.RpcMeta{ + Kind: mailboxpb.RpcMeta_KIND_EVENT, + Service: "arkrpc.ArkService", + Method: waved.MethodIncomingOOR, + ReplyTo: serverconn.IndexerMailboxID, + }, + }) + } + + return nil +} + +// handleListOORRecipientEventsByScript returns indexed recipient events +// matching the requested uncomposed routing script. +func (o *assetOORTestOperator) handleListOORRecipientEventsByScript( + env *mailboxpb.Envelope) error { + + var req arkrpc.ListOORRecipientEventsByScriptRequest + if err := env.Body.UnmarshalTo(&req); err != nil { + return fmt.Errorf("decode ListOORRecipientEventsByScript: %w", + err) + } + + o.mu.Lock() + var events []*arkrpc.OORRecipientEvent + for _, out := range o.indexedOutputs { + if !bytes.Equal(out.routingPkScript, req.PkScript) { + continue + } + if out.eventID <= req.AfterEventId { + continue + } + events = append(events, &arkrpc.OORRecipientEvent{ + RecipientPkScript: bytes.Clone(out.composedPkScript), + EventId: out.eventID, + SessionId: bytes.Clone(out.sessionID[:]), + OutputIndex: out.outputIndex, + Value: out.value, + ArkPsbt: bytes.Clone(out.arkPSBT), + CheckpointPsbts: cloneByteSlices( + out.checkpointPSBTs, + ), + VtxoPolicyTemplate: bytes.Clone(out.policyTemplate), + TaprootAssetRoot: bytes.Clone(out.assetRoot), + TaprootAssetRef: out.assetRef, + TaprootAssetAmount: out.assetAmount, + TaprootAssetTransfer: bytes.Clone(out.assetTransfer), + }) + } + o.mu.Unlock() + + return o.replyUnary( + env, serverconn.IndexerMailboxID, + &arkrpc.ListOORRecipientEventsByScriptResponse{ + Events: events, + }, + ) +} + +// handleListVTXOsByScripts returns indexed VTXO records with full ancestry for +// every requested script. +func (o *assetOORTestOperator) handleListVTXOsByScripts( + env *mailboxpb.Envelope) error { + + var req arkrpc.ListVTXOsByScriptsRequest + if err := env.Body.UnmarshalTo(&req); err != nil { + return fmt.Errorf("decode ListVTXOsByScripts: %w", err) + } + + o.mu.Lock() + f := o.fixture + outputs := append([]indexedOOROutput(nil), o.indexedOutputs...) + o.mu.Unlock() + if f == nil { + return fmt.Errorf("round fixture not installed") + } + + var matched []*arkrpc.VTXO + for _, scope := range req.Scripts { + wantScript := scope.GetPkScript() + for _, out := range outputs { + if !bytes.Equal(out.composedPkScript, wantScript) { + continue + } + matched = append(matched, &arkrpc.VTXO{ + Outpoint: &arkrpc.OutPoint{ + Txid: bytes.Clone(out.sessionID[:]), + Vout: out.outputIndex, + }, + ValueSat: out.value, + PkScript: bytes.Clone(out.composedPkScript), + Status: arkrpc.VTXOStatus_VTXO_STATUS_LIVE, + RoundId: f.roundID.String(), + CommitmentTxid: bytes.Clone( + f.commitTxID[:], + ), + CreatedHeight: f.commitHeight, + BatchExpiryHeight: f.batchExpiry, + RelativeExpiry: assetOORExitDelay, + ChainDepth: 1, + OperatorPubkey: o.operatorKey.PubKey(). + SerializeCompressed(), + ConstructionVersion: 1, + AncestryPaths: out.ancestryPaths, + AncestryPackages: []*arkrpc.OORSessionPackage{{ + SessionId: bytes.Clone( + out.sessionID[:], + ), + ArkPsbt: bytes.Clone(out.arkPSBT), + CheckpointPsbts: cloneByteSlices( + out.checkpointPSBTs, + ), + }}, + TaprootAssetRoot: bytes.Clone(out.assetRoot), + TaprootAssetRef: out.assetRef, + TaprootAssetAmount: out.assetAmount, + }) + } + } + + return o.replyUnary( + env, serverconn.IndexerMailboxID, + &arkrpc.ListVTXOsByScriptsResponse{ + Vtxos: matched, + }, + ) +} + +// buildProtoAncestryPath encodes a signed tree with sweep policy and +// confirmation height into an arkrpc.AncestryPath. +func buildProtoAncestryPath(t *tree.Tree, commitTxID chainhash.Hash, + commitHeight int32, sweepKey *btcec.PublicKey, sweepDelay uint32, + inputIndices []uint32) (*arkrpc.AncestryPath, error) { + + path, err := arkrpc.AncestryPathFromTree(t, commitTxID, inputIndices) + if err != nil { + return nil, err + } + path.CommitmentHeight = commitHeight + path.CommitmentSweepDelay = sweepDelay + path.CommitmentSweepKey = sweepKey.SerializeCompressed() + + return path, nil +} + +// signTaprootScriptInput appends a BIP-341 Tapscript Schnorr signature for +// privKey on the first TaprootLeafScript of pkt.Inputs[inputIdx]. +func signTaprootScriptInput(pkt *psbt.Packet, inputIdx int, + privKey *btcec.PrivateKey) error { + + if inputIdx < 0 || inputIdx >= len(pkt.Inputs) { + return fmt.Errorf("input index %d out of range", inputIdx) + } + in := &pkt.Inputs[inputIdx] + if len(in.TaprootLeafScript) == 0 { + return fmt.Errorf("input %d missing taproot leaf script", + inputIdx) + } + + prevOuts := make(map[wire.OutPoint]*wire.TxOut, len(pkt.Inputs)) + for i, pin := range pkt.Inputs { + if pin.WitnessUtxo == nil { + return fmt.Errorf("input %d missing witness utxo", i) + } + prevOuts[pkt.UnsignedTx.TxIn[i].PreviousOutPoint] = + pin.WitnessUtxo + } + fetcher := txscript.NewMultiPrevOutFetcher(prevOuts) + + leafScript := in.TaprootLeafScript[0] + tapLeaf := txscript.NewTapLeaf( + leafScript.LeafVersion, leafScript.Script, + ) + leafHash := tapLeaf.TapHash() + + sigHashes := txscript.NewTxSigHashes(pkt.UnsignedTx, fetcher) + sigHash, err := txscript.CalcTapscriptSignaturehash( + sigHashes, txscript.SigHashDefault, pkt.UnsignedTx, inputIdx, + fetcher, tapLeaf, + ) + if err != nil { + return fmt.Errorf("calc tapscript sighash: %w", err) + } + sig, err := schnorr.Sign(privKey, sigHash) + if err != nil { + return fmt.Errorf("schnorr sign: %w", err) + } + + in.TaprootScriptSpendSig = append( + in.TaprootScriptSpendSig, + &psbt.TaprootScriptSpendSig{ + XOnlyPubKey: schnorr.SerializePubKey(privKey.PubKey()), + LeafHash: leafHash[:], + Signature: sig.Serialize(), + SigHash: txscript.SigHashDefault, + }, + ) + + return nil +} + +// attachCheckpointCollabLeaf derives the collaborative spend leaf and control +// block for the spent VTXO (composed with TaprootAssetRoot when asset-bearing) +// and attaches it to checkpoint input 0 if not already present. +func attachCheckpointCollabLeaf(cp *psbt.Packet, + desc *oorpb.OORSigningDescriptor) error { + + if desc == nil || len(desc.VtxoPolicyTemplate) == 0 { + return fmt.Errorf("missing vtxo policy template") + } + + template, err := arkscript.DecodePolicyTemplate(desc.VtxoPolicyTemplate) + if err != nil { + return fmt.Errorf("decode vtxo policy: %w", err) + } + params, err := arkscript.DecodeStandardVTXOParams(template) + if err != nil { + return fmt.Errorf("decode standard vtxo params: %w", err) + } + policy, err := arkscript.NewVTXOPolicy( + params.OwnerKey, params.OperatorKey, params.ExitDelay, + ) + if err != nil { + return fmt.Errorf("build vtxo policy: %w", err) + } + info, err := policy.CollabSpendInfo() + if err != nil { + return fmt.Errorf("collab spend info: %w", err) + } + if len(desc.TaprootAssetRoot) > 0 { + root, err := chainhash.NewHash(desc.TaprootAssetRoot) + if err != nil { + return fmt.Errorf("parse asset root: %w", err) + } + leafIdx := policy.ScriptIndex(info.WitnessScript) + if leafIdx < 0 { + return fmt.Errorf("collab leaf index not found") + } + composed, err := arkscript.ComposeWithSiblingRoot( + policy.CompiledPolicy, *root, + ) + if err != nil { + return fmt.Errorf("compose asset root: %w", err) + } + info, err = composed.SpendInfo(leafIdx) + if err != nil { + return fmt.Errorf("composed spend info: %w", err) + } + } + + leaf := &psbt.TaprootTapLeafScript{ + ControlBlock: bytes.Clone(info.ControlBlock), + Script: bytes.Clone(info.WitnessScript), + LeafVersion: txscript.BaseLeafVersion, + } + in := &cp.Inputs[0] + for _, existing := range in.TaprootLeafScript { + if existing != nil && + bytes.Equal(existing.Script, leaf.Script) && + bytes.Equal(existing.ControlBlock, leaf.ControlBlock) { + return nil + } + } + in.TaprootLeafScript = append(in.TaprootLeafScript, leaf) + + return nil +} + +// embeddedAssetOORDaemon is a running waved instance plus its config for +// direct test DB inspection and seeding. +type embeddedAssetOORDaemon struct { + client waverpc.DaemonServiceClient + server *waved.Server + cfg *waved.Config + dataDir string + stop func() +} + +// startEmbeddedAssetDaemonAt runs waved with the real embedded asset engine +// against an externally managed operator mailbox address. +func startEmbeddedAssetDaemonAt(t *testing.T, h *SysTestHarness, dataDir, + mailboxAddr string) *embeddedAssetOORDaemon { + + t.Helper() + + cfg := waved.DefaultConfig() + cfg.DataDir = dataDir + cfg.Network = "regtest" + cfg.DebugLevel = "info" + cfg.Wallet.Type = waved.WalletTypeLwwallet + cfg.Wallet.EsploraURL = h.Harness.EsploraURL + cfg.Server.Host = mailboxAddr + cfg.Server.Insecure = true + cfg.RPC.ListenAddr = "127.0.0.1:0" + cfg.RPC.Gateway.ListenAddr = "127.0.0.1:0" + cfg.RPC.NoTLS = true + cfg.RPC.NoMacaroons = true + + courierHost := h.Harness.TapdUniverseHost() + cfg.Assets = &waved.AssetsConfig{ + Enabled: true, + Courier: waved.AssetCourierConfig{ + Addr: "authmailbox+universerpc://" + courierHost, + Endpoints: []string{ + courierHost + "=" + net.JoinHostPort( + "127.0.0.1", h.Harness.TapdGRPCPort, + ) + "=" + h.Harness.TapdTLSCertPath(), + }, + }, + } + + server, err := waved.NewServer(cfg) + require.NoError(t, err) + + ctx, cancel := context.WithCancel(h.Context()) + errChan := make(chan error, 1) + go func() { + errChan <- server.RunWithContext(ctx) + }() + stopped := false + stop := func() { + if stopped { + return + } + stopped = true + + cancel() + select { + case err := <-errChan: + if err != nil && !errors.Is(err, context.Canceled) { + t.Logf("waved stopped: %v", err) + } + + case <-time.After(30 * time.Second): + t.Errorf("waved did not stop") + } + } + t.Cleanup(stop) + + require.Eventually(t, func() bool { + return server.RPCAddr() != nil + }, time.Minute, 50*time.Millisecond, "waved RPC never listened") + + conn, err := grpc.NewClient( + server.RPCAddr().String(), + grpc.WithTransportCredentials( + insecure.NewCredentials(), + ), + ) + require.NoError(t, err) + t.Cleanup(func() { _ = conn.Close() }) + client := waverpc.NewDaemonServiceClient(conn) + + rpcCtx, rpcCancel := context.WithTimeout(ctx, time.Minute) + defer rpcCancel() + + var info *waverpc.GetInfoResponse + require.Eventually(t, func() bool { + info, err = client.GetInfo(rpcCtx, &waverpc.GetInfoRequest{}) + + return err == nil + }, time.Minute, 100*time.Millisecond, "waved RPC never answered") + + fresh := info.GetWalletState() == waverpc.WalletState_WALLET_STATE_NONE + if fresh { + seed, err := client.GenSeed(rpcCtx, &waverpc.GenSeedRequest{}) + require.NoError(t, err) + _, err = client.InitWallet(rpcCtx, &waverpc.InitWalletRequest{ + Mnemonic: seed.Mnemonic, + WalletPassword: embeddedAssetTestPassword, + }) + require.NoError(t, err) + } else { + _, err = client.UnlockWallet( + rpcCtx, &waverpc.UnlockWalletRequest{ + WalletPassword: embeddedAssetTestPassword, + }, + ) + require.NoError(t, err) + } + + require.NoError(t, server.WaitForWalletServicesReady(rpcCtx)) + waitForDaemonReady(t, client) + + if fresh { + funding, err := client.NewAssetFundingAddress( + rpcCtx, &waverpc.NewAssetFundingAddressRequest{}, + ) + require.NoError(t, err) + h.Harness.Faucet(funding.Address, assetTestWalletFunds) + h.Harness.GenerateAndWait(1) + require.Eventually(t, func() bool { + utxos, err := server.ListWalletUnspent( + rpcCtx, 1, 9_999_999, + ) + + return err == nil && len(utxos) >= 1 + }, time.Minute, time.Second, "daemon wallet never funded") + } + + return &embeddedAssetOORDaemon{ + client: client, + server: server, + cfg: cfg, + dataDir: dataDir, + stop: stop, + } +} + +// fundDaemonWalletExtraUTXOs sends count additional confirmed P2TR UTXOs to +// the daemon wallet so parallel CPFP bumps have independent fee inputs. +func fundDaemonWalletExtraUTXOs(t *testing.T, h *SysTestHarness, + d *embeddedAssetOORDaemon, count int) { + + t.Helper() + + ctx, cancel := context.WithTimeout(t.Context(), time.Minute) + defer cancel() + + for range count { + funding, err := d.client.NewAssetFundingAddress( + ctx, &waverpc.NewAssetFundingAddressRequest{}, + ) + require.NoError(t, err) + h.Harness.Faucet(funding.Address, assetTestWalletFunds) + } + h.Harness.GenerateAndWait(1) + + require.Eventually(t, func() bool { + utxos, err := d.server.ListWalletUnspent(ctx, 1, 9_999_999) + + return err == nil && len(utxos) >= count+1 + }, time.Minute, time.Second, + "extra daemon wallet UTXOs never confirmed") +} + +// lookupOwnedReceiveKey reads a persisted owned receive script's full key +// descriptor (including compressed 33-byte pubkey and key locator) from the +// daemon's SQLite database while the daemon is stopped. +func lookupOwnedReceiveKey(t *testing.T, cfg *waved.Config, + pkScriptHex string) keychain.KeyDescriptor { + + t.Helper() + + pkScript, err := hex.DecodeString(pkScriptHex) + require.NoError(t, err) + + sqliteStore, err := db.NewSqliteStore( + db.DefaultSqliteConfig( + cfg.NetworkDir(), + ), + btclog.Disabled, + ) + require.NoError(t, err) + defer func() { + require.NoError(t, sqliteStore.Close()) + }() + + store := db.NewStore( + sqliteStore.DB, sqliteStore.Queries, sqliteStore.Backend(), + btclog.Disabled, + ) + oorStore := store.NewOORArtifactStore(clock.NewDefaultClock()) + + rec, err := oorStore.LookupOwnedReceiveScript( + t.Context(), pkScript, + ) + require.NoError(t, err) + require.NotNil(t, rec, "receive script %s not found", pkScriptHex) + require.NotNil(t, rec.ClientKey.PubKey) + + return rec.ClientKey +} + +// confirmedOnlyProofVerifier adapts tapassets.ProofChainVerifier to +// customanchor.ConfirmedProofVerifier for confirmed-only batch sources. +type confirmedOnlyProofVerifier struct { + chain tapassets.ProofChainVerifier +} + +func (v *confirmedOnlyProofVerifier) VerifyConfirmedProof(ctx context.Context, + proofFile []byte) (*customanchor.ConfirmedProofVerification, error) { + + if err := v.chain.VerifyProofChain(ctx, proofFile); err != nil { + return nil, err + } + + return customanchor.DeriveConfirmedProofInventory(proofFile) +} + +// memTransitionStore is an in-memory tapassets.Store for building the test +// commitment anchor and asset tree. +type memTransitionStore struct { + mu sync.Mutex + records map[string][]byte +} + +func (m *memTransitionStore) Load(_ context.Context, key string) ([]byte, + error) { + + m.mu.Lock() + defer m.mu.Unlock() + + val, ok := m.records[key] + if !ok { + return nil, tapassets.ErrStoreNotFound + } + + return bytes.Clone(val), nil +} + +func (m *memTransitionStore) Store(_ context.Context, key string, + data []byte) error { + + m.mu.Lock() + defer m.mu.Unlock() + + if m.records == nil { + m.records = make(map[string][]byte) + } + m.records[key] = bytes.Clone(data) + + return nil +} + +// mintV1AssetTestAsset mints an ungrouped v1 fungible asset in the harness +// tapd (required for unconfirmed proof paths) and waits until tapd holds it. +func mintV1AssetTestAsset(t *testing.T, h *SysTestHarness, tapd *tapgrpc.Client, + amount uint64) tapsdk.AssetRef { + + t.Helper() + + ctx, cancel := context.WithTimeout(t.Context(), time.Minute) + defer cancel() + + _, err := tapd.MintAsset(ctx, &tapsdk.MintAssetRequest{ + Asset: &tapsdk.MintAsset{ + AssetVersion: tapsdk.AssetVersionV1, + AssetType: tapsdk.AssetTypeNormal, + Name: "oor-test-v1", + InitialSupply: amount, + AssetMeta: &tapsdk.AssetMeta{ + Data: []byte("oor test v1 asset"), + }, + }, + ShortResponse: true, + }) + require.NoError(t, err) + batch, err := tapd.FinalizeBatch(ctx, &tapsdk.FinalizeBatchRequest{ + ShortResponse: true, + }) + require.NoError(t, err) + h.Harness.WaitMempoolTx(batch.BatchTxid) + h.Harness.Generate(1) + + var ref tapsdk.AssetRef + require.Eventually(t, func() bool { + utxos, err := tapd.ListUtxos(ctx, &tapsdk.ListUtxosRequest{}) + if err != nil { + return false + } + for _, utxo := range utxos { + for _, asset := range utxo.Assets { + if asset != nil && asset.Amount == amount { + ref = asset.AssetRef + } + } + } + + return ref != "" + }, time.Minute, time.Second, "minted v1 asset never appeared") + + return ref +} + +// buildRealAssetOORRoundFixture mints a real confirmed commitment tx anchored +// on regtest bitcoind containing both a 2-leaf asset batch output (400 + 300 +// units for Alice) and a 1-leaf 10,000-sat carrier float batch output, and +// signs every tree transaction with real MuSig2 signatures. +func buildRealAssetOORRoundFixture(t *testing.T, h *SysTestHarness, + issuer *tapgrpc.Client, ref tapsdk.AssetRef, op *assetOORTestOperator, + aliceKey0, aliceKey1 keychain.KeyDescriptor) *assetOORRoundFixture { + + t.Helper() + + ctx, cancel := context.WithTimeout(t.Context(), 2*time.Minute) + defer cancel() + + // Locate the minted 700-unit asset UTXO held by the harness tapd. + utxos, err := issuer.ListUtxos(ctx, &tapsdk.ListUtxosRequest{}) + require.NoError(t, err) + + var ( + assetUtxo *tapsdk.ManagedUtxo + mintedAsset *tapsdk.AssetRecord + ) + for _, u := range utxos { + for _, a := range u.Assets { + if a != nil && a.AssetRef.Equivalent(ref) && + a.Amount == assetOORLeaf0Units+ + assetOORLeaf1Units { + + assetUtxo = u + mintedAsset = a + break + } + } + if assetUtxo != nil { + break + } + } + require.NotNil(t, assetUtxo, "minted asset UTXO not found") + + exportedProof, err := issuer.ExportProof( + ctx, ref, mintedAsset.ScriptKey.PubKey, &assetUtxo.OutPoint, + ) + require.NoError(t, err) + require.NotEmpty(t, exportedProof.RawProofFile) + + assetOutpoint := wire.OutPoint{ + Hash: chainhash.Hash(assetUtxo.OutPoint.Txid), + Index: assetUtxo.OutPoint.Index, + } + assetPrevTx := h.Harness.GetRawTransaction(assetOutpoint.Hash.String()) + require.Greater(t, len(assetPrevTx.TxOut), int(assetOutpoint.Index)) + assetTxOut := assetPrevTx.TxOut[assetOutpoint.Index] + + assetInternalKey, err := btcec.ParsePubKey(assetUtxo.InternalKey[:]) + require.NoError(t, err) + + // Generate ephemeral cosigner keys for the two asset tree leaves so + // the test holds every MuSig2 private key needed to sign the tree. + cosignerPriv0, err := btcec.NewPrivateKey() + require.NoError(t, err) + cosignerPriv1, err := btcec.NewPrivateKey() + require.NoError(t, err) + + sweepLeaf, err := arkscript.UnilateralCSVTimeoutTapLeaf( + op.operatorKey.PubKey(), assetOORBatchSweepDelay, + ) + require.NoError(t, err) + sweepRoot := sweepLeaf.TapHash() + + assetCosigners := []*btcec.PublicKey{ + op.operatorKey.PubKey(), + cosignerPriv0.PubKey(), + cosignerPriv1.PubKey(), + } + floatCosigners := []*btcec.PublicKey{ + op.operatorKey.PubKey(), + op.carrierKey.PubKey(), + } + floatInternalKey, err := tree.ComputeInternalKey(floatCosigners) + require.NoError(t, err) + floatBatchKey, err := tree.ComputeFinalKey(floatCosigners, sweepRoot[:]) + require.NoError(t, err) + floatBatchScript, err := txscript.PayToTaprootScript(floatBatchKey) + require.NoError(t, err) + + // Encode Output 1's single-leaf BIP-371 TapTree so Taproot Assets can + // construct a valid exclusion proof for the non-asset P2TR float batch + // output on the commitment transaction. + var floatTapTreeBuf bytes.Buffer + floatTapTreeBuf.WriteByte(0) + floatTapTreeBuf.WriteByte(byte(sweepLeaf.LeafVersion)) + require.NoError( + t, wire.WriteVarBytes(&floatTapTreeBuf, 0, sweepLeaf.Script), + ) + floatTapTree := floatTapTreeBuf.Bytes() + + issuerWallet := tapsdk.NewWallet(issuer, tapsdk.Network("regtest")) + proofChainVerifier, err := tapassets.NewTapdProofChainVerifier(issuer) + require.NoError(t, err) + confirmedVerifier := &confirmedOnlyProofVerifier{ + chain: proofChainVerifier, + } + + store := &memTransitionStore{} + committer, err := tapassets.NewBatchAnchorCommitter( + tapassets.BatchAnchorCommitterConfig{ + Wallet: issuerWallet, + Store: store, + }, + ) + require.NoError(t, err) + + batchDigest := tapsdk.Hash( + chainhash.HashH( + []byte("asset-oor-systest-batch"), + ), + ) + totalAssetUnits := assetOORLeaf0Units + assetOORLeaf1Units + batchReq := &tapassets.BatchAnchorRequest{ + AssetRef: ref, + Amount: totalAssetUnits, + Sources: []tapassets.BatchAnchorSource{{ + ProofFile: exportedProof.RawProofFile, + Amount: totalAssetUnits, + Verifier: confirmedVerifier, + AnchorOutpoint: assetOutpoint, + AnchorInternalKey: assetInternalKey, + }}, + Cosigners: assetCosigners, + SweepLeaf: sweepLeaf, + Digest: batchDigest, + OutputIndex: 0, + OutputValueSat: 2 * assetOORMinVTXOSat, + } + + // Derive the composed asset batch script before Bitcoin funding. + placeholderTx := wire.NewMsgTx(2) + placeholderTx.AddTxIn(wire.NewTxIn(&assetOutpoint, nil, nil)) + placeholderTx.AddTxOut( + wire.NewTxOut( + 2*assetOORMinVTXOSat, floatBatchScript, + ), + ) + placeholderTx.AddTxOut( + wire.NewTxOut( + assetOORFloatValueSat, floatBatchScript, + ), + ) + preFunding, err := psbt.NewFromUnsignedTx(placeholderTx) + require.NoError(t, err) + preFunding.Inputs[0].WitnessUtxo = assetTxOut + preFunding.Outputs[1].TaprootInternalKey = schnorr.SerializePubKey( + floatInternalKey, + ) + preFunding.Outputs[1].TaprootTapTree = bytes.Clone(floatTapTree) + + derived, err := committer.DeriveScript(ctx, batchReq, preFunding) + require.NoError(t, err) + + // Fund the commitment transaction via OperatorLND so it supplies a + // confirmed fee input and change output with full derivation info. + outputsOnlyTx := wire.NewMsgTx(2) + outputsOnlyTx.AddTxOut( + wire.NewTxOut( + 2*assetOORMinVTXOSat, derived.PkScript, + ), + ) + outputsOnlyTx.AddTxOut( + wire.NewTxOut( + assetOORFloatValueSat, floatBatchScript, + ), + ) + outputsOnlyPkt, err := psbt.NewFromUnsignedTx(outputsOnlyTx) + require.NoError(t, err) + outputsOnlyRaw, err := psbtutil.Serialize(outputsOnlyPkt) + require.NoError(t, err) + + funded, changeIdx, _, err := h.Harness.LND.WalletKit. + FundPsbt(ctx, &walletrpc.FundPsbtRequest{ + Template: &walletrpc.FundPsbtRequest_Psbt{ + Psbt: outputsOnlyRaw, + }, + Fees: &walletrpc.FundPsbtRequest_SatPerVbyte{ + SatPerVbyte: 2, + }, + MinConfs: 1, + ChangeType: walletrpc. + ChangeAddressType_CHANGE_ADDRESS_TYPE_P2TR, + }) + require.NoError(t, err) + require.GreaterOrEqual(t, changeIdx, int32(0)) + + // Assemble the final commitment PSBT with: Input 0: minted asset UTXO + // (signed by tapd via BatchAnchorCommitter) Inputs 1..N: LND funding + // inputs (signed by OperatorLND) Output 0: asset batch output (2,000 + // sats) Output 1: float batch output (10,000 sats) Output 2: LND change + // (increased by assetTxOut.Value) + changeOut := funded.UnsignedTx.TxOut[changeIdx] + changePOut := funded.Outputs[changeIdx] + + commitUnsigned := wire.NewMsgTx(2) + commitUnsigned.AddTxIn(wire.NewTxIn(&assetOutpoint, nil, nil)) + for _, in := range funded.UnsignedTx.TxIn { + commitUnsigned.AddTxIn(in) + } + commitUnsigned.AddTxOut( + wire.NewTxOut( + 2*assetOORMinVTXOSat, derived.PkScript, + ), + ) + commitUnsigned.AddTxOut( + wire.NewTxOut( + assetOORFloatValueSat, floatBatchScript, + ), + ) + commitUnsigned.AddTxOut( + wire.NewTxOut( + changeOut.Value+assetTxOut.Value, changeOut.PkScript, + ), + ) + + commitPkt, err := psbt.NewFromUnsignedTx(commitUnsigned) + require.NoError(t, err) + commitPkt.Inputs[0].WitnessUtxo = assetTxOut + for i := range funded.Inputs { + commitPkt.Inputs[i+1] = funded.Inputs[i] + } + commitPkt.Outputs[1].TaprootInternalKey = schnorr.SerializePubKey( + floatInternalKey, + ) + commitPkt.Outputs[1].TaprootTapTree = bytes.Clone(floatTapTree) + commitPkt.Outputs[2] = changePOut + + batchCommit, err := committer.Commit(ctx, batchReq, commitPkt, derived) + require.NoError(t, err) + + // Restore LND's derivation metadata on the BTC funding inputs + // (stripped during tapd's custom-anchor commit), sign via OperatorLND, + // finalize every input (including input 0 signed by tapd), record the + // transfer via committer.Publish, and broadcast on regtest bitcoind. + committedPkt, err := psbtutil.Parse(batchCommit.AnchorPSBT) + require.NoError(t, err) + for i := range funded.Inputs { + committedPkt.Inputs[i+1].Bip32Derivation = + funded.Inputs[i].Bip32Derivation + committedPkt.Inputs[i+1].TaprootBip32Derivation = + funded.Inputs[i].TaprootBip32Derivation + } + signedCommitPkt, err := h.Harness.LND.WalletKit.SignPsbt( + ctx, committedPkt, + ) + require.NoError(t, err) + for i := range signedCommitPkt.Inputs { + if len(signedCommitPkt.Inputs[i].FinalScriptWitness) != 0 { + continue + } + finalized, err := psbt.MaybeFinalize(signedCommitPkt, i) + require.NoError(t, err) + require.True( + t, finalized, "commitment input %d failed to finalize", + i, + ) + } + commitTx, err := psbt.Extract(signedCommitPkt) + require.NoError(t, err) + + finalCommitPSBT, err := psbtutil.Serialize(signedCommitPkt) + require.NoError(t, err) + require.NoError( + t, committer.Publish( + ctx, batchCommit.PackageBytes, finalCommitPSBT, + ), + ) + + btcClient, err := h.Harness.BitcoinRPCClient() + require.NoError(t, err) + commitTxIDPtr, err := btcClient.SendRawTransaction(commitTx, true) + require.NoError(t, err) + commitTxID := *commitTxIDPtr + + h.Harness.GenerateAndWait(1) + commitHeight := int32(h.Harness.BlockCount()) + + // Build and MuSig2-sign the 2-leaf asset VTXO tree (400 + 300 units). + aliceAnchor0, err := tapassets.StandardVTXOLeafAnchor( + aliceKey0.PubKey, op.operatorKey.PubKey(), assetOORExitDelay, + ) + require.NoError(t, err) + aliceAnchor1, err := tapassets.StandardVTXOLeafAnchor( + aliceKey1.PubKey, op.operatorKey.PubKey(), assetOORExitDelay, + ) + require.NoError(t, err) + + cosigner0Key := string(cosignerPriv0.PubKey().SerializeCompressed()) + cosigner1Key := string(cosignerPriv1.PubKey().SerializeCompressed()) + anchorByCosigner := map[string]tapassets.TreeLeafAnchor{ + cosigner0Key: aliceAnchor0, + cosigner1Key: aliceAnchor1, + } + + assetTree, err := tapassets.BuildAssetTree( + ctx, + tapassets.TreeMaterializerConfig{ + Wallet: issuerWallet, + Store: store, + AssetRef: ref, + SweepLeaf: sweepLeaf, + LeafAnchor: func(node *tree.Node) ( + tapassets.TreeLeafAnchor, error) { + + for _, k := range node.CoSigners { + if a, ok := anchorByCosigner[string( + k.SerializeCompressed(), + )]; ok { + return a, nil + } + } + + return tapassets.TreeLeafAnchor{}, fmt.Errorf( + "unknown leaf " + + "cosigners") + }, + Root: batchCommit.RootSource, + Digest: batchDigest, + }, + tapassets.AssetTreeRequest{ + Leaves: []tree.LeafDescriptor{ + { + PkScript: aliceAnchor0. + UncomposedPkScript, + Amount: btcutil.Amount( + assetOORMinVTXOSat, + ), + CoSignerKey: cosignerPriv0.PubKey(), + AssetAmount: assetOORLeaf0Units, + }, + { + PkScript: aliceAnchor1. + UncomposedPkScript, + Amount: btcutil.Amount( + assetOORMinVTXOSat, + ), + CoSignerKey: cosignerPriv1.PubKey(), + AssetAmount: assetOORLeaf1Units, + }, + }, + OperatorKey: op.operatorKey.PubKey(), + Radix: 2, + BatchOutpoint: wire.OutPoint{ + Hash: commitTxID, + Index: 0, + }, + BatchOutput: commitTx.TxOut[0], + AssetAmount: assetOORLeaf0Units + assetOORLeaf1Units, + }, + ) + require.NoError(t, err) + require.Equal(t, derived.AssetRoot[:], assetTree.BatchAssetRoot) + + opPubKey := string(op.operatorKey.PubKey().SerializeCompressed()) + carrierPubKey := string(op.carrierKey.PubKey().SerializeCompressed()) + signTreeWithLocalKeys(t, assetTree, map[string]*btcec.PrivateKey{ + opPubKey: op.operatorKey, + cosigner0Key: cosignerPriv0, + cosigner1Key: cosignerPriv1, + }) + require.NoError(t, assetTree.VerifySigned()) + + // Build and MuSig2-sign the 1-leaf Bitcoin carrier float tree. + floatDesc, err := tree.NewVTXODescriptor( + btcutil.Amount(assetOORFloatValueSat), op.carrierKey.PubKey(), + op.operatorKey.PubKey(), assetOORExitDelay, + ) + require.NoError(t, err) + + floatTree, err := tree.NewTree( + wire.OutPoint{Hash: commitTxID, Index: 1}, + commitTx.TxOut[1], + []tree.LeafDescriptor{{ + PkScript: floatDesc.PkScript, + Amount: btcutil.Amount(assetOORFloatValueSat), + CoSignerKey: op.carrierKey.PubKey(), + }}, + op.operatorKey.PubKey(), + sweepRoot[:], + 2, + ) + require.NoError(t, err) + + signTreeWithLocalKeys(t, floatTree, map[string]*btcec.PrivateKey{ + opPubKey: op.operatorKey, + carrierPubKey: op.carrierKey, + }) + require.NoError(t, floatTree.VerifySigned()) + + floatLeafTx, err := floatTree.Root.ToSignedTx() + require.NoError(t, err) + floatOutpoint := wire.OutPoint{ + Hash: floatLeafTx.TxHash(), + Index: 0, + } + + // Extract Alice's two individual leaf specs from the signed asset tree. + leaf0 := extractSeededAssetLeaf( + t, assetTree, cosignerPriv0.PubKey(), aliceKey0, + op.operatorKey.PubKey(), assetOORLeaf0Units, + ) + leaf1 := extractSeededAssetLeaf( + t, assetTree, cosignerPriv1.PubKey(), aliceKey1, + op.operatorKey.PubKey(), assetOORLeaf1Units, + ) + + roundID, err := round.NewRoundID() + require.NoError(t, err) + + return &assetOORRoundFixture{ + roundID: roundID, + ref: ref, + commitTx: commitTx, + commitTxID: commitTxID, + commitHeight: commitHeight, + batchExpiry: commitHeight + int32(assetOORBatchSweepDelay), + sweepLeaf: sweepLeaf, + sweepRoot: sweepRoot, + assetTree: assetTree, + floatTree: floatTree, + leaf0: leaf0, + leaf1: leaf1, + floatOutpoint: floatOutpoint, + floatPolicy: floatDesc.PolicyTemplate, + floatPkScript: floatDesc.PkScript, + floatValueSat: assetOORFloatValueSat, + floatTreePath: floatTree, + assetTreePath0: leaf0.TreePath, + assetTreePath1: leaf1.TreePath, + } +} + +// extractSeededAssetLeaf extracts one signed leaf descriptor and sealed asset +// package from the materialized asset tree for Alice's key. +func extractSeededAssetLeaf(t *testing.T, fullTree *tree.Tree, + cosignerPub *btcec.PublicKey, clientKey keychain.KeyDescriptor, + operatorPub *btcec.PublicKey, assetAmount uint64) assetOORLeafSpec { + + t.Helper() + + extracted, err := fullTree.ExtractPathForCoSigners(cosignerPub) + require.NoError(t, err) + require.NotNil(t, extracted) + + leaves := extracted.Root.GetLeafNodes() + require.Len(t, leaves, 1) + leafNode := leaves[0] + + leafTx, err := leafNode.ToSignedTx() + require.NoError(t, err) + + rootBytes := extracted.AssetContext.LeafAssetRoot(leafNode.Input) + require.Len(t, rootBytes, chainhash.HashSize) + var assetRoot chainhash.Hash + copy(assetRoot[:], rootBytes) + + sealedPkg := extracted.AssetContext.SealedPackage(leafNode.Input) + require.NotEmpty(t, sealedPkg) + + policyTemplate, err := arkscript.EncodeStandardVTXOTemplate( + clientKey.PubKey, operatorPub, assetOORExitDelay, + ) + require.NoError(t, err) + + return assetOORLeafSpec{ + Outpoint: wire.OutPoint{ + Hash: leafTx.TxHash(), + Index: 0, + }, + Amount: btcutil.Amount(leafNode.Outputs[0].Value), + PolicyTemplate: policyTemplate, + PkScript: bytes.Clone(leafNode.Outputs[0].PkScript), + ClientKey: clientKey, + AssetRoot: assetRoot, + AssetAmount: assetAmount, + SealedPackage: bytes.Clone(sealedPkg), + TreePath: extracted, + } +} + +// signTreeWithLocalKeys computes real MuSig2 key-spend signatures for every +// node in a VTXO tree using the supplied cosigner private keys. +func signTreeWithLocalKeys(t *testing.T, vtxoTree *tree.Tree, + privByPub map[string]*btcec.PrivateKey) { + + t.Helper() + + prevOutFetcher, err := vtxoTree.Root.PrevOutputFetcher( + vtxoTree.BatchOutput, + ) + require.NoError(t, err) + + for node := range vtxoTree.Root.NodesIter() { + sigHash, err := node.SigHash(prevOutFetcher) + require.NoError(t, err) + + tweak := vtxoTree.SweepTapscriptRoot + if vtxoTree.AssetContext != nil { + tweak = vtxoTree.AssetContext.SigningTweak(node.Input) + } + + // Sort cosigners identically to MuSig2 key aggregation. + signers := append([]*btcec.PublicKey(nil), node.CoSigners...) + sort.Slice(signers, func(i, j int) bool { + return bytes.Compare( + signers[i].SerializeCompressed(), + signers[j].SerializeCompressed(), + ) < 0 + }) + + sessions := make([]*musig2.Session, len(signers)) + pubNonces := make([][musig2.PubNonceSize]byte, len(signers)) + for i, pub := range signers { + priv, ok := privByPub[string(pub.SerializeCompressed())] + require.True(t, ok, "missing private key for cosigner") + + ctx, err := musig2.NewContext( + priv, true, musig2.WithKnownSigners(signers), + musig2.WithTaprootTweakCtx(tweak), + ) + require.NoError(t, err) + + sess, err := ctx.NewSession() + require.NoError(t, err) + sessions[i] = sess + pubNonces[i] = sess.PublicNonce() + } + + for i, sess := range sessions { + for j, nonce := range pubNonces { + if i == j { + continue + } + _, err := sess.RegisterPubNonce(nonce) + require.NoError(t, err) + } + } + + partialSigs := make([]*musig2.PartialSignature, len(sessions)) + for i, sess := range sessions { + psig, err := sess.Sign([32]byte(sigHash)) + require.NoError(t, err) + partialSigs[i] = psig + } + + combiner := sessions[0] + for i := 1; i < len(partialSigs); i++ { + _, err := combiner.CombineSig(partialSigs[i]) + require.NoError(t, err) + } + node.Signature = combiner.FinalSig() + } +} + +// seedRealAssetVTXOs inserts Alice's two real confirmed-round asset VTXOs into +// her SQLite database while her daemon is stopped. +func seedRealAssetVTXOs(t *testing.T, cfg *waved.Config, + op *assetOORTestOperator, f *assetOORRoundFixture) { + + t.Helper() + + networkDir := cfg.NetworkDir() + require.NoError(t, os.MkdirAll(networkDir, 0o700)) + + sqliteStore, err := db.NewSqliteStore( + db.DefaultSqliteConfig(networkDir), btclog.Disabled, + ) + require.NoError(t, err) + defer func() { + require.NoError(t, sqliteStore.Close()) + }() + + store := db.NewStore( + sqliteStore.DB, sqliteStore.Queries, sqliteStore.Backend(), + btclog.Disabled, + ) + roundStore := store.NewRoundStore( + &chaincfg.RegressionNetParams, clock.NewDefaultClock(), + ) + vtxoStore := store.NewVTXOStore(clock.NewDefaultClock()) + + unsignedCommitTx := f.commitTx.Copy() + for _, in := range unsignedCommitTx.TxIn { + in.SignatureScript = nil + in.Witness = nil + } + commitPSBT, err := psbt.NewFromUnsignedTx(unsignedCommitTx) + require.NoError(t, err) + + err = roundStore.CommitState(t.Context(), &round.Round{ + RoundID: f.roundID, + StartHeight: uint32(f.commitHeight), + CommitmentTx: fn.Some(commitPSBT), + VTXOTreePaths: fn.Some(map[int]*tree.Tree{ + 0: f.assetTree, + }), + }, &round.InputSigSentState{ + RoundID: f.roundID, + ClientTrees: make(map[round.SignerKey]*tree.Tree), + }) + require.NoError(t, err) + + err = roundStore.FinalizeRound( + t.Context(), + f.roundID, + f.commitTxID, + round.ConfInfo{ + Height: f.commitHeight, + }, + nil, + ) + require.NoError(t, err) + + for _, leaf := range []assetOORLeafSpec{f.leaf0, f.leaf1} { + tapScript, err := arkscript.VTXOTapScript( + leaf.ClientKey.PubKey, op.operatorKey.PubKey(), + assetOORExitDelay, + ) + require.NoError(t, err) + + rootCopy := leaf.AssetRoot + err = vtxoStore.SaveVTXO(t.Context(), &vtxo.Descriptor{ + Outpoint: leaf.Outpoint, + Amount: leaf.Amount, + PolicyTemplate: leaf.PolicyTemplate, + PkScript: leaf.PkScript, + ClientKey: leaf.ClientKey, + OperatorKey: op.operatorKey.PubKey(), + TapScript: tapScript, + Ancestry: []types.Ancestry{{ + TreePath: leaf.TreePath, + CommitmentTxID: f.commitTxID, + CommitmentHeight: f.commitHeight, + CommitmentSweepDelay: assetOORBatchSweepDelay, + CommitmentSweepKey: op.operatorKey.PubKey(), + TreeDepth: 2, + }}, + RoundID: f.roundID.String(), + CommitmentTxID: f.commitTxID, + BatchExpiry: f.batchExpiry, + RelativeExpiry: assetOORExitDelay, + CreatedHeight: f.commitHeight, + Status: vtxo.VTXOStatusLive, + TaprootAssetRoot: &rootCopy, + TaprootAssetRef: f.ref.String(), + TaprootAssetAmount: leaf.AssetAmount, + TaprootAssetSealedPackage: leaf.SealedPackage, + }) + require.NoError(t, err) + } +} + +// cloneByteSlices returns a deep copy of a slice of byte slices. +func cloneByteSlices(in [][]byte) [][]byte { + if len(in) == 0 { + return nil + } + out := make([][]byte, len(in)) + for i := range in { + out[i] = bytes.Clone(in[i]) + } + + return out +} diff --git a/systest/send_vtxo_test.go b/systest/send_vtxo_test.go index 846e1895f..45d3cedd2 100644 --- a/systest/send_vtxo_test.go +++ b/systest/send_vtxo_test.go @@ -74,14 +74,14 @@ type fakeMailboxServer struct { operatorMailbox string operatorInfoResp *arkrpc.GetInfoResponse - mu sync.Mutex - mailboxes map[string][]*mailboxpb.Envelope - nextEventSeq map[string]uint64 - joinRoundReqs []*roundpb.JoinRoundRequest - joinRoundEnvs []*mailboxpb.Envelope - oorSubmitReqs []*oorpb.SubmitPackageRequest - oorSubmitEnvs []*mailboxpb.Envelope - inboxSignalChan chan struct{} + mu sync.Mutex + mailboxes map[string][]*mailboxpb.Envelope + nextEventSeq map[string]uint64 + joinRoundReqs []*roundpb.JoinRoundRequest + joinRoundEnvs []*mailboxpb.Envelope + oorSubmitReqs []*oorpb.SubmitPackageRequest + oorSubmitEnvs []*mailboxpb.Envelope + inboxSignal chan struct{} // failRoundOnJoin, when set, makes the operator push this // ClientRoundFailedResp back to the client immediately on every @@ -92,6 +92,11 @@ type fakeMailboxServer struct { // feeQuote, when set, answers EstimateFee. Unset leaves the RPC // unimplemented, so daemons fall back to the operator's minimum fee. feeQuote *arkrpc.EstimateFeeResponse + + // envelopeHandler, when set, intercepts inbound envelopes addressed + // to the operator or indexer before the default switch. Returning + // handled=true suppresses the default handler. + envelopeHandler func(context.Context, *mailboxpb.Envelope) (bool, error) } // newFakeMailboxServer constructs a fake mailbox edge with the given operator @@ -107,7 +112,7 @@ func newFakeMailboxServer(t *testing.T, operatorMailbox string, operatorInfoResp: operatorInfoResp, mailboxes: make(map[string][]*mailboxpb.Envelope), nextEventSeq: make(map[string]uint64), - inboxSignalChan: make(chan struct{}, 1), + inboxSignal: make(chan struct{}), } } @@ -168,7 +173,9 @@ func (s *fakeMailboxServer) Send(ctx context.Context, expectedCompound := serverconn.CompoundMailboxID( s.operatorMailbox, env.Sender, ) - if env.Recipient == expectedCompound { + if env.Recipient == expectedCompound || + env.Recipient == serverconn.IndexerMailboxID { + if err := s.handleOperatorEnvelope(ctx, env); err != nil { return nil, err } @@ -194,7 +201,7 @@ func (s *fakeMailboxServer) Pull(ctx context.Context, waitTimeout := time.Duration(req.WaitTimeoutMs) * time.Millisecond for { - envelopes, nextCursor := s.pullBatch( + envelopes, nextCursor, sig := s.pullBatch( req.MailboxId, req.Cursor, req.MaxEnvelopes, ) if len(envelopes) > 0 { @@ -223,7 +230,7 @@ func (s *fakeMailboxServer) Pull(ctx context.Context, return nil, ctx.Err() - case <-s.inboxSignalChan: + case <-sig: if !timer.Stop() { <-timer.C } @@ -277,6 +284,19 @@ func (s *fakeMailboxServer) handleOperatorEnvelope(ctx context.Context, return nil } + s.mu.Lock() + handler := s.envelopeHandler + s.mu.Unlock() + if handler != nil { + handled, err := handler(ctx, env) + if err != nil { + return err + } + if handled { + return nil + } + } + switch { case env.Rpc.Kind == mailboxpb.RpcMeta_KIND_REQUEST && env.Rpc.Service == "arkrpc.ArkService" && @@ -448,16 +468,15 @@ func (s *fakeMailboxServer) enqueueEnvelope(env *mailboxpb.Envelope) { s.mailboxes[env.Recipient] = append(s.mailboxes[env.Recipient], env) - select { - case s.inboxSignalChan <- struct{}{}: - default: - } + close(s.inboxSignal) + s.inboxSignal = make(chan struct{}) } // pullBatch returns the available envelopes for a mailbox starting at the -// requested cursor along with the exclusive next cursor. +// requested cursor along with the exclusive next cursor and a broadcast +// channel closed when any new envelope arrives. func (s *fakeMailboxServer) pullBatch(mailboxID string, cursor uint64, - maxEnvelopes uint32) ([]*mailboxpb.Envelope, uint64) { + maxEnvelopes uint32) ([]*mailboxpb.Envelope, uint64, <-chan struct{}) { s.mu.Lock() defer s.mu.Unlock() @@ -490,7 +509,7 @@ func (s *fakeMailboxServer) pullBatch(mailboxID string, cursor uint64, } } - return batch, nextCursor + return batch, nextCursor, s.inboxSignal } // oorSubmitPackages returns a cloned snapshot of recorded OOR submit requests. From 527cf1f4b762779566374e287b3116333ec79ff7 Mon Sep 17 00:00:00 2001 From: Dario Anongba Varela Date: Fri, 27 Nov 2026 19:10:07 +0100 Subject: [PATCH 11/15] vtxo: guard terminal VTXOs and asset reservation redrive Add VTXOStatus.IsTerminal and guard handleVTXOsMaterialized against replayed notifications for already-terminal stored VTXOs. Set AllowAssetTransition on the startup reservation-sweep redrive so resumed asset OOR reservations are not rejected, and match asset references case-insensitively during candidate selection. --- vtxo/asset_safety_test.go | 48 +++++++++++++++++++++++++++++++++++++++ vtxo/asset_selection.go | 3 ++- vtxo/interfaces.go | 12 ++++++++++ vtxo/manager.go | 30 +++++++++++++++++++++++- 4 files changed, 91 insertions(+), 2 deletions(-) diff --git a/vtxo/asset_safety_test.go b/vtxo/asset_safety_test.go index f318ce714..0a43e2387 100644 --- a/vtxo/asset_safety_test.go +++ b/vtxo/asset_safety_test.go @@ -74,6 +74,54 @@ func TestAssetVTXOSkipsAutomaticRefresh(t *testing.T) { require.ErrorIs(t, err, ErrAssetVTXORequiresTransition) } +// TestAssetRefSelectionCaseInsensitive verifies that asset selection matches +// asset references regardless of hex casing. +func TestAssetRefSelectionCaseInsensitive(t *testing.T) { + t.Parallel() + + root := chainhash.Hash{2} + descs := []*Descriptor{{ + Amount: 1_000, + Status: VTXOStatusLive, + TaprootAssetRoot: &root, + TaprootAssetRef: "AABBCC", + TaprootAssetAmount: 500, + TaprootAssetSealedPackage: []byte("sealed-pkg"), + }} + + selected, total, err := SelectAssetVTXOCandidates( + descs, "aabbcc", 250, 4, + ) + require.NoError(t, err) + require.Len(t, selected, 1) + require.EqualValues(t, 500, total) +} + +// TestMaterializedNotificationSkipsTerminalStoredVTXO verifies that +// handleVTXOsMaterialized refuses to resurrect a VTXO whose stored row is +// already terminal (e.g. VTXOStatusSpent). +func TestMaterializedNotificationSkipsTerminalStoredVTXO(t *testing.T) { + t.Parallel() + + desc := makeDescriptor(t, 1_000, 0) + spentDesc := *desc + spentDesc.Status = VTXOStatusSpent + + mgr, store := newTestManager(t, nil) + store.On("GetVTXO", t.Context(), desc.Outpoint).Return( + &spentDesc, nil, + ).Once() + + res := mgr.handleVTXOsMaterialized( + t.Context(), &VTXOsMaterializedNotification{ + VTXOs: []*Descriptor{desc}, + }, + ) + require.NoError(t, res.Err()) + require.Empty(t, mgr.actors) + store.AssertExpectations(t) +} + // TestAssetVTXOCarrierBalance reports asset carriers in total holdings while // excluding them from the Bitcoin spendable balance. func TestAssetVTXOCarrierBalance(t *testing.T) { diff --git a/vtxo/asset_selection.go b/vtxo/asset_selection.go index 239bfbc11..c78919792 100644 --- a/vtxo/asset_selection.go +++ b/vtxo/asset_selection.go @@ -7,6 +7,7 @@ import ( "log/slog" "math" "slices" + "strings" "github.com/btcsuite/btcd/wire/v2" fn "github.com/lightningnetwork/lnd/fn/v2" @@ -95,7 +96,7 @@ func isSpendableAssetDescriptor(desc *Descriptor, assetRef string) bool { } return desc.TaprootAssetRoot != nil && - desc.TaprootAssetRef == assetRef && + strings.EqualFold(desc.TaprootAssetRef, assetRef) && desc.TaprootAssetAmount > 0 && len(desc.TaprootAssetSealedPackage) > 0 } diff --git a/vtxo/interfaces.go b/vtxo/interfaces.go index ad42085fc..481d8c481 100644 --- a/vtxo/interfaces.go +++ b/vtxo/interfaces.go @@ -350,6 +350,18 @@ func (s VTXOStatus) String() string { } } +// IsTerminal reports whether the VTXO status is a terminal lifecycle state +// that must never be resurrected as live. +func (s VTXOStatus) IsTerminal() bool { + switch s { + case VTXOStatusForfeited, VTXOStatusSpent, VTXOStatusFailed: + return true + + default: + return false + } +} + // Ancestry describes one rooted commitment-tree fragment that contributes // ancestry to a VTXO. The canonical type lives in lib/types so that both // round.ClientVTXO and vtxo.Descriptor can carry the same multi-fragment diff --git a/vtxo/manager.go b/vtxo/manager.go index 532c7e961..33e4b2751 100644 --- a/vtxo/manager.go +++ b/vtxo/manager.go @@ -1066,6 +1066,9 @@ func (m *Manager) handleVTXOsMaterialized(ctx context.Context, if descriptor == nil { continue } + if descriptor.Status.IsTerminal() { + continue + } outpoint := descriptor.Outpoint if _, exists := m.actors[outpoint]; exists { @@ -1076,6 +1079,30 @@ func (m *Manager) handleVTXOsMaterialized(ctx context.Context, continue } + // Re-check the authoritative store before spawning a live + // actor so a replayed materialization notification can never + // resurrect an already-spent or otherwise terminal VTXO. + if m.cfg.Store != nil { + stored, getErr := m.cfg.Store.GetVTXO(ctx, outpoint) + if getErr == nil && stored != nil && + stored.Status.IsTerminal() { + + m.logger(ctx).DebugS( + ctx, "Skipping terminal VTXO "+ + "materialization notification", + slog.String( + "outpoint", outpoint.String(), + ), + slog.String( + "status", + stored.Status.String(), + ), + ) + + continue + } + } + ref, err := m.spawnVTXOActor(ctx, descriptor) if err != nil { m.logger(ctx).ErrorS(ctx, "Failed to spawn VTXO actor", @@ -2763,7 +2790,8 @@ func (m *Manager) sweepOrphanedReservations(ctx context.Context) { // refuse". m.markReservedUnknown(op) - if err := ref.Tell(ctx, &SpendReserveEvent{}); err != nil { + reserveEvt := &SpendReserveEvent{AllowAssetTransition: true} + if err := ref.Tell(ctx, reserveEvt); err != nil { m.logger(ctx).WarnS( ctx, "Reservation sweep: re-drive reserve failed", From d227d93b1e2fe5db0c0261d686a9582e7ec607f6 Mon Sep 17 00:00:00 2001 From: Dario Anongba Varela Date: Fri, 27 Nov 2026 19:10:07 +0100 Subject: [PATCH 12/15] oor: key incoming hints per script and harden asset replay Key multi-output incoming receive hints, parked self-hints, and ReceiveCompleted tracking on IncomingHintKey{ScriptHash, EventID} so distinct fresh scripts numbered 1 by the operator do not collide. Record MaterializedPlainScripts so plain Bitcoin sessions stay dormant without reopening, preserve prior ReceiveCompleted if a follow-up pass fails, reject stale phase-1 resolutions, reconstruct active hints on restore, and guard persistIncomingDescriptor against terminal rows. Isolate per-output asset verification failures and disabled-asset sessions so sibling plain Bitcoin outputs still materialize, normalize incoming TaprootAssetRef casing, and add version-2 OutgoingAssetReplay proofs to isolate asset and Bitcoin idempotency namespaces. --- oor/AGENTS.md | 37 +-- oor/CLAUDE.md | 37 +-- oor/actor_durable_message.go | 88 +++++-- oor/asset_oor_receive_test.go | 434 +++++++++++++++++++++++++++---- oor/events.go | 22 +- oor/incoming_adapter.go | 43 +-- oor/incoming_vtxo.go | 5 +- oor/local_persistence_handler.go | 241 ++++++++++++----- oor/outgoing_replay.go | 164 +++++++++++- oor/outgoing_snapshot_test.go | 40 +++ oor/receive_snapshot.go | 295 ++++++++++++++++----- oor/receive_states.go | 208 ++++++++++++--- oor/receive_transitions.go | 155 ++++++----- oor/registry.go | 86 ++++-- oor/session_actor_handlers.go | 56 ++-- 15 files changed, 1497 insertions(+), 414 deletions(-) diff --git a/oor/AGENTS.md b/oor/AGENTS.md index 22b816fe1..84b79df13 100644 --- a/oor/AGENTS.md +++ b/oor/AGENTS.md @@ -112,28 +112,33 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/oor. 0 { + records = append( + records, tlv.MakePrimitiveRecord( + eventPayloadRecipientEventIDType, + &recipientEventID, + ), + ) + } + if len(recipientPkScript) > 0 { + records = append( + records, tlv.MakePrimitiveRecord( + eventPayloadRecipientPkScriptType, + &recipientPkScript, + ), + ) + } return tlvutil.EncodeRecordsToBytes(records...) } @@ -2699,19 +2721,21 @@ func decodeEventPayloadWithLimits(raw []byte, limits ReceiveLimits) (Event, error) { var ( - eventKind uint64 - submitSession []byte - arkPSBT []byte - checkpointPSBT []byte - reason []byte - outpointPayload []byte - metadataPayload []byte - ancestorPayload []byte - outboxType []byte - retryable uint8 - retryAfterNanos uint64 - recipientPayload []byte - assetTransferRaw []byte + eventKind uint64 + submitSession []byte + arkPSBT []byte + checkpointPSBT []byte + reason []byte + outpointPayload []byte + metadataPayload []byte + ancestorPayload []byte + outboxType []byte + retryable uint8 + retryAfterNanos uint64 + recipientPayload []byte + assetTransferRaw []byte + recipientEventID uint64 + recipientPkScript []byte ) records := []tlv.Record{ @@ -2751,6 +2775,12 @@ func decodeEventPayloadWithLimits(raw []byte, tlv.MakePrimitiveRecord( eventPayloadTaprootAssetTransferType, &assetTransferRaw, ), + tlv.MakePrimitiveRecord( + eventPayloadRecipientEventIDType, &recipientEventID, + ), + tlv.MakePrimitiveRecord( + eventPayloadRecipientPkScriptType, &recipientPkScript, + ), } if _, err := decodeBoundedRecords( @@ -2875,6 +2905,10 @@ func decodeEventPayloadWithLimits(raw []byte, AncestorPackages: ancestors, Recipients: recipients, TaprootAssetTransfer: assetTransfer, + RecipientEventID: recipientEventID, + RecipientPkScript: append( + []byte(nil), recipientPkScript..., + ), }, nil case eventKindIncomingHandled: diff --git a/oor/asset_oor_receive_test.go b/oor/asset_oor_receive_test.go index e440e214d..d409e1698 100644 --- a/oor/asset_oor_receive_test.go +++ b/oor/asset_oor_receive_test.go @@ -3,11 +3,13 @@ package oor import ( "bytes" "context" + "crypto/sha256" "errors" "fmt" "testing" "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcutil/v2" "github.com/btcsuite/btcd/chainhash/v2" "github.com/btcsuite/btcd/psbt/v2" "github.com/btcsuite/btcd/txscript/v2" @@ -28,9 +30,9 @@ import ( // checkpoint PSBT paying an asset-bearing composed output to recipientKey. func buildTestIncomingAssetGraph(t *testing.T, recipientKey *btcec.PublicKey, operatorPriv *btcec.PrivateKey, exitDelay uint32, - assetRoot chainhash.Hash, assetRef string, assetAmount uint64) ( - *psbt.Packet, []*psbt.Packet, []byte, []byte, []byte, - *oortx.TaprootAssetTransfer) { + assetRoot chainhash.Hash, assetRef string, assetAmount uint64, + extraOutputs ...oortx.RecipientOutput) (*psbt.Packet, []*psbt.Packet, + []byte, []byte, []byte, *oortx.TaprootAssetTransfer) { t.Helper() @@ -43,12 +45,17 @@ func buildTestIncomingAssetGraph(t *testing.T, recipientKey *btcec.PublicKey, CSVDelay: exitDelay, } + totalVal := btcutil.Amount(1_000) + for i := range extraOutputs { + totalVal += extraOutputs[i].Value + } + inVTXO := newTestComposedAssetInput( t, senderPriv, operatorKey, wire.OutPoint{ Hash: chainhash.Hash{0x11}, Index: 0, }, - 1_000, + totalVal, chainhash.Hash{0x22}, assetRef, assetAmount, @@ -97,8 +104,7 @@ func buildTestIncomingAssetGraph(t *testing.T, recipientKey *btcec.PublicKey, ) require.NoError(t, err) - arkPSBT, err := oortx.BuildArkPSBT( - []oortx.CheckpointOutput{cpOut}, + outputs := append( []oortx.RecipientOutput{{ PkScript: composedPkScript, Value: 1_000, @@ -109,6 +115,11 @@ func buildTestIncomingAssetGraph(t *testing.T, recipientKey *btcec.PublicKey, Amount: assetAmount, }, }}, + extraOutputs..., + ) + + arkPSBT, err := oortx.BuildArkPSBT( + []oortx.CheckpointOutput{cpOut}, outputs, ) require.NoError(t, err) @@ -604,11 +615,13 @@ func TestLocalPersistenceHandlerIncomingAssetMaterialization(t *testing.T) { } // TestMultiEventIncomingReceivePass verifies that an incoming OOR session -// records completed recipient event IDs across snapshots, allows a distinct -// recipient event for the same session (e.g. asset change plus Bitcoin carrier -// return) to run a fresh receive pass after ReceiveCompleted, postpones a -// distinct event arriving while another pass is in flight, absorbs duplicates, -// and preserves multiple parked self-hints per session in FIFO order. +// keys completed hints by (pkScript, eventID) across snapshots, allows a +// distinct script with the same per-script event ID (e.g. both fresh scripts +// numbered 1) to run a fresh receive pass after ReceiveCompleted, does not +// reopen completed sessions for already-materialized plain Bitcoin scripts, +// preserves ReceiveCompleted on follow-up failure, rejects stale phase-1 +// events, postpones concurrent distinct hints, and preserves parked hints in +// FIFO order. func TestMultiEventIncomingReceivePass(t *testing.T) { t.Parallel() @@ -616,40 +629,65 @@ func TestMultiEventIncomingReceivePass(t *testing.T) { require.NoError(t, err) recipPriv, err := btcec.NewPrivateKey() require.NoError(t, err) + secondScript := bytes.Repeat([]byte{0x51}, 34) + plainScript := bytes.Repeat([]byte{0x52}, 34) + plainScriptHash := sha256.Sum256(plainScript) arkPSBT, cps, _, routingScript, _, xfer := buildTestIncomingAssetGraph( t, recipPriv.PubKey(), operatorPriv, 144, chainhash.Hash{0xaa}, "asset-usd", 150, ) sessionID := SessionID(arkPSBT.UnsignedTx.TxHash()) + hintA := NewIncomingHintKey(routingScript, 1) + hintB := NewIncomingHintKey(secondScript, 1) + hintPlain := NewIncomingHintKey(plainScript, 1) - // Walk ReceiveResolving(event 3) -> ReceiveNotified -> - // ReceiveAwaitingAck -> ReceiveCompleted{CompletedEventIDs: [3]}. + // Walk ReceiveResolving(scriptA, event 1) -> ReceiveNotified -> + // ReceiveAwaitingAck -> ReceiveCompleted. sess, err := newReceiveSessionWithState( t.Context(), sessionID, &ReceiveResolving{ SessionID: sessionID, RecipientPkScript: routingScript, - RecipientEventID: 3, + RecipientEventID: 1, }, EnvConfig{}, ) require.NoError(t, err) + // A stale phase-1 resolution for a different (script, event) must be + // ignored without advancing ReceiveResolving. + staleRes := sess.FSM.AskEvent(t.Context(), &IncomingTransferEvent{ + SessionID: sessionID, + RecipientPkScript: secondScript, + RecipientEventID: 1, + ArkPSBT: arkPSBT, + FinalCheckpointPSBTs: cps, + TaprootAssetTransfer: xfer, + }).Await(t.Context()) + require.NoError(t, staleRes.Err()) + st, err := sess.FSM.CurrentState() + require.NoError(t, err) + _, stillResolving := st.(*ReceiveResolving) + require.True(t, stillResolving) + res := sess.FSM.AskEvent(t.Context(), &IncomingTransferEvent{ SessionID: sessionID, + RecipientPkScript: routingScript, + RecipientEventID: 1, ArkPSBT: arkPSBT, FinalCheckpointPSBTs: cps, TaprootAssetTransfer: xfer, }).Await(t.Context()) require.NoError(t, res.Err()) - st, err := sess.FSM.CurrentState() + st, err = sess.FSM.CurrentState() require.NoError(t, err) notified, ok := st.(*ReceiveNotified) require.True(t, ok) - require.EqualValues(t, 3, notified.RecipientEventID) + require.Equal(t, hintA, notified.ActiveHint) - res = sess.FSM.AskEvent(t.Context(), &IncomingHandledEvent{}). - Await(t.Context()) + res = sess.FSM.AskEvent(t.Context(), &IncomingHandledEvent{ + MaterializedPlainScripts: [][sha256.Size]byte{plainScriptHash}, + }).Await(t.Context()) require.NoError(t, res.Err()) res = sess.FSM.AskEvent(t.Context(), &IncomingAckSentEvent{}). @@ -660,11 +698,13 @@ func TestMultiEventIncomingReceivePass(t *testing.T) { require.NoError(t, err) completed, ok := st.(*ReceiveCompleted) require.True(t, ok) - require.Equal(t, []uint64{3}, completed.CompletedEventIDs) - require.True(t, completed.HasEventID(3)) - require.False(t, completed.HasEventID(2)) + require.Equal(t, []IncomingHintKey{hintA}, completed.CompletedHints) + require.True(t, completed.HasHint(hintA)) + require.False(t, completed.HasHint(hintB)) + require.True(t, completed.HasPlainScript(plainScriptHash)) - // Snapshot round-trip preserves CompletedEventIDs on ReceiveCompleted. + // Snapshot round-trip preserves CompletedHints and + // MaterializedPlainScripts on ReceiveCompleted. snap, err := NewIncomingSnapshot(sessionID, completed) require.NoError(t, err) raw, err := encodeIncomingSnapshot(snap) @@ -677,11 +717,24 @@ func TestMultiEventIncomingReceivePass(t *testing.T) { require.NoError(t, err) restoredCompleted, ok := restoredState.(*ReceiveCompleted) require.True(t, ok) - require.Equal(t, []uint64{3}, restoredCompleted.CompletedEventIDs) + require.Equal( + t, []IncomingHintKey{hintA}, restoredCompleted.CompletedHints, + ) + require.Equal( + t, [][sha256.Size]byte{plainScriptHash}, + restoredCompleted.MaterializedPlainScripts, + ) - // On the session behavior: repeating event 3 is a no-op; a distinct - // event 2 starts a fresh ReceiveResolving pass carrying [3]; and while - // event 2 is active, a distinct event 4 postpones instead of dropping. + // On the session behavior: + // - repeating hintA is a no-op; + // - a hint for an already-materialized plain Bitcoin script stays + // dormant (no-op) without reopening; + // - a distinct script with the same per-script event ID (hintB, + // event_id=1) starts a fresh ReceiveResolving pass carrying hintA; + // - while hintB is active, a third hint postpones instead of dropping; + // - if the follow-up pass fails, the session returns to + // ReceiveCompleted rather than overwriting prior completion with + // Failed. b := &sessionBehavior{ sessionID: sessionID, log: btclog.Disabled, @@ -693,7 +746,7 @@ func TestMultiEventIncomingReceivePass(t *testing.T) { t.Context(), &ResolveIncomingTransferRequest{ SessionID: sessionID, RecipientPkScript: routingScript, - RecipientEventID: 3, + RecipientEventID: 1, }, ) require.NoError(t, dupRes.Err()) @@ -702,11 +755,24 @@ func TestMultiEventIncomingReceivePass(t *testing.T) { _, stillCompleted := st.(*ReceiveCompleted) require.True(t, stillCompleted) + plainRes := b.handleResolveIncomingTransfer( + t.Context(), &ResolveIncomingTransferRequest{ + SessionID: sessionID, + RecipientPkScript: plainScript, + RecipientEventID: hintPlain.EventID, + }, + ) + require.NoError(t, plainRes.Err()) + st, err = b.fsm.CurrentState() + require.NoError(t, err) + _, stillCompleted = st.(*ReceiveCompleted) + require.True(t, stillCompleted) + nextRes := b.handleResolveIncomingTransfer( t.Context(), &ResolveIncomingTransferRequest{ SessionID: sessionID, - RecipientPkScript: routingScript, - RecipientEventID: 2, + RecipientPkScript: secondScript, + RecipientEventID: 1, }, ) require.NoError(t, nextRes.Err()) @@ -714,50 +780,320 @@ func TestMultiEventIncomingReceivePass(t *testing.T) { require.NoError(t, err) resolving, ok := st.(*ReceiveResolving) require.True(t, ok) - require.EqualValues(t, 2, resolving.RecipientEventID) - require.Equal(t, []uint64{3}, resolving.CompletedEventIDs) + require.Equal(t, hintB, resolving.HintKey()) + require.Equal(t, []IncomingHintKey{hintA}, resolving.CompletedHints) busyRes := b.handleResolveIncomingTransfer( t.Context(), &ResolveIncomingTransferRequest{ SessionID: sessionID, - RecipientPkScript: routingScript, - RecipientEventID: 4, + RecipientPkScript: secondScript, + RecipientEventID: 2, }, ) require.ErrorIs(t, busyRes.Err(), actor.ErrPostponed) - // Registry parkedSelfHints preserves multiple distinct recipient - // events for the same session in FIFO order and deduplicates repeats. + // A follow-up pass failure must preserve ReceiveCompleted with hintA. + failRes := b.fsm.AskEvent(t.Context(), &FailEvent{ + Reason: "follow-up verification failed", + }).Await(t.Context()) + require.NoError(t, failRes.Err()) + st, err = b.fsm.CurrentState() + require.NoError(t, err) + preserved, ok := st.(*ReceiveCompleted) + require.True(t, ok) + require.Equal(t, []IncomingHintKey{hintA}, preserved.CompletedHints) + + // Registry parkedSelfHints keys by (pkScript, eventID) so two fresh + // scripts both with event_id=1 do not collide, preserves FIFO order, + // and deduplicates exact repeats. reg := &oorRegistryBehavior{} reg.parkSelfHint(&ResolveIncomingTransferRequest{ SessionID: sessionID, RecipientPkScript: routingScript, - RecipientEventID: 2, + RecipientEventID: 1, }) reg.parkSelfHint(&ResolveIncomingTransferRequest{ SessionID: sessionID, - RecipientPkScript: routingScript, - RecipientEventID: 3, + RecipientPkScript: secondScript, + RecipientEventID: 1, }) reg.parkSelfHint(&ResolveIncomingTransferRequest{ SessionID: sessionID, RecipientPkScript: routingScript, - RecipientEventID: 2, + RecipientEventID: 1, }) require.Len(t, reg.parkedSelfHints[sessionID], 2) - require.EqualValues( - t, 2, reg.parkedSelfHints[sessionID][0]. - RecipientEventID, + require.Equal( + t, routingScript, + reg.parkedSelfHints[sessionID][0].RecipientPkScript, ) - require.EqualValues( - t, 3, reg.parkedSelfHints[sessionID][1]. - RecipientEventID, + require.Equal( + t, secondScript, + reg.parkedSelfHints[sessionID][1].RecipientPkScript, ) - reg.unparkSelfHint(sessionID, 2) + reg.unparkSelfHint(sessionID, hintA) require.Len(t, reg.parkedSelfHints[sessionID], 1) - require.EqualValues( - t, 3, reg.parkedSelfHints[sessionID][0]. - RecipientEventID, + require.Equal( + t, secondScript, + reg.parkedSelfHints[sessionID][0].RecipientPkScript, + ) +} + +// TestIncomingPersistSkipsTerminalAndCanonicalizesAssetRef verifies that +// persistIncomingDescriptor never resurrects an already-spent VTXO (even if +// SaveVTXO uses an upsert that returns nil), that mixed asset+Bitcoin sessions +// still materialize sibling Bitcoin outputs when assets are disabled or an +// asset output fails verification, and that incoming asset refs are +// canonicalized to lowercase. +func TestIncomingPersistSkipsTerminalAndCanonicalizesAssetRef(t *testing.T) { + t.Parallel() + + operatorPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + recipPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + btcPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + + const exitDelay = uint32(144) + + // Build a spent VTXO in the store and verify persistIncomingDescriptor + // refuses to overwrite it or notify the manager. + spentOP := wire.OutPoint{Hash: chainhash.Hash{0x44}, Index: 0} + spentStore := newTestVTXOStore() + require.NoError( + t, + spentStore.SaveVTXO( + t.Context(), &vtxo.Descriptor{ + Outpoint: spentOP, + Amount: 1_000, + Status: vtxo.VTXOStatusSpent, + }, + ), + ) + spentHandler := &LocalPersistenceOutboxHandler{ + Store: spentStore, + } + + persisted, notify, err := spentHandler.persistIncomingDescriptor( + t.Context(), &vtxo.Descriptor{ + Outpoint: spentOP, + Amount: 1_000, + Status: vtxo.VTXOStatusLive, + }, + ) + require.NoError(t, err) + require.False(t, notify) + require.Equal(t, vtxo.VTXOStatusSpent, persisted.Status) + + gotSpent, err := spentStore.GetVTXO(t.Context(), spentOP) + require.NoError(t, err) + require.Equal(t, vtxo.VTXOStatusSpent, gotSpent.Status) + + // Build an asset-bearing Ark PSBT and append a sibling plain Bitcoin + // output owned by btcPriv. With VerifyIncomingAssetPackage == nil + // (assets disabled), the plain Bitcoin output must still materialize + // while the asset output is skipped. + btcPolicyBytes, err := arkscript.EncodeStandardVTXOTemplate( + btcPriv.PubKey(), operatorPriv.PubKey(), exitDelay, + ) + require.NoError(t, err) + btcTemplate, err := arkscript.DecodePolicyTemplate(btcPolicyBytes) + require.NoError(t, err) + btcCompiled, err := btcTemplate.Compile() + require.NoError(t, err) + btcPkScript, err := txscript.PayToTaprootScript( + btcCompiled.OutputKey(), + ) + require.NoError(t, err) + + assetRoot := chainhash.Hash{0xbb} + const assetRef = "asset-usd" + const assetAmount = uint64(200) + arkPSBT, cps, recipPolicy, _, composedScript, xfer := + buildTestIncomingAssetGraph( + t, recipPriv.PubKey(), operatorPriv, exitDelay, + assetRoot, assetRef, assetAmount, + oortx.RecipientOutput{ + PkScript: btcPkScript, + Value: 1_000, + }, + ) + + sessionID := SessionID(arkPSBT.UnsignedTx.TxHash()) + + // BuildArkPSBT canonically sorts recipient outputs by (Value, + // PkScript), so resolve each output's actual index from the built tx. + assetIdx := uint32(len(arkPSBT.UnsignedTx.TxOut)) + btcIdx := uint32(len(arkPSBT.UnsignedTx.TxOut)) + for i, txOut := range arkPSBT.UnsignedTx.TxOut { + switch { + case bytes.Equal(txOut.PkScript, composedScript): + assetIdx = uint32(i) + + case bytes.Equal(txOut.PkScript, btcPkScript): + btcIdx = uint32(i) + } + } + require.Less(t, int(assetIdx), len(arkPSBT.UnsignedTx.TxOut)) + require.Less(t, int(btcIdx), len(arkPSBT.UnsignedTx.TxOut)) + + recipients := []ArkRecipientOutput{ + { + OutputIndex: assetIdx, + Value: 1_000, + PkScript: composedScript, + VTXOPolicyTemplate: recipPolicy, + Asset: &oortx.RecipientAsset{ + Root: assetRoot, + Ref: assetRef, + Amount: assetAmount, + }, + }, + { + OutputIndex: btcIdx, + Value: 1_000, + PkScript: btcPkScript, + }, + } + + commitmentID := chainhash.Hash{0x66} + matches := []IncomingMetadataMatch{ + { + OutputIndex: assetIdx, + Metadata: IncomingVTXOMetadata{ + RoundID: "round-1", + CommitmentTxID: commitmentID, + ChainDepth: 1, + OperatorKey: operatorPriv.PubKey(), + Ancestry: validTestIncomingAncestry( + commitmentID, + ), + }, + }, + { + OutputIndex: btcIdx, + Metadata: IncomingVTXOMetadata{ + RoundID: "round-1", + CommitmentTxID: commitmentID, + ChainDepth: 1, + OperatorKey: operatorPriv.PubKey(), + Ancestry: validTestIncomingAncestry( + commitmentID, + ), + }, + }, + } + + disabledStore := newTestVTXOStore() + var notified []*vtxo.Descriptor + + disabledHandler := &LocalPersistenceOutboxHandler{ + Store: disabledStore, + PackageStore: &testPackageStore{}, + OperatorKey: operatorPriv.PubKey(), + ExitDelay: exitDelay, + AuthenticateIncomingExpiry: func(_ context.Context, + _ []vtxo.Ancestry) (vtxo.AuthenticatedBatchEvidence, + error) { + + return vtxo.AuthenticatedBatchEvidence{ + BatchExpiry: 10_000, + EarliestCommitmentHeight: 100, + }, nil + }, + // VerifyIncomingAssetPackage intentionally nil (assets off). + ResolveIncomingClientKey: func(_ context.Context, + recipient ArkRecipientOutput) (keychain.KeyDescriptor, + error) { + + if bytes.Equal(recipient.PkScript, btcPkScript) { + return keychain.KeyDescriptor{ + PubKey: btcPriv.PubKey(), + }, nil + } + + return keychain.KeyDescriptor{ + PubKey: recipPriv.PubKey(), + }, nil + }, + NotifyIncomingVTXOs: func(_ context.Context, + descs []*vtxo.Descriptor) error { + + notified = append(notified, descs...) + + return nil + }, + } + + authEvents, err := disabledHandler.Handle( + t.Context(), sessionID, &AuthenticateIncomingMetadataRequest{ + SessionID: sessionID, + Matches: matches, + ArkPSBT: arkPSBT, + FinalCheckpointPSBTs: cps, + Recipients: recipients, + TaprootAssetTransfer: xfer, + }, + ) + require.NoError(t, err) + require.Len(t, authEvents, 1) + + resolved, ok := authEvents[0].(*IncomingMetadataResolvedEvent) + require.True(t, ok) + require.Len(t, resolved.Matches, 1) + require.Equal(t, btcIdx, resolved.Matches[0].OutputIndex) + require.False(t, resolved.Matches[0].Metadata.AssetVerified) + + matEvents, err := disabledHandler.Handle( + t.Context(), sessionID, &MaterializeIncomingVTXOsRequest{ + SessionID: sessionID, + ArkPSBT: arkPSBT, + FinalCheckpointPSBTs: cps, + Recipients: recipients, + MetadataMatches: resolved.Matches, + TaprootAssetTransfer: xfer, + }, + ) + require.NoError(t, err) + require.Len(t, matEvents, 1) + + handledEv, ok := matEvents[0].(*IncomingHandledEvent) + require.True(t, ok) + require.Equal( + t, [][sha256.Size]byte{sha256.Sum256(btcPkScript)}, + handledEv.MaterializedPlainScripts, ) + require.Len(t, notified, 1) + require.Equal(t, btcPkScript, notified[0].PkScript) + + // Asset output must NOT have been saved while Bitcoin output was. + _, err = disabledStore.GetVTXO(t.Context(), wire.OutPoint{ + Hash: chainhash.Hash(sessionID), + Index: assetIdx, + }) + require.Error(t, err) + + savedBTC, err := disabledStore.GetVTXO(t.Context(), wire.OutPoint{ + Hash: chainhash.Hash(sessionID), + Index: btcIdx, + }) + require.NoError(t, err) + require.Equal(t, btcPkScript, savedBTC.PkScript) + + // Canonicalization check (M-8): incoming mixed-case TaprootAssetRef is + // lowercased and trimmed by parseRecipientEventAsset. + xferBytes, err := xfer.MarshalBinary() + require.NoError(t, err) + parsedAsset, _, err := parseIncomingEventAsset( + &arkrpc.OORRecipientEvent{ + TaprootAssetRoot: assetRoot[:], + TaprootAssetRef: " ASSET-USD-MIXED ", + TaprootAssetAmount: assetAmount, + TaprootAssetTransfer: xferBytes, + }, len(cps), + ) + require.NoError(t, err) + require.Equal(t, "asset-usd-mixed", parsedAsset.Ref) } diff --git a/oor/events.go b/oor/events.go index b40a79ed6..000b4f9cd 100644 --- a/oor/events.go +++ b/oor/events.go @@ -1,6 +1,7 @@ package oor import ( + "crypto/sha256" "time" "github.com/btcsuite/btcd/psbt/v2" @@ -186,6 +187,15 @@ type IncomingTransferEvent struct { // TaprootAssetTransfer carries the sealed Taproot Asset transition // packages when this incoming transfer creates an asset VTXO. TaprootAssetTransfer *oortx.TaprootAssetTransfer + + // RecipientEventID identifies the per-script recipient event returned + // by phase-1 resolution so ReceiveResolving ignores stale responses + // from earlier passes on the same session. + RecipientEventID uint64 + + // RecipientPkScript is the uncomposed routing script resolved by + // phase-1 lookup, paired with RecipientEventID for pass correlation. + RecipientPkScript []byte } // eventSealed marks this as implementing the sealed Event interface. @@ -196,15 +206,21 @@ func (e *IncomingTransferEvent) eventSealed() {} // descriptors are attached so the actor can forward them to the VTXO // manager for actor activation. type IncomingHandledEvent struct { - // MaterializedVTXOs contains descriptors that were durably - // persisted during materialization. The OOR actor forwards these - // to the VTXO manager so it can spawn monitoring actors. + // MaterializedVTXOs contains newly materialized live descriptors that + // were durably persisted during materialization. The OOR actor + // forwards these to the VTXO manager so it can spawn monitoring actors. MaterializedVTXOs []*vtxo.Descriptor // MaterializedOutpoints identifies the persisted VTXOs by outpoint so // durable callback delivery can round-trip the event without embedding // the full descriptor payload in the mailbox record. MaterializedOutpoints []wire.OutPoint + + // MaterializedPlainScripts records the SHA-256 hashes of plain + // (non-asset) output scripts owned and handled in this pass so + // follow-up hints for those scripts stay idempotent no-ops without + // reopening a completed session. + MaterializedPlainScripts [][sha256.Size]byte } // eventSealed marks this as implementing the sealed Event interface. diff --git a/oor/incoming_adapter.go b/oor/incoming_adapter.go index 5ebf978f1..800d7d894 100644 --- a/oor/incoming_adapter.go +++ b/oor/incoming_adapter.go @@ -180,9 +180,10 @@ func IncomingTransferEventFromResponseWithLimits(sessionID SessionID, return nil, err } - recipients, assetTransfer, err := incomingRecipientsFromEvent( - arkPSBT, recipientEvt, len(checkpoints), - ) + recipients, assetTransfer, routingScript, err := + incomingRecipientsFromEvent( + arkPSBT, recipientEvt, len(checkpoints), + ) if err != nil { return nil, err } @@ -200,31 +201,33 @@ func IncomingTransferEventFromResponseWithLimits(sessionID SessionID, AncestorPackages: ancestors, Recipients: recipients, TaprootAssetTransfer: assetTransfer, + RecipientEventID: recipientEventID, + RecipientPkScript: routingScript, }, nil } // incomingRecipientsFromEvent overlays the policy and optional Taproot Asset // metadata carried by the recipient event onto the structurally extracted Ark -// outputs. +// outputs and returns the matched recipient's uncomposed routing script. func incomingRecipientsFromEvent(ark *psbt.Packet, evt *arkrpc.OORRecipientEvent, checkpointCount int) ( - []ArkRecipientOutput, *oortx.TaprootAssetTransfer, error) { + []ArkRecipientOutput, *oortx.TaprootAssetTransfer, []byte, error) { recipients, err := ExtractArkRecipients(ark) if err != nil { - return nil, nil, err + return nil, nil, nil, err } if evt.GetValue() > uint64(math.MaxInt64) { - return nil, nil, fmt.Errorf("recipient event value overflows " + - "int64") + return nil, nil, nil, fmt.Errorf("recipient event value " + + "overflows int64") } asset, assetTransfer, err := parseIncomingEventAsset( evt, checkpointCount, ) if err != nil { - return nil, nil, err + return nil, nil, nil, err } value := btcutil.Amount(evt.GetValue()) @@ -234,14 +237,14 @@ func incomingRecipientsFromEvent(ark *psbt.Packet, } if recipients[i].Value != value { - return nil, nil, fmt.Errorf("recipient event value " + - "mismatch") + return nil, nil, nil, fmt.Errorf("recipient event " + + "value mismatch") } if !bytes.Equal( recipients[i].PkScript, evt.GetRecipientPkScript(), ) { - return nil, nil, fmt.Errorf("recipient event " + + return nil, nil, nil, fmt.Errorf("recipient event " + "pkscript mismatch") } @@ -249,18 +252,16 @@ func incomingRecipientsFromEvent(ark *psbt.Packet, []byte(nil), evt.GetVtxoPolicyTemplate()..., ) recipients[i].Asset = asset - if asset != nil { - _, err := recipients[i].RoutingPkScript() - if err != nil { - return nil, nil, fmt.Errorf("recipient event "+ - "asset script binding: %w", err) - } + routingScript, err := recipients[i].RoutingPkScript() + if err != nil { + return nil, nil, nil, fmt.Errorf("recipient event "+ + "asset script binding: %w", err) } - return recipients, assetTransfer, nil + return recipients, assetTransfer, routingScript, nil } - return nil, nil, fmt.Errorf("recipient event output %d not found", + return nil, nil, nil, fmt.Errorf("recipient event output %d not found", evt.GetOutputIndex()) } @@ -272,7 +273,7 @@ func parseIncomingEventAsset(evt *arkrpc.OORRecipientEvent, *oortx.TaprootAssetTransfer, error) { rootRaw := evt.GetTaprootAssetRoot() - ref := evt.GetTaprootAssetRef() + ref := strings.ToLower(strings.TrimSpace(evt.GetTaprootAssetRef())) amount := evt.GetTaprootAssetAmount() transferRaw := evt.GetTaprootAssetTransfer() diff --git a/oor/incoming_vtxo.go b/oor/incoming_vtxo.go index 69925f4d3..07b149aa9 100644 --- a/oor/incoming_vtxo.go +++ b/oor/incoming_vtxo.go @@ -4,6 +4,7 @@ import ( "bytes" "crypto/sha256" "fmt" + "strings" "github.com/btcsuite/btcd/btcec/v2" "github.com/btcsuite/btcd/btcutil/v2" @@ -229,7 +230,9 @@ func BuildIncomingVTXODescriptor(ark *psbt.Packet, root := cfg.Asset.Root desc.TapScript = nil desc.TaprootAssetRoot = &root - desc.TaprootAssetRef = cfg.Asset.Ref + desc.TaprootAssetRef = strings.ToLower( + strings.TrimSpace(cfg.Asset.Ref), + ) desc.TaprootAssetAmount = cfg.Asset.Amount desc.TaprootAssetSealedPackage = bytes.Clone( cfg.TaprootAssetSealedPackage, diff --git a/oor/local_persistence_handler.go b/oor/local_persistence_handler.go index 2165a95f6..7afccea7f 100644 --- a/oor/local_persistence_handler.go +++ b/oor/local_persistence_handler.go @@ -3,6 +3,7 @@ package oor import ( "bytes" "context" + "crypto/sha256" "errors" "fmt" "log/slog" @@ -246,11 +247,11 @@ func (h *LocalPersistenceOutboxHandler) handleAuthenticateIncomingMetadata( Recipients[i] } - matches := make([]IncomingMetadataMatch, len(msg.Matches)) - copy(matches, msg.Matches) - for i := range matches { + verifiedMatches := make([]IncomingMetadataMatch, 0, len(msg.Matches)) + var lastAssetTermErr error + for _, match := range msg.Matches { evidence, err := h.AuthenticateIncomingExpiry( - ctx, matches[i].Metadata.Ancestry, + ctx, match.Metadata.Ancestry, ) if err != nil { if errors.Is(err, vtxo.ErrInvalidBatchExpiryEvidence) { @@ -266,61 +267,99 @@ func (h *LocalPersistenceOutboxHandler) handleAuthenticateIncomingMetadata( return nil, &terminalOutboxError{cause: err} } - matches[i].Metadata.BatchExpiry = evidence.BatchExpiry - matches[i].Metadata.CreatedHeight = + match.Metadata.BatchExpiry = evidence.BatchExpiry + match.Metadata.CreatedHeight = evidence.EarliestCommitmentHeight - matches[i].Metadata.ExpiryAuthenticated = true + match.Metadata.ExpiryAuthenticated = true - recipient, hasRecipient := recipientsByIndex[matches[i]. - OutputIndex] + recipient, hasRecipient := recipientsByIndex[match.OutputIndex] if !hasRecipient || recipient.Asset == nil { - continue - } + verifiedMatches = append(verifiedMatches, match) - if h.VerifyIncomingAssetPackage == nil { - return nil, &terminalOutboxError{ - cause: fmt.Errorf("incoming asset output %d "+ - "requires an asset package verifier", - recipient.OutputIndex), - } - } - if msg.TaprootAssetTransfer == nil || - len(msg.TaprootAssetTransfer.ArkPackage) == 0 { - return nil, &terminalOutboxError{ - cause: fmt.Errorf("incoming asset output %d "+ - "missing sealed ark asset package", - recipient.OutputIndex), - } + continue } - err = h.VerifyIncomingAssetPackage( - ctx, IncomingAssetVerification{ - SessionID: msg.SessionID, - Recipient: recipient, - ArkPSBT: msg.ArkPSBT, - FinalCheckpointPSBTs: msg.FinalCheckpointPSBTs, - AncestorPackages: msg.AncestorPackages, - Metadata: matches[i].Metadata, - TaprootAssetTransfer: msg.TaprootAssetTransfer, - }, + termErr, retryErr := h.verifyAuthenticatedAssetMatch( + ctx, msg, recipient, &match.Metadata, ) - if err != nil { - if errors.Is(err, ErrInvalidIncomingAssetPackage) { - return nil, &terminalOutboxError{cause: err} - } + if retryErr != nil { + return nil, retryErr + } + if termErr != nil { + // Isolate per-output asset verification failures so a + // disabled asset engine or one bad asset output cannot + // drop valid sibling Bitcoin outputs in the same tx. + logger(ctx).InfoS(ctx, "Skipping unverifiable "+ + "incoming asset output", + slog.String( + "session_id", msg.SessionID.String(), + ), + slog.Uint64( + "output_index", + uint64(recipient.OutputIndex), + ), + slog.String("reason", termErr.Error()), + ) + lastAssetTermErr = termErr - return nil, err + continue } - matches[i].Metadata.AssetVerified = true + verifiedMatches = append(verifiedMatches, match) + } + + if len(verifiedMatches) == 0 && lastAssetTermErr != nil { + return nil, &terminalOutboxError{cause: lastAssetTermErr} } return []Event{&IncomingMetadataResolvedEvent{ - Matches: matches, + Matches: verifiedMatches, ExpiryAuthenticated: true, }}, nil } +// verifyAuthenticatedAssetMatch validates one asset-bearing incoming match. +// Deterministic failures are returned as termErr (so sibling outputs can still +// materialize); transient backend errors are returned as retryErr. +func (h *LocalPersistenceOutboxHandler) verifyAuthenticatedAssetMatch( + ctx context.Context, msg *AuthenticateIncomingMetadataRequest, + recipient ArkRecipientOutput, metadata *IncomingVTXOMetadata) (error, + error) { + + if h.VerifyIncomingAssetPackage == nil { + return fmt.Errorf("incoming asset output %d requires an "+ + "asset package verifier", recipient.OutputIndex), nil + } + if msg.TaprootAssetTransfer == nil || + len(msg.TaprootAssetTransfer.ArkPackage) == 0 { + return fmt.Errorf("incoming asset output %d missing "+ + "sealed ark asset package", recipient.OutputIndex), nil + } + + err := h.VerifyIncomingAssetPackage( + ctx, IncomingAssetVerification{ + SessionID: msg.SessionID, + Recipient: recipient, + ArkPSBT: msg.ArkPSBT, + FinalCheckpointPSBTs: msg.FinalCheckpointPSBTs, + AncestorPackages: msg.AncestorPackages, + Metadata: *metadata, + TaprootAssetTransfer: msg.TaprootAssetTransfer, + }, + ) + if err != nil { + if errors.Is(err, ErrInvalidIncomingAssetPackage) { + return err, nil + } + + return nil, err + } + + metadata.AssetVerified = true + + return nil, nil +} + // handleMaterializeIncoming persists recipient VTXOs for an incoming transfer // before the receive FSM acknowledges the transfer to the server. func (h *LocalPersistenceOutboxHandler) handleMaterializeIncoming( @@ -497,6 +536,7 @@ func (h *LocalPersistenceOutboxHandler) materializeIncoming(ctx context.Context, ownedRecipients := 0 materializedVTXOs := make([]*vtxo.Descriptor, 0, len(msg.Recipients)) materializedOutpoints := make([]wire.OutPoint, 0, len(msg.Recipients)) + plainScripts := make([][sha256.Size]byte, 0, len(msg.Recipients)) sessionIDHash := chainhash.Hash(msg.SessionID) metadataByOutput := make( map[uint32]IncomingVTXOMetadata, len(msg.MetadataMatches), @@ -549,9 +589,24 @@ func (h *LocalPersistenceOutboxHandler) materializeIncoming(ctx context.Context, return nil, err } + if recipient.Asset != nil && + h.VerifyIncomingAssetPackage == nil { + + continue + } + ownedRecipients++ metadata, ok := metadataByOutput[recipient.OutputIndex] + if !ok && recipient.Asset != nil && hasActorDBTx(ctx) { + // This asset output failed per-output verification in + // AuthenticateIncomingMetadata while sibling outputs + // succeeded; skip it without failing the sibling + // outputs. + ownedRecipients-- + + continue + } // Legacy synchronous path for callers outside the durable // actor transaction (e.g. systest, non-actor consumers). @@ -649,36 +704,23 @@ func (h *LocalPersistenceOutboxHandler) materializeIncoming(ctx context.Context, return nil, err } - err = h.Store.SaveVTXO(ctx, desc) + stored, shouldNotify, err := h.persistIncomingDescriptor( + ctx, desc, + ) if err != nil { - // SaveVTXO may fail for duplicates on retry/restart - // paths. Treat that case as idempotent only if the - // already-persisted descriptor matches the - // materialized recipient output. - existing, getErr := h.Store.GetVTXO(ctx, desc.Outpoint) - if getErr != nil || existing == nil { - return nil, err - } - - if existing.Amount != desc.Amount { - return nil, err - } - - if !bytes.Equal(existing.PkScript, desc.PkScript) { - return nil, err - } - - if !descriptorsMatchAssetState(existing, desc) { - return nil, err - } - - desc = existing + return nil, err + } + if shouldNotify { + materializedVTXOs = append(materializedVTXOs, stored) } - - materializedVTXOs = append(materializedVTXOs, desc) materializedOutpoints = append( - materializedOutpoints, desc.Outpoint, + materializedOutpoints, stored.Outpoint, ) + if stored.TaprootAssetRoot == nil && len(stored.PkScript) > 0 { + plainScripts = appendUniqueScriptHash( + plainScripts, sha256.Sum256(stored.PkScript), + ) + } if h.PackageStore != nil { err := h.PackageStore.UpsertBinding( @@ -729,11 +771,70 @@ func (h *LocalPersistenceOutboxHandler) materializeIncoming(ctx context.Context, } return []Event{&IncomingHandledEvent{ - MaterializedVTXOs: materializedVTXOs, - MaterializedOutpoints: materializedOutpoints, + MaterializedVTXOs: materializedVTXOs, + MaterializedOutpoints: materializedOutpoints, + MaterializedPlainScripts: plainScripts, }}, nil } +// persistIncomingDescriptor saves desc idempotently without resurrecting a +// previously persisted terminal (e.g. Spent) VTXO row. The boolean reports +// whether callers should notify the VTXO manager about the descriptor. +func (h *LocalPersistenceOutboxHandler) persistIncomingDescriptor( + ctx context.Context, desc *vtxo.Descriptor) (*vtxo.Descriptor, bool, + error) { + + existing, getErr := h.Store.GetVTXO(ctx, desc.Outpoint) + if getErr == nil && existing != nil { + if err := verifyStoredDescriptorMatch( + existing, desc, + ); err != nil { + return nil, false, err + } + + return existing, !existing.Status.IsTerminal(), nil + } + + if err := h.Store.SaveVTXO(ctx, desc); err != nil { + // SaveVTXO may fail for concurrent duplicates on retry/restart + // paths. Treat that case as idempotent only if the stored row + // matches the materialized output. + existing, getErr = h.Store.GetVTXO(ctx, desc.Outpoint) + if getErr != nil || existing == nil { + return nil, false, err + } + if matchErr := verifyStoredDescriptorMatch( + existing, desc, + ); matchErr != nil { + return nil, false, err + } + + return existing, !existing.Status.IsTerminal(), nil + } + + return desc, true, nil +} + +// verifyStoredDescriptorMatch checks immutable amount, script, and Taproot +// Asset equality between an already-stored VTXO row and a newly materialized +// descriptor for the same outpoint. +func verifyStoredDescriptorMatch(existing, desc *vtxo.Descriptor) error { + if existing.Amount != desc.Amount { + return fmt.Errorf("existing VTXO %s amount mismatch: %d != %d", + desc.Outpoint, existing.Amount, desc.Amount) + } + if !bytes.Equal(existing.PkScript, desc.PkScript) { + return fmt.Errorf("existing VTXO %s pkScript mismatch", + desc.Outpoint) + } + if !descriptorsMatchAssetState(existing, desc) { + return fmt.Errorf("existing VTXO %s asset state mismatch", + desc.Outpoint) + } + + return nil +} + // emitVTXOsReceived books one receive per materialized descriptor. // // It mirrors the session behaviour's own emission exactly, session id diff --git a/oor/outgoing_replay.go b/oor/outgoing_replay.go index 9b72083e1..62bf718d6 100644 --- a/oor/outgoing_replay.go +++ b/oor/outgoing_replay.go @@ -12,15 +12,26 @@ import ( const ( // outgoingReplayVersion is the normalized recipient-proof encoding - // written before an outgoing submit can be dispatched. + // written before an outgoing Bitcoin OOR submit can be dispatched. outgoingReplayVersion byte = 1 + // outgoingAssetReplayVersion is the normalized request-identity and + // summary proof encoding written before an outgoing asset OOR submit + // can be dispatched. Using a distinct version byte isolates Bitcoin + // and asset idempotency namespaces cleanly. + outgoingAssetReplayVersion byte = 2 + // maxOutgoingReplayPkScriptSize is Bitcoin's maximum script size. OOR // construction validates scripts before this proof is written. maxOutgoingReplayPkScriptSize = 10_000 - outgoingReplayHeaderSize = 5 - outgoingReplayEntrySize = 16 + // maxOutgoingAssetRefSize bounds canonical asset references encoded in + // outgoing asset replay proofs. + maxOutgoingAssetRefSize = 256 + + outgoingReplayHeaderSize = 5 + outgoingReplayEntrySize = 16 + outgoingAssetReplayHeaderSize = 33 ) // NewOutgoingReplayData binds the caller-requested recipients to their @@ -197,3 +208,150 @@ func OutgoingReplayRecipients(raw []byte) ([]ArkRecipientOutput, error) { return recipients, nil } + +// OutgoingAssetReplay binds an asset OOR idempotency attempt to its canonical +// request parameters and response summary so replays verify identity and return +// the original figures instead of newly built or blank values. +type OutgoingAssetReplay struct { + OutputIndex uint32 + SelectedInputCount uint32 + AssetRef string + AssetAmount uint64 + AssetChangeAmount uint64 + SenderBtcChangeSat int64 + RecipientPolicy []byte +} + +// IsOutgoingAssetReplayData reports whether raw is a v2 asset OOR replay proof. +func IsOutgoingAssetReplayData(raw []byte) bool { + return len(raw) > 0 && raw[0] == outgoingAssetReplayVersion +} + +// NewOutgoingAssetReplayData validates and serializes an asset OOR replay +// proof. +func NewOutgoingAssetReplayData(r OutgoingAssetReplay) ([]byte, error) { + switch { + case r.AssetRef == "" || len(r.AssetRef) > maxOutgoingAssetRefSize: + return nil, fmt.Errorf("invalid asset replay ref length %d", + len(r.AssetRef)) + + case r.AssetAmount == 0: + return nil, fmt.Errorf("asset replay amount must be positive") + + case r.SenderBtcChangeSat < 0 || + r.SenderBtcChangeSat > btcutil.MaxSatoshi: + return nil, fmt.Errorf("invalid asset replay sender BTC "+ + "change %d", r.SenderBtcChangeSat) + + case len(r.RecipientPolicy) == 0 || + len(r.RecipientPolicy) > maxOutgoingReplayPkScriptSize: + return nil, fmt.Errorf("invalid asset replay recipient policy "+ + "length %d", len(r.RecipientPolicy)) + } + + totalLen := outgoingAssetReplayHeaderSize + 4 + len(r.AssetRef) + + 4 + len(r.RecipientPolicy) + raw := make([]byte, 0, totalLen) + raw = append(raw, outgoingAssetReplayVersion) + + var scratch [8]byte + binary.BigEndian.PutUint32(scratch[:4], r.OutputIndex) + raw = append(raw, scratch[:4]...) + + binary.BigEndian.PutUint32(scratch[:4], r.SelectedInputCount) + raw = append(raw, scratch[:4]...) + + binary.BigEndian.PutUint64(scratch[:], r.AssetAmount) + raw = append(raw, scratch[:]...) + + binary.BigEndian.PutUint64(scratch[:], r.AssetChangeAmount) + raw = append(raw, scratch[:]...) + + binary.BigEndian.PutUint64(scratch[:], uint64(r.SenderBtcChangeSat)) + raw = append(raw, scratch[:]...) + + binary.BigEndian.PutUint32(scratch[:4], uint32(len(r.AssetRef))) + raw = append(raw, scratch[:4]...) + raw = append(raw, r.AssetRef...) + + binary.BigEndian.PutUint32(scratch[:4], uint32(len(r.RecipientPolicy))) + raw = append(raw, scratch[:4]...) + raw = append(raw, r.RecipientPolicy...) + + return raw, nil +} + +// DecodeOutgoingAssetReplayData decodes a v2 asset OOR replay proof. +func DecodeOutgoingAssetReplayData(raw []byte) (OutgoingAssetReplay, error) { + var out OutgoingAssetReplay + if len(raw) < outgoingAssetReplayHeaderSize+8 { + return out, fmt.Errorf("asset outgoing replay proof is " + + "truncated") + } + if raw[0] != outgoingAssetReplayVersion { + return out, fmt.Errorf("unknown asset outgoing replay proof "+ + "version: %d", raw[0]) + } + + offset := 1 + out.OutputIndex = binary.BigEndian.Uint32(raw[offset:]) + offset += 4 + + out.SelectedInputCount = binary.BigEndian.Uint32(raw[offset:]) + offset += 4 + + out.AssetAmount = binary.BigEndian.Uint64(raw[offset:]) + offset += 8 + if out.AssetAmount == 0 { + return OutgoingAssetReplay{}, fmt.Errorf("asset replay " + + "amount must be positive") + } + + out.AssetChangeAmount = binary.BigEndian.Uint64(raw[offset:]) + offset += 8 + + senderChange := binary.BigEndian.Uint64(raw[offset:]) + offset += 8 + if senderChange > uint64(btcutil.MaxSatoshi) { + return OutgoingAssetReplay{}, fmt.Errorf("invalid asset "+ + "replay sender BTC change %d", senderChange) + } + out.SenderBtcChangeSat = int64(senderChange) + + if len(raw)-offset < 4 { + return OutgoingAssetReplay{}, fmt.Errorf("asset replay ref " + + "length is truncated") + } + refLen := binary.BigEndian.Uint32(raw[offset:]) + offset += 4 + if refLen == 0 || refLen > maxOutgoingAssetRefSize || + uint32(len(raw)-offset) < refLen { + return OutgoingAssetReplay{}, fmt.Errorf("invalid asset "+ + "replay ref length %d", refLen) + } + out.AssetRef = string(raw[offset : offset+int(refLen)]) + offset += int(refLen) + + if len(raw)-offset < 4 { + return OutgoingAssetReplay{}, fmt.Errorf("asset replay " + + "policy length is truncated") + } + policyLen := binary.BigEndian.Uint32(raw[offset:]) + offset += 4 + if policyLen == 0 || policyLen > maxOutgoingReplayPkScriptSize || + uint32(len(raw)-offset) < policyLen { + return OutgoingAssetReplay{}, fmt.Errorf("invalid asset "+ + "replay policy length %d", policyLen) + } + out.RecipientPolicy = append( + []byte(nil), raw[offset:offset+int(policyLen)]..., + ) + offset += int(policyLen) + + if offset != len(raw) { + return OutgoingAssetReplay{}, fmt.Errorf("asset outgoing "+ + "replay proof has %d trailing bytes", len(raw)-offset) + } + + return out, nil +} diff --git a/oor/outgoing_snapshot_test.go b/oor/outgoing_snapshot_test.go index b72a5e0f3..2d9f811b5 100644 --- a/oor/outgoing_snapshot_test.go +++ b/oor/outgoing_snapshot_test.go @@ -255,6 +255,46 @@ func TestOutgoingReplayRecipientsRejectsMalformedProof(t *testing.T) { require.ErrorContains(t, err, "pkScript is truncated") } +// TestOutgoingAssetReplayRoundTripAndRejectsMalformed verifies v2 asset replay +// proof encoding, decoding, version isolation, and strict framing. +func TestOutgoingAssetReplayRoundTripAndRejectsMalformed(t *testing.T) { + t.Parallel() + + orig := OutgoingAssetReplay{ + OutputIndex: 1, + SelectedInputCount: 2, + AssetRef: "asset-usd", + AssetAmount: 500, + AssetChangeAmount: 250, + SenderBtcChangeSat: 1_200, + RecipientPolicy: []byte{ + 0x01, + 0x02, + 0x03, + 0x04, + }, + } + + raw, err := NewOutgoingAssetReplayData(orig) + require.NoError(t, err) + require.True(t, IsOutgoingAssetReplayData(raw)) + + // Bitcoin v1 decoder must reject v2 asset proofs. + _, err = OutgoingReplayRecipients(raw) + require.ErrorContains(t, err, "unknown outgoing replay proof version") + + decoded, err := DecodeOutgoingAssetReplayData(raw) + require.NoError(t, err) + require.Equal(t, orig, decoded) + + trailing := append(append([]byte(nil), raw...), 0x00) + _, err = DecodeOutgoingAssetReplayData(trailing) + require.ErrorContains(t, err, "trailing bytes") + + _, err = DecodeOutgoingAssetReplayData(raw[:len(raw)-1]) + require.Error(t, err) +} + // TestSnapshotRetryMetadataRoundTrip verifies that RetryAfter and retry // reason survive TLV encode/decode. This is essential for restart-safe // retry scheduling: the actor persists retry metadata alongside the real diff --git a/oor/receive_snapshot.go b/oor/receive_snapshot.go index 4d37d96a7..5ae7cad60 100644 --- a/oor/receive_snapshot.go +++ b/oor/receive_snapshot.go @@ -2,6 +2,7 @@ package oor import ( "context" + "crypto/sha256" "encoding/binary" "fmt" @@ -26,7 +27,9 @@ const ( incomingSnapshotResolveAttemptsType tlv.Type = 21 incomingSnapshotRecipientsType tlv.Type = 23 incomingSnapshotTaprootAssetTransferType tlv.Type = 25 - incomingSnapshotCompletedEventIDsType tlv.Type = 27 + incomingSnapshotCompletedHintsType tlv.Type = 27 + incomingSnapshotActiveScriptHashType tlv.Type = 29 + incomingSnapshotPlainScriptHashesType tlv.Type = 31 ) // IncomingPhase identifies the coarse stage of an incoming OOR receive @@ -97,13 +100,21 @@ type IncomingSnapshot struct { RecipientPkScript []byte // RecipientEventID is the per-script cursor hint paired with - // RecipientPkScript during resolve-pending restart and carried through - // ReceiveNotified/ReceiveAwaitingAck until ReceiveCompleted records it. + // RecipientPkScript or ActiveScriptHash until ReceiveCompleted records + // the completed hint. RecipientEventID uint64 - // CompletedEventIDs records recipient event IDs already processed by - // this session across sequential receive passes. - CompletedEventIDs []uint64 + // ActiveScriptHash is the SHA-256 hash of the active hint's routing + // pkScript during materialize-pending and ack-pending phases. + ActiveScriptHash [sha256.Size]byte + + // CompletedHints records per-script recipient hints already processed + // by this session across sequential receive passes. + CompletedHints []IncomingHintKey + + // MaterializedPlainScripts records SHA-256 hashes of non-asset scripts + // already materialized on this session. + MaterializedPlainScripts [][sha256.Size]byte // MetadataAttempts is the persisted retry count for the authoritative // metadata resolution, used to bound backoff and the terminal give-up @@ -141,8 +152,11 @@ func NewIncomingSnapshot(sessionID SessionID, []byte(nil), s.RecipientPkScript..., ) snap.RecipientEventID = s.RecipientEventID - snap.CompletedEventIDs = append( - []uint64(nil), s.CompletedEventIDs..., + snap.CompletedHints = append( + []IncomingHintKey(nil), s.CompletedHints..., + ) + snap.MaterializedPlainScripts = append( + [][sha256.Size]byte(nil), s.MaterializedPlainScripts..., ) snap.ResolveAttempts = s.ResolveAttempts @@ -167,23 +181,34 @@ func NewIncomingSnapshot(sessionID SessionID, ) snap.Recipients = CloneArkRecipients(s.Recipients) snap.TaprootAssetTransfer = s.TaprootAssetTransfer.Clone() - snap.RecipientEventID = s.RecipientEventID - snap.CompletedEventIDs = append( - []uint64(nil), s.CompletedEventIDs..., + snap.RecipientEventID = s.ActiveHint.EventID + snap.ActiveScriptHash = s.ActiveHint.ScriptHash + snap.CompletedHints = append( + []IncomingHintKey(nil), s.CompletedHints..., + ) + snap.MaterializedPlainScripts = append( + [][sha256.Size]byte(nil), s.MaterializedPlainScripts..., ) snap.MetadataAttempts = s.MetadataAttempts case *ReceiveAwaitingAck: snap.Phase = IncomingPhaseAckPending - snap.RecipientEventID = s.RecipientEventID - snap.CompletedEventIDs = append( - []uint64(nil), s.CompletedEventIDs..., + snap.RecipientEventID = s.ActiveHint.EventID + snap.ActiveScriptHash = s.ActiveHint.ScriptHash + snap.CompletedHints = append( + []IncomingHintKey(nil), s.CompletedHints..., + ) + snap.MaterializedPlainScripts = append( + [][sha256.Size]byte(nil), s.MaterializedPlainScripts..., ) case *ReceiveCompleted: snap.Phase = IncomingPhaseCompleted - snap.CompletedEventIDs = append( - []uint64(nil), s.CompletedEventIDs..., + snap.CompletedHints = append( + []IncomingHintKey(nil), s.CompletedHints..., + ) + snap.MaterializedPlainScripts = append( + [][sha256.Size]byte(nil), s.MaterializedPlainScripts..., ) case *Failed: @@ -218,6 +243,28 @@ func NewReceiveSessionFromSnapshot(ctx context.Context, ) } +// ActiveHintKey returns the active per-script hint tracked by this snapshot +// for non-terminal incoming phases, or the zero key when unset. +func (s *IncomingSnapshot) ActiveHintKey() IncomingHintKey { + if s == nil { + return IncomingHintKey{} + } + if s.Phase == IncomingPhaseResolvePending { + return NewIncomingHintKey( + s.RecipientPkScript, s.RecipientEventID, + ) + } + if s.RecipientEventID == 0 || + s.ActiveScriptHash == ([sha256.Size]byte{}) { + return IncomingHintKey{} + } + + return IncomingHintKey{ + ScriptHash: s.ActiveScriptHash, + EventID: s.RecipientEventID, + } +} + // IncomingStateFromSnapshot converts an incoming receive snapshot into the // corresponding concrete state. func IncomingStateFromSnapshot(snapshot *IncomingSnapshot) (SessionState, @@ -243,8 +290,13 @@ func IncomingStateFromSnapshot(snapshot *IncomingSnapshot) (SessionState, []byte(nil), snapshot.RecipientPkScript..., ), RecipientEventID: snapshot.RecipientEventID, - CompletedEventIDs: append( - []uint64(nil), snapshot.CompletedEventIDs..., + CompletedHints: append( + []IncomingHintKey(nil), + snapshot.CompletedHints..., + ), + MaterializedPlainScripts: append( + [][sha256.Size]byte(nil), + snapshot.MaterializedPlainScripts..., ), ResolveAttempts: snapshot.ResolveAttempts, }, nil @@ -275,26 +327,41 @@ func IncomingStateFromSnapshot(snapshot *IncomingSnapshot) (SessionState, ), TaprootAssetTransfer: snapshot.TaprootAssetTransfer. Clone(), - RecipientEventID: snapshot.RecipientEventID, - CompletedEventIDs: append( - []uint64(nil), snapshot.CompletedEventIDs..., + ActiveHint: snapshot.ActiveHintKey(), + CompletedHints: append( + []IncomingHintKey(nil), + snapshot.CompletedHints..., + ), + MaterializedPlainScripts: append( + [][sha256.Size]byte(nil), + snapshot.MaterializedPlainScripts..., ), MetadataAttempts: snapshot.MetadataAttempts, }, nil case IncomingPhaseAckPending: return &ReceiveAwaitingAck{ - SessionID: snapshot.SessionID, - RecipientEventID: snapshot.RecipientEventID, - CompletedEventIDs: append( - []uint64(nil), snapshot.CompletedEventIDs..., + SessionID: snapshot.SessionID, + ActiveHint: snapshot.ActiveHintKey(), + CompletedHints: append( + []IncomingHintKey(nil), + snapshot.CompletedHints..., + ), + MaterializedPlainScripts: append( + [][sha256.Size]byte(nil), + snapshot.MaterializedPlainScripts..., ), }, nil case IncomingPhaseCompleted: return &ReceiveCompleted{ - CompletedEventIDs: append( - []uint64(nil), snapshot.CompletedEventIDs..., + CompletedHints: append( + []IncomingHintKey(nil), + snapshot.CompletedHints..., + ), + MaterializedPlainScripts: append( + [][sha256.Size]byte(nil), + snapshot.MaterializedPlainScripts..., ), }, nil @@ -399,12 +466,34 @@ func encodeIncomingSnapshot(snapshot *IncomingSnapshot) ([]byte, error) { ), ) } - if len(snapshot.CompletedEventIDs) > 0 { - completedIDsRaw := encodeUint64List(snapshot.CompletedEventIDs) + if len(snapshot.CompletedHints) > 0 { + completedHintsRaw := encodeIncomingHintKeys( + snapshot.CompletedHints, + ) + records = append( + records, tlv.MakePrimitiveRecord( + incomingSnapshotCompletedHintsType, + &completedHintsRaw, + ), + ) + } + if snapshot.ActiveScriptHash != ([sha256.Size]byte{}) { + activeHashRaw := snapshot.ActiveScriptHash[:] + records = append( + records, tlv.MakePrimitiveRecord( + incomingSnapshotActiveScriptHashType, + &activeHashRaw, + ), + ) + } + if len(snapshot.MaterializedPlainScripts) > 0 { + plainScriptsRaw := encodeScriptHashes( + snapshot.MaterializedPlainScripts, + ) records = append( records, tlv.MakePrimitiveRecord( - incomingSnapshotCompletedEventIDsType, - &completedIDsRaw, + incomingSnapshotPlainScriptHashesType, + &plainScriptsRaw, ), ) } @@ -418,20 +507,22 @@ func decodeIncomingSnapshotWithLimits(raw []byte, limits ReceiveLimits) (*IncomingSnapshot, error) { var ( - version uint64 - sessionBytes []byte - phaseBytes []byte - arkPSBT []byte - checkpointsRaw []byte - failReasonRaw []byte - recipientPkScript []byte - recipientEventID uint64 - ancestorPackages []byte - metadataAttempts uint64 - resolveAttempts uint64 - recipientsRaw []byte - assetTransferRaw []byte - completedIDsRaw []byte + version uint64 + sessionBytes []byte + phaseBytes []byte + arkPSBT []byte + checkpointsRaw []byte + failReasonRaw []byte + recipientPkScript []byte + recipientEventID uint64 + ancestorPackages []byte + metadataAttempts uint64 + resolveAttempts uint64 + recipientsRaw []byte + assetTransferRaw []byte + completedHintsRaw []byte + activeScriptHash []byte + plainScriptHashRaw []byte ) records := []tlv.Record{ @@ -478,7 +569,14 @@ func decodeIncomingSnapshotWithLimits(raw []byte, &assetTransferRaw, ), tlv.MakePrimitiveRecord( - incomingSnapshotCompletedEventIDsType, &completedIDsRaw, + incomingSnapshotCompletedHintsType, &completedHintsRaw, + ), + tlv.MakePrimitiveRecord( + incomingSnapshotActiveScriptHashType, &activeScriptHash, + ), + tlv.MakePrimitiveRecord( + incomingSnapshotPlainScriptHashesType, + &plainScriptHashRaw, ), } @@ -537,12 +635,30 @@ func decodeIncomingSnapshotWithLimits(raw []byte, decodedAssetTransfer = &transfer } - completedEventIDs, err := decodeUint64List( - completedIDsRaw, maxCompletedIncomingEventIDs, + completedHints, err := decodeIncomingHintKeys( + completedHintsRaw, maxCompletedIncomingEventIDs, ) if err != nil { return nil, fmt.Errorf("decode incoming snapshot completed "+ - "event ids: %w", err) + "hints: %w", err) + } + + var decodedActiveHash [sha256.Size]byte + if len(activeScriptHash) > 0 { + if len(activeScriptHash) != sha256.Size { + return nil, fmt.Errorf("incoming snapshot active "+ + "script hash must be %d bytes, got %d", + sha256.Size, len(activeScriptHash)) + } + copy(decodedActiveHash[:], activeScriptHash) + } + + plainScripts, err := decodeScriptHashes( + plainScriptHashRaw, maxCompletedIncomingEventIDs, + ) + if err != nil { + return nil, fmt.Errorf("decode incoming snapshot plain script "+ + "hashes: %w", err) } decodedVersion, err := decodeUint64ToUint8( @@ -567,40 +683,87 @@ func decodeIncomingSnapshotWithLimits(raw []byte, RecipientPkScript: append( []byte(nil), recipientPkScript..., ), - RecipientEventID: recipientEventID, - CompletedEventIDs: completedEventIDs, - MetadataAttempts: uint32(metadataAttempts), - ResolveAttempts: uint32(resolveAttempts), + RecipientEventID: recipientEventID, + ActiveScriptHash: decodedActiveHash, + CompletedHints: completedHints, + MaterializedPlainScripts: plainScripts, + MetadataAttempts: uint32(metadataAttempts), + ResolveAttempts: uint32(resolveAttempts), }, nil } -// encodeUint64List encodes a slice of uint64 values as big-endian 8-byte words. -func encodeUint64List(ids []uint64) []byte { - out := make([]byte, len(ids)*8) - for i, id := range ids { - binary.BigEndian.PutUint64(out[i*8:(i+1)*8], id) +const incomingHintKeySize = sha256.Size + 8 + +// encodeIncomingHintKeys encodes per-script hint keys as fixed 40-byte entries +// (32-byte ScriptHash || 8-byte big-endian EventID). +func encodeIncomingHintKeys(hints []IncomingHintKey) []byte { + out := make([]byte, len(hints)*incomingHintKeySize) + for i, h := range hints { + off := i * incomingHintKeySize + copy(out[off:off+sha256.Size], h.ScriptHash[:]) + binary.BigEndian.PutUint64( + out[off+sha256.Size:off+incomingHintKeySize], h.EventID, + ) + } + + return out +} + +// decodeIncomingHintKeys decodes fixed 40-byte hint-key entries. +func decodeIncomingHintKeys(raw []byte, + maxCount int) ([]IncomingHintKey, error) { + + if len(raw) == 0 { + return nil, nil + } + if len(raw)%incomingHintKeySize != 0 { + return nil, fmt.Errorf("byte length %d is not a multiple of %d", + len(raw), incomingHintKeySize) + } + count := len(raw) / incomingHintKeySize + if maxCount > 0 && count > maxCount { + return nil, fmt.Errorf("count %d exceeds limit %d", count, + maxCount) + } + out := make([]IncomingHintKey, count) + for i := range count { + off := i * incomingHintKeySize + copy(out[i].ScriptHash[:], raw[off:off+sha256.Size]) + out[i].EventID = binary.BigEndian.Uint64( + raw[off+sha256.Size : off+incomingHintKeySize], + ) + } + + return out, nil +} + +// encodeScriptHashes encodes SHA-256 script hashes as contiguous 32-byte words. +func encodeScriptHashes(hashes [][sha256.Size]byte) []byte { + out := make([]byte, len(hashes)*sha256.Size) + for i, h := range hashes { + copy(out[i*sha256.Size:(i+1)*sha256.Size], h[:]) } return out } -// decodeUint64List decodes big-endian 8-byte words into a bounded uint64 slice. -func decodeUint64List(raw []byte, maxCount int) ([]uint64, error) { +// decodeScriptHashes decodes contiguous 32-byte SHA-256 script hashes. +func decodeScriptHashes(raw []byte, maxCount int) ([][sha256.Size]byte, error) { if len(raw) == 0 { return nil, nil } - if len(raw)%8 != 0 { - return nil, fmt.Errorf("byte length %d is not a multiple of 8", - len(raw)) + if len(raw)%sha256.Size != 0 { + return nil, fmt.Errorf("byte length %d is not a multiple of %d", + len(raw), sha256.Size) } - count := len(raw) / 8 + count := len(raw) / sha256.Size if maxCount > 0 && count > maxCount { return nil, fmt.Errorf("count %d exceeds limit %d", count, maxCount) } - out := make([]uint64, count) + out := make([][sha256.Size]byte, count) for i := range count { - out[i] = binary.BigEndian.Uint64(raw[i*8 : (i+1)*8]) + copy(out[i][:], raw[i*sha256.Size:(i+1)*sha256.Size]) } return out, nil diff --git a/oor/receive_states.go b/oor/receive_states.go index d9b72ed8a..471d71e9e 100644 --- a/oor/receive_states.go +++ b/oor/receive_states.go @@ -1,6 +1,8 @@ package oor import ( + "crypto/sha256" + "github.com/btcsuite/btcd/psbt/v2" "github.com/lightninglabs/wavelength/baselib/protofsm" oortx "github.com/lightninglabs/wavelength/lib/tx/oor" @@ -17,12 +19,39 @@ type ReceiveState interface { receiveStateSealed() } -// maxCompletedIncomingEventIDs bounds how many distinct recipient event IDs a +// maxCompletedIncomingEventIDs bounds how many distinct recipient hints a // single incoming OOR session will track and replay across sequential passes // (for example, a sender receiving both an asset change output and a Bitcoin // carrier-return output in the same OOR transfer). const maxCompletedIncomingEventIDs = 64 +// IncomingHintKey uniquely identifies one per-script recipient event hint. +// Operators number recipient_event_id per pk_script (so fresh scripts all +// start at 1), meaning event ID alone collides across distinct scripts in the +// same OOR session. +type IncomingHintKey struct { + ScriptHash [sha256.Size]byte + EventID uint64 +} + +// NewIncomingHintKey constructs a hint key from a recipient routing pkScript +// and its per-script event ID. Returns the zero key if either is missing. +func NewIncomingHintKey(pkScript []byte, eventID uint64) IncomingHintKey { + if len(pkScript) == 0 || eventID == 0 { + return IncomingHintKey{} + } + + return IncomingHintKey{ + ScriptHash: sha256.Sum256(pkScript), + EventID: eventID, + } +} + +// IsZero reports whether the hint key is unset. +func (k IncomingHintKey) IsZero() bool { + return k.EventID == 0 && k.ScriptHash == ([sha256.Size]byte{}) +} + // ReceiveResolving indicates the client durably recorded a lightweight // incoming-transfer hint and still needs to fetch the full Ark/checkpoint // package outside the live durable actor transaction. @@ -33,9 +62,13 @@ type ReceiveResolving struct { RecipientEventID uint64 - // CompletedEventIDs carries recipient event IDs already completed by - // earlier receive passes for this session so they remain idempotent. - CompletedEventIDs []uint64 + // CompletedHints carries per-script hints already completed by earlier + // receive passes for this session so they remain idempotent. + CompletedHints []IncomingHintKey + + // MaterializedPlainScripts carries SHA-256 hashes of non-asset output + // scripts already materialized by earlier passes for this session. + MaterializedPlainScripts [][sha256.Size]byte // ResolveAttempts counts how many times the phase-1 hint resolution has // been re-issued for this session without a response. It drives the @@ -44,6 +77,15 @@ type ReceiveResolving struct { ResolveAttempts uint32 } +// HintKey returns the per-script hint key currently being resolved. +func (s *ReceiveResolving) HintKey() IncomingHintKey { + if s == nil { + return IncomingHintKey{} + } + + return NewIncomingHintKey(s.RecipientPkScript, s.RecipientEventID) +} + // String returns a human-readable representation of ReceiveResolving. func (s *ReceiveResolving) String() string { return "ReceiveResolving" @@ -93,13 +135,17 @@ type ReceiveNotified struct { // verifies and persists the Ark package on the received VTXO. TaprootAssetTransfer *oortx.TaprootAssetTransfer - // RecipientEventID identifies the recipient event currently being + // ActiveHint identifies the per-script recipient event currently being // processed by this receive pass (zero for direct/legacy transitions). - RecipientEventID uint64 + ActiveHint IncomingHintKey - // CompletedEventIDs carries recipient event IDs already completed by - // earlier receive passes for this session. - CompletedEventIDs []uint64 + // CompletedHints carries per-script hints already completed by earlier + // receive passes for this session. + CompletedHints []IncomingHintKey + + // MaterializedPlainScripts carries SHA-256 hashes of non-asset output + // scripts already materialized by earlier passes for this session. + MaterializedPlainScripts [][sha256.Size]byte // MetadataAttempts counts how many times the authoritative metadata // resolution has failed retryably for this session. It drives the @@ -126,13 +172,17 @@ func (s *ReceiveNotified) receiveStateSealed() {} type ReceiveAwaitingAck struct { SessionID SessionID - // RecipientEventID identifies the recipient event whose outputs were - // just materialized. - RecipientEventID uint64 + // ActiveHint identifies the per-script recipient event whose outputs + // were just materialized. + ActiveHint IncomingHintKey - // CompletedEventIDs carries recipient event IDs already completed by - // earlier receive passes for this session. - CompletedEventIDs []uint64 + // CompletedHints carries per-script hints already completed by earlier + // receive passes for this session. + CompletedHints []IncomingHintKey + + // MaterializedPlainScripts carries SHA-256 hashes of non-asset output + // scripts materialized on this session so far. + MaterializedPlainScripts [][sha256.Size]byte } // String returns a human-readable representation of ReceiveAwaitingAck. @@ -150,20 +200,39 @@ func (s *ReceiveAwaitingAck) receiveStateSealed() {} // ReceiveCompleted is the terminal success state for an incoming transfer. type ReceiveCompleted struct { - // CompletedEventIDs records the recipient event IDs processed by this - // session so distinct owned outputs (such as asset change plus Bitcoin - // carrier return) can each run a receive pass while duplicate pushes - // stay idempotent. - CompletedEventIDs []uint64 + // CompletedHints records the per-script recipient hints processed by + // this session so distinct owned asset outputs can each run a receive + // pass while duplicate pushes stay idempotent. + CompletedHints []IncomingHintKey + + // MaterializedPlainScripts records SHA-256 hashes of plain (non-asset) + // scripts already materialized on this session so follow-up hints for + // plain Bitcoin outputs stay idempotent no-ops without reopening. + MaterializedPlainScripts [][sha256.Size]byte +} + +// HasHint reports whether key has already completed on this session. +func (s *ReceiveCompleted) HasHint(key IncomingHintKey) bool { + if s == nil || key.IsZero() { + return false + } + for _, h := range s.CompletedHints { + if h == key { + return true + } + } + + return false } -// HasEventID reports whether eventID has already completed on this session. -func (s *ReceiveCompleted) HasEventID(eventID uint64) bool { - if s == nil || eventID == 0 { +// HasPlainScript reports whether a non-asset output paying to scriptHash was +// already materialized by a prior pass on this session. +func (s *ReceiveCompleted) HasPlainScript(scriptHash [sha256.Size]byte) bool { + if s == nil || scriptHash == ([sha256.Size]byte{}) { return false } - for _, id := range s.CompletedEventIDs { - if id == eventID { + for _, h := range s.MaterializedPlainScripts { + if h == scriptHash { return true } } @@ -184,36 +253,95 @@ func (s *ReceiveCompleted) IsTerminal() bool { // receiveStateSealed marks ReceiveCompleted as implementing ReceiveState. func (s *ReceiveCompleted) receiveStateSealed() {} -// appendCompletedEventID returns a defensive copy of existing with eventID -// appended when eventID is non-zero and not already present. -func appendCompletedEventID(existing []uint64, eventID uint64) []uint64 { - out := append([]uint64(nil), existing...) - if eventID == 0 { +// appendCompletedHint returns a defensive copy of existing with key appended +// when key is non-zero and not already present. +func appendCompletedHint(existing []IncomingHintKey, + key IncomingHintKey) []IncomingHintKey { + + out := append([]IncomingHintKey(nil), existing...) + if key.IsZero() { + return out + } + for _, h := range out { + if h == key { + return out + } + } + + return append(out, key) +} + +// appendUniqueScriptHash returns a defensive copy of existing with h appended +// when h is non-zero, not already present, and under the per-session cap. +func appendUniqueScriptHash(existing [][sha256.Size]byte, + h [sha256.Size]byte) [][sha256.Size]byte { + + out := append([][sha256.Size]byte(nil), existing...) + if h == ([sha256.Size]byte{}) { return out } - for _, id := range out { - if id == eventID { + for _, cur := range out { + if cur == h { return out } } + if len(out) >= maxCompletedIncomingEventIDs { + return out + } - return append(out, eventID) + return append(out, h) } -// activeIncomingEventID returns the recipient event ID being processed by a -// non-terminal incoming receive state, or zero when unset. -func activeIncomingEventID(state SessionState) uint64 { +// activeIncomingHint returns the per-script hint being processed by a +// non-terminal incoming receive state, or the zero key when unset. +func activeIncomingHint(state SessionState) IncomingHintKey { switch s := state.(type) { case *ReceiveResolving: - return s.RecipientEventID + return s.HintKey() case *ReceiveNotified: - return s.RecipientEventID + return s.ActiveHint case *ReceiveAwaitingAck: - return s.RecipientEventID + return s.ActiveHint default: - return 0 + return IncomingHintKey{} + } +} + +// priorCompletedReceiveState returns the ReceiveCompleted state to fall back +// to if a follow-up receive pass fails after an earlier pass already +// succeeded, or nil when this is the session's first pass. +func priorCompletedReceiveState(state SessionState) *ReceiveCompleted { + var ( + hints []IncomingHintKey + scripts [][sha256.Size]byte + ) + switch s := state.(type) { + case *ReceiveResolving: + hints = s.CompletedHints + scripts = s.MaterializedPlainScripts + + case *ReceiveNotified: + hints = s.CompletedHints + scripts = s.MaterializedPlainScripts + + case *ReceiveAwaitingAck: + hints = s.CompletedHints + scripts = s.MaterializedPlainScripts + + default: + return nil + } + if len(hints) == 0 { + return nil + } + + return &ReceiveCompleted{ + CompletedHints: append([]IncomingHintKey(nil), hints...), + MaterializedPlainScripts: append( + [][sha256.Size]byte(nil), scripts..., + ), } } diff --git a/oor/receive_transitions.go b/oor/receive_transitions.go index 2fc1a4cca..54542cb99 100644 --- a/oor/receive_transitions.go +++ b/oor/receive_transitions.go @@ -1,7 +1,9 @@ package oor import ( + "bytes" "context" + "crypto/sha256" "fmt" "log/slog" "time" @@ -55,6 +57,25 @@ func unexpectedReceiveEvent(state ReceiveState, event Event) *StateTransition { } } +// receiveFailTransition returns the terminal transition for a receive failure. +// When an earlier pass on this session already completed, it preserves the +// prior ReceiveCompleted state instead of overwriting Completed with Failed. +func receiveFailTransition(state SessionState, reason string) *StateTransition { + if prior := priorCompletedReceiveState(state); prior != nil { + return &StateTransition{ + NextState: prior, + NewEvents: fn.None[EmittedEvent](), + } + } + + return &StateTransition{ + NextState: &Failed{ + Reason: reason, + }, + NewEvents: fn.None[EmittedEvent](), + } +} + // handleReceiveOutboxError derives the receive-FSM retry/fail transition for // one outbox execution error. func handleReceiveOutboxError(state ReceiveState, @@ -65,12 +86,7 @@ func handleReceiveOutboxError(state ReceiveState, } if !evt.Retryable { - return &StateTransition{ - NextState: &Failed{ - Reason: evt.ErrorReason, - }, - NewEvents: fn.None[EmittedEvent](), - }, nil + return receiveFailTransition(state, evt.ErrorReason), nil } // The notified state retries the authoritative metadata resolution. @@ -109,14 +125,11 @@ func notifiedGiveUp(state *ReceiveNotified, reason string) (*ReceiveNotified, *StateTransition) { if state.MetadataAttempts >= maxMetadataRetries { - return nil, &StateTransition{ - NextState: &Failed{ - Reason: fmt.Sprintf("incoming metadata "+ - "unresolved after %d retries: %s", - maxMetadataRetries, reason), - }, - NewEvents: fn.None[EmittedEvent](), - } + return nil, receiveFailTransition( + state, fmt.Sprintf("incoming metadata unresolved "+ + "after %d retries: %s", maxMetadataRetries, + reason), + ) } next := *state @@ -245,8 +258,8 @@ func waitsOnGiveUpTimer(state SessionState) bool { // transitionIncomingTransfer validates and applies a fully resolved incoming // transfer event, moving the receive FSM into the notified/materialize phase. func transitionIncomingTransfer(evt *IncomingTransferEvent, - recipientEventID uint64, - completedEventIDs []uint64) (*StateTransition, error) { + activeHint IncomingHintKey, completedHints []IncomingHintKey, + plainScripts [][sha256.Size]byte) (*StateTransition, error) { if evt.ArkPSBT == nil || evt.ArkPSBT.UnsignedTx == nil { return nil, fmt.Errorf("ark psbt must be provided") @@ -285,9 +298,12 @@ func transitionIncomingTransfer(evt *IncomingTransferEvent, AncestorPackages: evt.AncestorPackages, Recipients: recipients, TaprootAssetTransfer: evt.TaprootAssetTransfer.Clone(), - RecipientEventID: recipientEventID, - CompletedEventIDs: append( - []uint64(nil), completedEventIDs..., + ActiveHint: activeHint, + CompletedHints: append( + []IncomingHintKey(nil), completedHints..., + ), + MaterializedPlainScripts: append( + [][sha256.Size]byte(nil), plainScripts..., ), } @@ -323,7 +339,9 @@ func (s *ReceiveIdle) ProcessEvent(ctx context.Context, event Event, switch evt := event.(type) { case *IncomingTransferEvent: - return transitionIncomingTransfer(evt, 0, nil) + return transitionIncomingTransfer( + evt, IncomingHintKey{}, nil, nil, + ) case *FailEvent: return &StateTransition{ @@ -352,20 +370,30 @@ func (s *ReceiveResolving) ProcessEvent(ctx context.Context, event Event, switch evt := event.(type) { case *IncomingTransferEvent: + // Ignore stale phase-1 responses from a different script or + // event pass on this same session. + if evt.RecipientEventID > 0 && s.RecipientEventID > 0 && + evt.RecipientEventID != s.RecipientEventID { + return unexpectedReceiveEvent(s, event), nil + } + if len(evt.RecipientPkScript) > 0 && + len(s.RecipientPkScript) > 0 && + !bytes.Equal( + evt.RecipientPkScript, s.RecipientPkScript, + ) { + return unexpectedReceiveEvent(s, event), nil + } + return transitionIncomingTransfer( - evt, s.RecipientEventID, s.CompletedEventIDs, + evt, s.HintKey(), s.CompletedHints, + s.MaterializedPlainScripts, ) case *RetryDueEvent: return handleResolveRetry(s), nil case *FailEvent: - return &StateTransition{ - NextState: &Failed{ - Reason: evt.Reason, - }, - NewEvents: fn.None[EmittedEvent](), - }, nil + return receiveFailTransition(s, evt.Reason), nil default: logger(ctx).WarnS(ctx, "Unexpected event in receive FSM", @@ -388,14 +416,11 @@ func handleResolveRetry(state *ReceiveResolving) *StateTransition { // persisted counter before incrementing so a corrupted snapshot at // math.MaxUint32 cannot wrap past the limit and bypass the give-up. if state.ResolveAttempts >= maxResolveRetries { - return &StateTransition{ - NextState: &Failed{ - Reason: fmt.Sprintf("incoming transfer hint "+ - "unresolved after %d retries", - maxResolveRetries), - }, - NewEvents: fn.None[EmittedEvent](), - } + return receiveFailTransition( + state, fmt.Sprintf("incoming transfer hint "+ + "unresolved after %d retries", + maxResolveRetries), + ) } attempts := state.ResolveAttempts + 1 @@ -532,16 +557,35 @@ func (s *ReceiveNotified) ProcessEvent(ctx context.Context, event Event, // The application signals it has processed the // notification. Wallet state has been updated // (materialization complete), so we can now ack to the - // server. - _ = evt + // server. Record plain (non-asset) script hashes materialized + // in this pass so follow-up hints for those scripts remain + // idempotent no-ops without reopening the session. + plainScripts := append( + [][sha256.Size]byte(nil), s.MaterializedPlainScripts..., + ) + for _, h := range evt.MaterializedPlainScripts { + plainScripts = appendUniqueScriptHash(plainScripts, h) + } + for _, desc := range evt.MaterializedVTXOs { + if desc != nil && desc.TaprootAssetRoot == nil && + len(desc.PkScript) > 0 { + + plainScripts = appendUniqueScriptHash( + plainScripts, + sha256.Sum256(desc.PkScript), + ) + } + } return &StateTransition{ NextState: &ReceiveAwaitingAck{ - SessionID: s.SessionID, - RecipientEventID: s.RecipientEventID, - CompletedEventIDs: append( - []uint64(nil), s.CompletedEventIDs..., + SessionID: s.SessionID, + ActiveHint: s.ActiveHint, + CompletedHints: append( + []IncomingHintKey(nil), + s.CompletedHints..., ), + MaterializedPlainScripts: plainScripts, }, NewEvents: fn.Some(EmittedEvent{ Outbox: []OutboxEvent{ @@ -563,12 +607,7 @@ func (s *ReceiveNotified) ProcessEvent(ctx context.Context, event Event, return handleNotifiedTimerRetry(s), nil case *FailEvent: - return &StateTransition{ - NextState: &Failed{ - Reason: evt.Reason, - }, - NewEvents: fn.None[EmittedEvent](), - }, nil + return receiveFailTransition(s, evt.Reason), nil default: logger(ctx).WarnS(ctx, "Unexpected event in receive FSM", @@ -608,28 +647,22 @@ func (s *ReceiveAwaitingAck) ProcessEvent(ctx context.Context, event Event, return &StateTransition{ NextState: &ReceiveCompleted{ - CompletedEventIDs: appendCompletedEventID( - s.CompletedEventIDs, s.RecipientEventID, + CompletedHints: appendCompletedHint( + s.CompletedHints, s.ActiveHint, + ), + MaterializedPlainScripts: append( + [][sha256.Size]byte(nil), + s.MaterializedPlainScripts..., ), }, NewEvents: fn.None[EmittedEvent](), }, nil case *OutboxErrorEvent: - return &StateTransition{ - NextState: &Failed{ - Reason: evt.ErrorReason, - }, - NewEvents: fn.None[EmittedEvent](), - }, nil + return receiveFailTransition(s, evt.ErrorReason), nil case *FailEvent: - return &StateTransition{ - NextState: &Failed{ - Reason: evt.Reason, - }, - NewEvents: fn.None[EmittedEvent](), - }, nil + return receiveFailTransition(s, evt.Reason), nil default: logger(ctx).WarnS(ctx, "Unexpected event in receive FSM", diff --git a/oor/registry.go b/oor/registry.go index b7a6cd149..9f07e8442 100644 --- a/oor/registry.go +++ b/oor/registry.go @@ -322,7 +322,7 @@ func NewOORRegistryActor(cfg OORRegistryConfig) (*OORRegistryActor, error) { map[SessionID]clientdb.OORSessionDirection, ), incoming: make(map[SessionID]struct{}), - activeIncomingEvent: make(map[SessionID]uint64), + activeIncomingHint: make(map[SessionID]IncomingHintKey), pendingOutgoingKeys: make(map[string]SessionID), parkedSelfHints: make( map[SessionID][]*ResolveIncomingTransferRequest, @@ -432,11 +432,11 @@ type oorRegistryBehavior struct { spawnFunc func(SessionID, clientdb.OORSessionDirection) ( *OORSessionActor, error) - // activeIncomingEvent tracks the RecipientEventID currently being - // driven by each resident incoming session child, so a distinct - // recipient event for the same session can be parked and immediately + // activeIncomingHint tracks the (pkScript, RecipientEventID) hint + // currently being driven by each resident incoming session child, so a + // distinct hint for the same session can be parked and immediately // redriven when the active pass completes and reaps. - activeIncomingEvent map[SessionID]uint64 + activeIncomingHint map[SessionID]IncomingHintKey // parkedSelfHints holds incoming hints deferred because their session // is still active as outgoing or currently resolving another owned @@ -1249,14 +1249,18 @@ func (r *oorRegistryBehavior) handleResolveIncoming(ctx context.Context, return fn.Err[ActorResp](err) } + hintKey := NewIncomingHintKey( + req.RecipientPkScript, req.RecipientEventID, + ) + _, existed := r.active[req.SessionID] if existed && r.activeDirs[req.SessionID] == clientdb.OORSessionDirectionIncoming && - req.RecipientEventID > 0 { + !hintKey.IsZero() { - activeID := r.activeIncomingEvent[req.SessionID] - if activeID > 0 && activeID != req.RecipientEventID { + activeHint := r.activeIncomingHint[req.SessionID] + if !activeHint.IsZero() && activeHint != hintKey { r.parkSelfHint(req) return fn.Err[ActorResp]( @@ -1273,7 +1277,7 @@ func (r *oorRegistryBehavior) handleResolveIncoming(ctx context.Context, // Remove any parked copy of this specific hint now that it is being // admitted, while preserving any other distinct parked hints for the // same session. - r.unparkSelfHint(req.SessionID, req.RecipientEventID) + r.unparkSelfHint(req.SessionID, hintKey) // Bound the number of resident incoming children one daemon admits at // once. A new admission past the cap is rejected before any child is @@ -1326,14 +1330,13 @@ func (r *oorRegistryBehavior) handleResolveIncoming(ctx context.Context, } if !existed { - if req.RecipientEventID > 0 { - if r.activeIncomingEvent == nil { - r.activeIncomingEvent = make( - map[SessionID]uint64, + if !hintKey.IsZero() { + if r.activeIncomingHint == nil { + r.activeIncomingHint = make( + map[SessionID]IncomingHintKey, ) } - r.activeIncomingEvent[req.SessionID] = req. - RecipientEventID + r.activeIncomingHint[req.SessionID] = hintKey } r.logger(ctx).InfoS(ctx, "Admitting incoming OOR session", slog.String("session_id", req.SessionID.String()), @@ -1432,8 +1435,14 @@ func (r *oorRegistryBehavior) parkSelfHint( } queued := r.parkedSelfHints[req.SessionID] + reqKey := NewIncomingHintKey( + req.RecipientPkScript, req.RecipientEventID, + ) for i := range queued { - if queued[i].RecipientEventID == req.RecipientEventID { + curKey := NewIncomingHintKey( + queued[i].RecipientPkScript, queued[i].RecipientEventID, + ) + if curKey == reqKey { queued[i] = req return @@ -1446,10 +1455,10 @@ func (r *oorRegistryBehavior) parkSelfHint( r.parkedSelfHints[req.SessionID] = append(queued, req) } -// unparkSelfHint removes one parked hint matching recipientEventID from -// sessionID's queue, leaving any other distinct parked hints intact. +// unparkSelfHint removes one parked hint matching hintKey from sessionID's +// queue, leaving any other distinct parked hints intact. func (r *oorRegistryBehavior) unparkSelfHint(sessionID SessionID, - recipientEventID uint64) { + hintKey IncomingHintKey) { queued := r.parkedSelfHints[sessionID] if len(queued) == 0 { @@ -1458,7 +1467,10 @@ func (r *oorRegistryBehavior) unparkSelfHint(sessionID SessionID, kept := queued[:0] for _, h := range queued { - if h.RecipientEventID == recipientEventID { + curKey := NewIncomingHintKey( + h.RecipientPkScript, h.RecipientEventID, + ) + if curKey == hintKey { continue } kept = append(kept, h) @@ -1952,7 +1964,7 @@ func (r *oorRegistryBehavior) dropChild(sessionID SessionID, delete(r.active, sessionID) delete(r.activeDirs, sessionID) delete(r.incoming, sessionID) - delete(r.activeIncomingEvent, sessionID) + delete(r.activeIncomingHint, sessionID) for key, pendingID := range r.pendingOutgoingKeys { if pendingID == sessionID { delete(r.pendingOutgoingKeys, key) @@ -2050,6 +2062,14 @@ func (r *oorRegistryBehavior) restoreNonTerminal(ctx context.Context) error { err) } + if rows[i].Direction == clientdb.OORSessionDirectionIncoming && + len(rows[i].SnapshotData) > 0 { + + r.restoreActiveIncomingHint( + sessionID, rows[i].SnapshotData, + ) + } + // Re-emit the outbox implied by the restored state. The Tell // lands in the child's durable mailbox, so the resume itself // survives a crash between this loop and the child's turn. @@ -2082,3 +2102,27 @@ func (r *oorRegistryBehavior) restoreNonTerminal(ctx context.Context) error { return nil } + +// restoreActiveIncomingHint reconstructs the registry's in-flight hint entry +// from a restored incoming session snapshot so concurrent hints for a busy +// session are parked instead of racing after restart. +func (r *oorRegistryBehavior) restoreActiveIncomingHint(sessionID SessionID, + snapshotData []byte) { + + snap, err := decodeIncomingSnapshotWithLimits( + snapshotData, r.cfg.Limits, + ) + if err != nil { + return + } + + activeHint := snap.ActiveHintKey() + if activeHint.IsZero() { + return + } + + if r.activeIncomingHint == nil { + r.activeIncomingHint = make(map[SessionID]IncomingHintKey) + } + r.activeIncomingHint[sessionID] = activeHint +} diff --git a/oor/session_actor_handlers.go b/oor/session_actor_handlers.go index cb7aafd30..31473b9a1 100644 --- a/oor/session_actor_handlers.go +++ b/oor/session_actor_handlers.go @@ -2,6 +2,7 @@ package oor import ( "context" + "crypto/sha256" "database/sql" "errors" "fmt" @@ -577,14 +578,23 @@ func (b *sessionBehavior) handleResolveIncomingTransfer(ctx context.Context, } // Handle hints targeting an already-loaded incoming session: - // - While a pass is in flight for another recipient event of the - // same session, postpone so the new event runs once the current - // pass completes (rather than dropping it as a duplicate). - // - Once completed, allow a distinct new recipient event ID (such as - // asset change + Bitcoin carrier return in one transfer) to start a - // fresh ReceiveResolving pass while keeping previously completed - // event IDs and legacy completed snapshots idempotent. - var priorCompleted []uint64 + // - While a pass is in flight for another per-script recipient hint + // of the same session, postpone so the new hint runs once the + // current pass completes (rather than dropping it as a duplicate). + // - Once completed, allow a distinct new (pkScript, eventID) hint + // whose plain script was not already materialized (such as asset + // change + Bitcoin carrier return in one transfer) to start a fresh + // ReceiveResolving pass while keeping previously completed hints, + // already-materialized plain Bitcoin scripts, and legacy completed + // snapshots idempotent. + hintKey := NewIncomingHintKey( + req.RecipientPkScript, req.RecipientEventID, + ) + + var ( + priorCompleted []IncomingHintKey + priorPlainScripts [][sha256.Size]byte + ) if b.loaded && b.fsm != nil { curState, err := b.fsm.CurrentState() if err != nil { @@ -593,9 +603,9 @@ func (b *sessionBehavior) handleResolveIncomingTransfer(ctx context.Context, completed, isCompleted := curState.(*ReceiveCompleted) if !isCompleted { - activeID := activeIncomingEventID(curState) - if req.RecipientEventID > 0 && activeID > 0 && - activeID != req.RecipientEventID { + activeHint := activeIncomingHint(curState) + if !hintKey.IsZero() && !activeHint.IsZero() && + activeHint != hintKey { postpone := actor.Postpone( selfHintRedeliveryBackoff, @@ -604,24 +614,29 @@ func (b *sessionBehavior) handleResolveIncomingTransfer(ctx context.Context, return fn.Err[ActorResp]( fmt.Errorf("incoming session %s busy "+ "with event %d: %w", - req.SessionID, activeID, - postpone), + req.SessionID, + activeHint.EventID, postpone), ) } return fn.Ok[ActorResp](&DriveEventResponse{}) } - if req.RecipientEventID == 0 || - len(completed.CompletedEventIDs) == 0 || - completed.HasEventID(req.RecipientEventID) || - len(completed.CompletedEventIDs) >= + if hintKey.IsZero() || + len(completed.CompletedHints) == 0 || + completed.HasHint(hintKey) || + completed.HasPlainScript(hintKey.ScriptHash) || + len(completed.CompletedHints) >= maxCompletedIncomingEventIDs { return fn.Ok[ActorResp](&DriveEventResponse{}) } priorCompleted = append( - []uint64(nil), completed.CompletedEventIDs..., + []IncomingHintKey(nil), completed.CompletedHints..., + ) + priorPlainScripts = append( + [][sha256.Size]byte(nil), + completed.MaterializedPlainScripts..., ) } @@ -631,8 +646,9 @@ func (b *sessionBehavior) handleResolveIncomingTransfer(ctx context.Context, RecipientPkScript: append( []byte(nil), req.RecipientPkScript..., ), - RecipientEventID: req.RecipientEventID, - CompletedEventIDs: priorCompleted, + RecipientEventID: req.RecipientEventID, + CompletedHints: priorCompleted, + MaterializedPlainScripts: priorPlainScripts, }, b.envConfig(), ) if err != nil { From 2b7278481cd1be20c4abe007d2fd7d7227bf2efb Mon Sep 17 00:00:00 2001 From: Dario Anongba Varela Date: Fri, 27 Nov 2026 19:10:07 +0100 Subject: [PATCH 13/15] waved: harden SendAssetOOR validation, replay, and recovery Validate policy_template destinations with arkscript.ValidatePolicy, parse oor_carrier_pubkey leniently during operator-terms bootstrap, and build checkpoint owner leaves under current terms.PubKey so asset VTXOs remain spendable across operator key rotations. Consolidate SendAssetOOR lock cleanup into a single detached-context defer and check local carrier floor preconditions before leasing a carrier float. Bind keyed asset OOR attempts to v2 OutgoingAssetReplay identity, reject cross-type Bitcoin/asset key reuse with AlreadyExists, and return stored summary figures without emitting duplicate metrics. Wire incomingAssetVerifier as nil when Taproot Assets are disabled, unwrap proof-verifier errors so transient chain outages retry with bounded backoff, and skip unverifiable asset events during wallet recovery instead of aborting the scan. --- waved/AGENTS.md | 36 ++- waved/CLAUDE.md | 36 ++- waved/asset_oor.go | 332 ++++++++++++++++------- waved/asset_oor_test.go | 405 +++++++++++++++++++++++++++++ waved/oor_diagnostics.go | 2 +- waved/operator_negotiation.go | 12 +- waved/operator_negotiation_test.go | 8 +- waved/rpc_server.go | 5 + waved/server.go | 2 +- waved/wallet_recovery.go | 23 +- 10 files changed, 730 insertions(+), 131 deletions(-) diff --git a/waved/AGENTS.md b/waved/AGENTS.md index 49c487650..37d969cac 100644 --- a/waved/AGENTS.md +++ b/waved/AGENTS.md @@ -774,17 +774,25 @@ background-window guide for legacy-reference and device acceptance limits. ## Asset OOR transfers -`RPCServer.SendAssetOOR` (daemon RPC only, guarded by `entityOOR:write`) sends -Taproot Assets out-of-round without exposing a CLI subcommand. It validates the -request and operator terms (asset admission + `OORCarrierPubKey`), reserves up -to `tapassets.MaxOORAssetInputs` live asset VTXOs via -`SelectAndLockAssetVTXOsRequest`, leases an operator carrier float via -authenticated `LeaseOORCarrier`, plans carrier allocation (`oortx.PlanAssetCarriers`), -builds the asset transitions on `s.assetClient` (`tapassets.BuildOORTransfer`) -against lineage-scoped input proof verifiers, attaches composed tapleaf scripts -onto `oor.PreparedSubmitPackage`, and hands it to `OORRegistryActor`. Incoming -asset OOR outputs resolve their signing key via uncomposed `RoutingPkScript()` -(`ResolveOwnedReceiveScriptKey` and `ScopedVTXOQueryBuilder`), verify the -sealed Ark package outside the actor DB transaction (`Server.verifyIncomingAssetOOR` -→ `tapassets.VTXOVerifier.VerifyOORAssetVTXO`), and persist `TaprootAssetSealedPackage` -on the materialized `vtxo.Descriptor` for unilateral claims and respends. +`RPCServer.SendAssetOOR` (daemon RPC guarded by `entityOOR:write`; no top-level +user CLI command, though reachable via the generated devrpc registry +`wavecli dev daemon send-asset-oor`) sends Taproot Assets out-of-round. It +validates the request, operator terms (asset admission + `OORCarrierPubKey`), +and destination policy (`arkscript.ValidatePolicy`), checks idempotency against +canonical v2 `oor.OutgoingAssetReplay` identity, reserves up to +`tapassets.MaxOORAssetInputs` live asset VTXOs via +`SelectAndLockAssetVTXOsRequest` (with a single deferred detached-context +unlock on failure), validates local carrier preconditions before leasing an +operator carrier float via authenticated `LeaseOORCarrier`, plans carrier +allocation (`oortx.PlanAssetCarriers`), builds the asset transitions on +`s.assetClient` (`tapassets.BuildOORTransfer`) against lineage-scoped input +proof verifiers and current-operator checkpoint leaves, attaches composed +tapleaf scripts onto `oor.PreparedSubmitPackage`, and hands it to +`OORRegistryActor`. Incoming asset OOR outputs resolve their signing key via +uncomposed `RoutingPkScript()` (`ResolveOwnedReceiveScriptKey` and +`ScopedVTXOQueryBuilder`), verify the sealed Ark package synchronously outside +the actor DB write transaction (`Server.incomingAssetVerifier` → +`tapassets.VTXOVerifier.VerifyOORAssetVTXO`, wired as `nil` when assets are +disabled so sibling Bitcoin outputs remain unaffected), and persist +`TaprootAssetSealedPackage` on the materialized `vtxo.Descriptor` for +unilateral claims and respends. diff --git a/waved/CLAUDE.md b/waved/CLAUDE.md index 49c487650..37d969cac 100644 --- a/waved/CLAUDE.md +++ b/waved/CLAUDE.md @@ -774,17 +774,25 @@ background-window guide for legacy-reference and device acceptance limits. ## Asset OOR transfers -`RPCServer.SendAssetOOR` (daemon RPC only, guarded by `entityOOR:write`) sends -Taproot Assets out-of-round without exposing a CLI subcommand. It validates the -request and operator terms (asset admission + `OORCarrierPubKey`), reserves up -to `tapassets.MaxOORAssetInputs` live asset VTXOs via -`SelectAndLockAssetVTXOsRequest`, leases an operator carrier float via -authenticated `LeaseOORCarrier`, plans carrier allocation (`oortx.PlanAssetCarriers`), -builds the asset transitions on `s.assetClient` (`tapassets.BuildOORTransfer`) -against lineage-scoped input proof verifiers, attaches composed tapleaf scripts -onto `oor.PreparedSubmitPackage`, and hands it to `OORRegistryActor`. Incoming -asset OOR outputs resolve their signing key via uncomposed `RoutingPkScript()` -(`ResolveOwnedReceiveScriptKey` and `ScopedVTXOQueryBuilder`), verify the -sealed Ark package outside the actor DB transaction (`Server.verifyIncomingAssetOOR` -→ `tapassets.VTXOVerifier.VerifyOORAssetVTXO`), and persist `TaprootAssetSealedPackage` -on the materialized `vtxo.Descriptor` for unilateral claims and respends. +`RPCServer.SendAssetOOR` (daemon RPC guarded by `entityOOR:write`; no top-level +user CLI command, though reachable via the generated devrpc registry +`wavecli dev daemon send-asset-oor`) sends Taproot Assets out-of-round. It +validates the request, operator terms (asset admission + `OORCarrierPubKey`), +and destination policy (`arkscript.ValidatePolicy`), checks idempotency against +canonical v2 `oor.OutgoingAssetReplay` identity, reserves up to +`tapassets.MaxOORAssetInputs` live asset VTXOs via +`SelectAndLockAssetVTXOsRequest` (with a single deferred detached-context +unlock on failure), validates local carrier preconditions before leasing an +operator carrier float via authenticated `LeaseOORCarrier`, plans carrier +allocation (`oortx.PlanAssetCarriers`), builds the asset transitions on +`s.assetClient` (`tapassets.BuildOORTransfer`) against lineage-scoped input +proof verifiers and current-operator checkpoint leaves, attaches composed +tapleaf scripts onto `oor.PreparedSubmitPackage`, and hands it to +`OORRegistryActor`. Incoming asset OOR outputs resolve their signing key via +uncomposed `RoutingPkScript()` (`ResolveOwnedReceiveScriptKey` and +`ScopedVTXOQueryBuilder`), verify the sealed Ark package synchronously outside +the actor DB write transaction (`Server.incomingAssetVerifier` → +`tapassets.VTXOVerifier.VerifyOORAssetVTXO`, wired as `nil` when assets are +disabled so sibling Bitcoin outputs remain unaffected), and persist +`TaprootAssetSealedPackage` on the materialized `vtxo.Descriptor` for +unilateral claims and respends. diff --git a/waved/asset_oor.go b/waved/asset_oor.go index 91a0ea76a..ee83a40e0 100644 --- a/waved/asset_oor.go +++ b/waved/asset_oor.go @@ -10,6 +10,7 @@ import ( "fmt" "log/slog" "math" + "strings" "time" "github.com/btcsuite/btcd/btcec/v2" @@ -36,6 +37,18 @@ import ( "google.golang.org/grpc/status" ) +// incomingAssetVerifier returns the daemon's incoming asset OOR verifier when +// Taproot Assets support is enabled, and nil when assets are disabled so +// default Bitcoin-only daemons skip asset overlays without breaking sibling +// Bitcoin outputs. +func (s *Server) incomingAssetVerifier() oor.IncomingAssetVerifier { + if s == nil || s.assetClient == nil || s.embeddedAssets == nil { + return nil + } + + return s.verifyIncomingAssetOOR +} + // verifyIncomingAssetOOR verifies one incoming Taproot Asset OOR output // against the daemon's embedded asset engine and the output's authenticated // Bitcoin lineage and OOR package chain before materialization stores its @@ -61,6 +74,11 @@ func (s *Server) verifyIncomingAssetOOR(ctx context.Context, "asset package", oor.ErrInvalidIncomingAssetPackage) } + if err := validateAssetRefFilter(req.Recipient.Asset.Ref); err != nil { + return fmt.Errorf("%w: %w", oor.ErrInvalidIncomingAssetPackage, + err) + } + if err := trustAssetGroup( s.embeddedAssets, req.Recipient.Asset.Ref, ); err != nil { @@ -124,12 +142,17 @@ func (s *Server) verifyIncomingAssetOOR(ctx context.Context, }, ) if err != nil { - if ctx.Err() != nil { - return err + // Classify deterministic package, binding, and proof-structure + // failures as terminal so per-output isolation drops bad asset + // outputs immediately without stalling sibling Bitcoin outputs, + // while leaving chain/proof-backend errors unwrapped for + // ReceiveNotified's bounded exponential backoff. + if errors.Is(err, tapassets.ErrInvalidOORAssetPackage) { + return fmt.Errorf("%w: %w", + oor.ErrInvalidIncomingAssetPackage, err) } - return fmt.Errorf("%w: %w", oor.ErrInvalidIncomingAssetPackage, - err) + return err } return nil @@ -172,24 +195,6 @@ func (r *RPCServer) SendAssetOOR(ctx context.Context, "admission_deadline_unix_nanos must not be negative") } - if req.GetIdempotencyKey() != "" && !req.GetDryRun() { - replay, handled, err := r.replaySendAssetOORByIdempotencyKey( - ctx, req.GetIdempotencyKey(), - ) - if err != nil { - return nil, err - } - if handled { - return replay, nil - } - } - - if deadline := req.GetAdmissionDeadlineUnixNanos(); deadline > 0 && - !time.Now().Before(time.Unix(0, deadline)) { - return nil, status.Errorf(codes.FailedPrecondition, "OOR "+ - "admission deadline reached") - } - terms, err := r.server.fetchOperatorTerms(ctx) if err != nil { return nil, operatorTermsError( @@ -216,6 +221,25 @@ func (r *RPCServer) SendAssetOOR(ctx context.Context, return nil, err } + if req.GetIdempotencyKey() != "" && !req.GetDryRun() { + replay, handled, err := r.replaySendAssetOORByIdempotencyKey( + ctx, req.GetIdempotencyKey(), assetRef, req.GetAmount(), + recipientPolicy, + ) + if err != nil { + return nil, err + } + if handled { + return replay, nil + } + } + + if deadline := req.GetAdmissionDeadlineUnixNanos(); deadline > 0 && + !time.Now().Before(time.Unix(0, deadline)) { + return nil, status.Errorf(codes.FailedPrecondition, "OOR "+ + "admission deadline reached") + } + if req.GetDryRun() { return r.previewSendAssetOOR( ctx, assetRef, req.GetAmount(), outputFloor, @@ -236,12 +260,17 @@ func (r *RPCServer) SendAssetOOR(ctx context.Context, return nil, err } - selectResp, err := wRef.Ask(ctx, &wallet.SelectAndLockAssetVTXOsRequest{ + selectFuture := wRef.Ask(ctx, &wallet.SelectAndLockAssetVTXOsRequest{ AssetRef: assetRef, TargetAmount: req.GetAmount(), MaxInputs: tapassets.MaxOORAssetInputs, - }).Await(ctx).Unpack() + }) + selectResp, err := selectFuture.Await(ctx).Unpack() if err != nil { + if isAwaitContextError(ctx, err) { + r.cleanupCanceledAssetSelection(ctx, selectFuture) + } + return nil, status.Errorf(vtxoAdmissionCode(err), "asset VTXO "+ "selection failed: %v", err) } @@ -253,8 +282,22 @@ func (r *RPCServer) SendAssetOOR(ctx context.Context, } // Build a compatible SelectAndLockVTXOsResponse so error and canceled- - // await cleanup reuse the exact same unlock helpers as SendOOR. + // await cleanup reuse the exact same unlock helpers as SendOOR. Use a + // single deferred unlock on a detached bounded context so a cancelled + // request context can never leak locked VTXOs. lockedCompat := toCompatLockedVTXOs(lockedAsset) + handoffDone := false + defer func() { + if handoffDone { + return + } + unlockCtx, cancel := context.WithTimeout( + context.WithoutCancel(ctx), 5*time.Second, + ) + defer cancel() + + r.unlockSelectedVTXOsBestEffort(unlockCtx, lockedCompat) + }() policy := arkscript.CheckpointPolicy{ OperatorKey: terms.PubKey, @@ -264,19 +307,14 @@ func (r *RPCServer) SendAssetOOR(ctx context.Context, if err := trustAssetGroup( r.server.embeddedAssets, assetRef, ); err != nil { - - r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) - return nil, status.Errorf(codes.InvalidArgument, "trust asset "+ "group: %v", err) } builtInputs, err := r.loadAssetOORInputs( - ctx, assetRef, lockedAsset.SelectedVTXOs, + ctx, assetRef, terms.PubKey, lockedAsset.SelectedVTXOs, ) if err != nil { - r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) - return nil, err } @@ -286,12 +324,24 @@ func (r *RPCServer) SendAssetOOR(ctx context.Context, newAssetLeafCount = 2 } + // Validate local carrier preconditions before leasing an operator + // carrier float so local rejections never consume a float lease. + var roundCarrierTotal btcutil.Amount + for _, carrier := range builtInputs.carriers { + if carrier.Origin == oortx.CarrierOriginRound { + roundCarrierTotal += carrier.Amount + } + } + if roundCarrierTotal > 0 && roundCarrierTotal < outputFloor { + return nil, status.Errorf(codes.FailedPrecondition, "sender "+ + "Bitcoin change %d sat is below output floor %d sat", + roundCarrierTotal, outputFloor) + } + requiredLeaseSat, err := oortx.RequiredCarrierLeaseSat( newAssetLeafCount, outputFloor, ) if err != nil { - r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) - return nil, status.Errorf(codes.InvalidArgument, "required "+ "carrier lease: %v", err) } @@ -300,8 +350,6 @@ func (r *RPCServer) SendAssetOOR(ctx context.Context, ctx, requiredLeaseSat, req.GetIdempotencyKey(), ) if err != nil { - r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) - return nil, err } @@ -309,8 +357,6 @@ func (r *RPCServer) SendAssetOOR(ctx context.Context, terms.PubKey, terms.OORCarrierPubKey, ) if err != nil { - r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) - return nil, status.Errorf(codes.FailedPrecondition, "invalid "+ "operator carrier lease: %v", err) } @@ -322,8 +368,6 @@ func (r *RPCServer) SendAssetOOR(ctx context.Context, LeaseValue: lease.Value, }) if err != nil { - r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) - return nil, status.Errorf(codes.FailedPrecondition, "plan "+ "asset carriers: %v", err) } @@ -342,15 +386,11 @@ func (r *RPCServer) SendAssetOOR(ctx context.Context, }, ) if err != nil { - r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) - return nil, status.Errorf(codes.Internal, "build carrier "+ "float checkpoint: %v", err) } floatCPOut, err := floatCPArtifact.ToCheckpointOutput() if err != nil { - r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) - return nil, status.Errorf(codes.Internal, "build carrier "+ "float checkpoint output: %v", err) } @@ -366,8 +406,6 @@ func (r *RPCServer) SendAssetOOR(ctx context.Context, carrierPlan.NewAssetLeafCarrier, ) if err != nil { - r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) - return nil, err } assetOutputs = append(assetOutputs, tapassets.OORAssetOutput{ @@ -384,8 +422,6 @@ func (r *RPCServer) SendAssetOOR(ctx context.Context, carrierPlan.SenderChange, ) if err != nil { - r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) - return nil, err } plainOutputs = append(plainOutputs, btcChangeRecip) @@ -404,8 +440,6 @@ func (r *RPCServer) SendAssetOOR(ctx context.Context, req.GetIdempotencyKey(), ) if err != nil { - r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) - return nil, status.Errorf(codes.Internal, "derive asset "+ "transfer digest: %v", err) } @@ -425,8 +459,6 @@ func (r *RPCServer) SendAssetOOR(ctx context.Context, }, ) if err != nil { - r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) - code := codes.Internal if errors.Is(err, tapassets.ErrOORProofLimit) || errors.Is(err, tapassets.ErrOOROrderingUnresolved) { @@ -470,17 +502,12 @@ func (r *RPCServer) SendAssetOOR(ctx context.Context, }, } if err := prepared.AttachTapLeafScripts(allInputs); err != nil { - r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) - return nil, status.Errorf(codes.Internal, "attach asset OOR "+ "tapleaf scripts: %v", err) } if err := prepared.Validate( policy, allInputs, builtTransfer.Recipients, ); err != nil { - - r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) - return nil, status.Errorf(codes.Internal, "validate prepared "+ "asset OOR submit: %v", err) } @@ -490,21 +517,37 @@ func (r *RPCServer) SendAssetOOR(ctx context.Context, req.GetAmount(), ) if err != nil { - r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) - return nil, status.Errorf(codes.Internal, "locate asset OOR "+ "recipient output: %v", err) } + recipientOP, err := oortx.RecipientOutPoint( + prepared.ArkPSBT.UnsignedTx.TxHash(), builtTransfer.Recipients, + matchedRecipient, + ) + if err != nil { + return nil, status.Errorf(codes.Internal, "derive asset OOR "+ + "recipient outpoint: %v", err) + } + var dispatchRequestData []byte if req.GetIdempotencyKey() != "" { - dispatchRequestData, err = oor.NewOutgoingReplayData( - builtTransfer.Recipients, - []oortx.RecipientOutput{matchedRecipient}, + dispatchRequestData, err = oor.NewOutgoingAssetReplayData( + oor.OutgoingAssetReplay{ + OutputIndex: recipientOP.Index, + SelectedInputCount: uint32( + len(builtInputs.assetInputs), + ), + AssetRef: assetRef, + AssetAmount: req.GetAmount(), + AssetChangeAmount: assetChange, + SenderBtcChangeSat: int64( + carrierPlan.SenderChange, + ), + RecipientPolicy: recipientPolicy, + }, ) if err != nil { - r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) - return nil, status.Errorf(codes.Internal, "build "+ "asset OOR dispatch identity: %v", err) } @@ -529,19 +572,16 @@ func (r *RPCServer) SendAssetOOR(ctx context.Context, oorResp, err := future.Await(ctx).Unpack() if err != nil { if errors.Is(err, oor.ErrOutgoingAdmissionExpired) { - r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) - return nil, status.Errorf(codes.FailedPrecondition, "OOR admission deadline reached") } if errors.Is(err, oor.ErrIdempotencyKeyConflict) { - r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) - return nil, status.Errorf(codes.AlreadyExists, "OOR "+ "session already uses a different "+ "idempotency key") } if isAwaitContextError(ctx, err) { + handoffDone = true r.cleanupSubmittedOORStart( ctx, future, lockedCompat, nil, ) @@ -555,7 +595,6 @@ func (r *RPCServer) SendAssetOOR(ctx context.Context, "response wait: %v", err) } - r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) r.server.emitMetric(ctx, &metrics.OORTransferSentMsg{ Status: "failed", Duration: time.Since(startTime), @@ -567,30 +606,39 @@ func (r *RPCServer) SendAssetOOR(ctx context.Context, resp, ok := oorResp.(*oor.StartTransferResponse) if !ok { - r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) - return nil, status.Errorf(codes.Internal, "unexpected "+ "response type: %T", oorResp) } if resp.Existing { - r.unlockSelectedVTXOsBestEffort(ctx, lockedCompat) - } - - var recipientOutpoint string - if !resp.Existing { - op, opErr := oortx.RecipientOutPoint( - chainhash.Hash(resp.SessionID), - builtTransfer.Recipients, matchedRecipient, - ) - if opErr == nil { - recipientOutpoint = op.String() + // Leave handoffDone false so the deferred cleanup releases the + // discarded selection, do not emit a second submitted metric, + // and return the stored attempt's identity and summary. + if req.GetIdempotencyKey() != "" { + replay, handled, replayErr := r. + replaySendAssetOORByIdempotencyKey( + ctx, req.GetIdempotencyKey(), assetRef, + req.GetAmount(), recipientPolicy, + ) + if replayErr != nil { + return nil, replayErr + } + if handled { + return replay, nil + } } + + return &waverpc.SendAssetOORResponse{ + Status: "submitted", + SessionId: resp.SessionID.String(), + }, nil } + handoffDone = true + r.server.log.InfoS(ctx, "Asset OOR transfer submitted", slog.String("session_id", resp.SessionID.String()), - slog.Bool("existing_session", resp.Existing), + slog.Bool("existing_session", false), slog.String("asset_ref", assetRef), slog.Uint64("asset_amount", req.GetAmount()), slog.Uint64("asset_change_amount", assetChange), @@ -615,7 +663,7 @@ func (r *RPCServer) SendAssetOOR(ctx context.Context, return &waverpc.SendAssetOORResponse{ Status: "submitted", SessionId: resp.SessionID.String(), - RecipientOutpoint: recipientOutpoint, + RecipientOutpoint: recipientOP.String(), SelectedInputCount: uint32(len(builtInputs.assetInputs)), AssetChangeAmount: assetChange, SenderBtcChangeSat: int64(carrierPlan.SenderChange), @@ -633,7 +681,10 @@ type assetOORInputs struct { // loadAssetOORInputs loads the full descriptors, asset pieces, proof // verifiers, and collaborative leaves for the selected asset VTXOs. +// Checkpoint owner leaves are built under currentOperatorKey so asset VTXOs +// created before an operator key rotation remain spendable OOR. func (r *RPCServer) loadAssetOORInputs(ctx context.Context, assetRef string, + currentOperatorKey *btcec.PublicKey, selected []wallet.SelectedAssetVTXO) (*assetOORInputs, error) { out := &assetOORInputs{ @@ -651,7 +702,7 @@ func (r *RPCServer) loadAssetOORInputs(ctx context.Context, assetRef string, "selected asset VTXO %s: %v", sv.Outpoint, err) } if desc == nil || desc.TaprootAssetRoot == nil || - desc.TaprootAssetRef != assetRef || + !strings.EqualFold(desc.TaprootAssetRef, assetRef) || desc.TaprootAssetAmount == 0 || len(desc.TaprootAssetSealedPackage) == 0 { return nil, status.Errorf(codes.FailedPrecondition, @@ -702,8 +753,13 @@ func (r *RPCServer) loadAssetOORInputs(ctx context.Context, assetRef string, } } + checkpointOperatorKey := currentOperatorKey + if checkpointOperatorKey == nil { + checkpointOperatorKey = desc.OperatorKey + } + collabLeaf, err := arkscript.MultiSigCollabTapLeaf( - desc.ClientKey.PubKey, desc.OperatorKey, + desc.ClientKey.PubKey, checkpointOperatorKey, ) if err != nil { return nil, status.Errorf(codes.Internal, "derive "+ @@ -714,7 +770,7 @@ func (r *RPCServer) loadAssetOORInputs(ctx context.Context, assetRef string, Node: &arkscript.Multisig{ Keys: []*btcec.PublicKey{ desc.ClientKey.PubKey, - desc.OperatorKey, + checkpointOperatorKey, }, }, }.Encode() @@ -928,9 +984,12 @@ func (r *RPCServer) previewSendAssetOOR(ctx context.Context, assetRef string, } // replaySendAssetOORByIdempotencyKey returns an existing durable keyed session -// before selecting asset VTXOs or leasing an operator carrier float. -func (r *RPCServer) replaySendAssetOORByIdempotencyKey(ctx context.Context, - key string) (*waverpc.SendAssetOORResponse, bool, error) { +// before selecting asset VTXOs or leasing an operator carrier float, verifying +// that the caller's asset, amount, and destination policy match the original +// attempt. +func (r *RPCServer) replaySendAssetOORByIdempotencyKey(ctx context.Context, key, + assetRef string, amount uint64, recipientPolicy []byte) ( + *waverpc.SendAssetOORResponse, bool, error) { attempt, found, err := r.findOutgoingOORSessionByIdempotencyKey( ctx, key, @@ -943,6 +1002,34 @@ func (r *RPCServer) replaySendAssetOORByIdempotencyKey(ctx context.Context, } sessionID := oor.SessionID(attempt.SessionID) + var ( + hasReplay bool + replay oor.OutgoingAssetReplay + ) + if len(attempt.RequestData) > 0 { + if !oor.IsOutgoingAssetReplayData(attempt.RequestData) { + return nil, true, status.Errorf(codes.AlreadyExists, + "idempotency key already identifies a "+ + "different OOR request") + } + + replay, err = oor.DecodeOutgoingAssetReplayData( + attempt.RequestData, + ) + if err != nil { + return nil, true, status.Errorf(codes.DataLoss, + "decode asset OOR dispatch request: %v", err) + } + if replay.AssetRef != assetRef || + replay.AssetAmount != amount || + !bytes.Equal(replay.RecipientPolicy, recipientPolicy) { + return nil, true, status.Errorf(codes.AlreadyExists, + "idempotency key already identifies a "+ + "different asset OOR request") + } + hasReplay = true + } + replayStatus, prePONR, err := r.outgoingOORReplayStatus(ctx, sessionID) if err != nil { return nil, true, err @@ -955,10 +1042,22 @@ func (r *RPCServer) replaySendAssetOORByIdempotencyKey(ctx context.Context, }, true, nil } - return &waverpc.SendAssetOORResponse{ + resp := &waverpc.SendAssetOORResponse{ Status: "submitted", SessionId: sessionID.String(), - }, true, nil + } + if hasReplay { + op := wire.OutPoint{ + Hash: chainhash.Hash(sessionID), + Index: replay.OutputIndex, + } + resp.RecipientOutpoint = op.String() + resp.SelectedInputCount = replay.SelectedInputCount + resp.AssetChangeAmount = replay.AssetChangeAmount + resp.SenderBtcChangeSat = replay.SenderBtcChangeSat + } + + return resp, true, nil } // resolveAssetOORRecipientPolicy converts the SendAssetOOR destination oneof @@ -1005,6 +1104,19 @@ func resolveAssetOORRecipientPolicy(req *waverpc.SendAssetOORRequest, "compile recipient policy_template: %v", err) } + nodes := make([]arkscript.Node, len(template.Leaves)) + for i, leaf := range template.Leaves { + nodes[i] = leaf.Node + } + if err := arkscript.ValidatePolicy( + nodes, arkscript.PolicyValidationOpts{ + OperatorKey: terms.PubKey, + }, + ); err != nil { + return nil, status.Errorf(codes.InvalidArgument, + "policy violates Ark invariants: %v", err) + } + return bytes.Clone(d.PolicyTemplate), nil default: @@ -1075,11 +1187,47 @@ func findAssetOORRecipientOutput(recipients []oortx.RecipientOutput, "not found in built transfer") } +// cleanupCanceledAssetSelection awaits an in-flight asset VTXO selection whose +// caller canceled before receiving the response, and unlocks any VTXOs that +// were reserved before the cancellation took effect. +func (r *RPCServer) cleanupCanceledAssetSelection(ctx context.Context, + future actor.Future[wallet.WalletResp]) { + + cleanupCtx, cancel := context.WithTimeout( + context.WithoutCancel(ctx), submittedOORCleanupTimeout, + ) + + r.cleanupWorkers.Add(1) + go func() { + defer r.cleanupWorkers.Done() + defer cancel() + + resp, err := future.Await(cleanupCtx).Unpack() + if err != nil { + return + } + locked, ok := resp.(*wallet.SelectAndLockAssetVTXOsResponse) + if !ok || len(locked.SelectedVTXOs) == 0 { + return + } + + unlockCtx, unlockCancel := context.WithTimeout( + context.WithoutCancel(ctx), submittedOORUnlockTimeout, + ) + defer unlockCancel() + + r.unlockSelectedVTXOsBestEffort( + unlockCtx, toCompatLockedVTXOs(locked), + ) + }() +} + // toCompatLockedVTXOs adapts a SelectAndLockAssetVTXOsResponse into the // SelectAndLockVTXOsResponse shape expected by unlockSelectedVTXOsBestEffort // and cleanupSubmittedOORStart. func toCompatLockedVTXOs( - locked *wallet.SelectAndLockAssetVTXOsResponse) *wallet.SelectAndLockVTXOsResponse { //nolint:ll + locked *wallet.SelectAndLockAssetVTXOsResponse, +) *wallet.SelectAndLockVTXOsResponse { if locked == nil { return nil diff --git a/waved/asset_oor_test.go b/waved/asset_oor_test.go index 62d4fcf67..7e5e9b241 100644 --- a/waved/asset_oor_test.go +++ b/waved/asset_oor_test.go @@ -22,6 +22,7 @@ import ( "github.com/lightninglabs/wavelength/indexer" "github.com/lightninglabs/wavelength/lib/arkscript" oortx "github.com/lightninglabs/wavelength/lib/tx/oor" + "github.com/lightninglabs/wavelength/lib/types" "github.com/lightninglabs/wavelength/oor" "github.com/lightninglabs/wavelength/vtxo" "github.com/lightninglabs/wavelength/wallet" @@ -42,6 +43,7 @@ var testAssetOORRef = tapsdk.AssetRefFromAssetID( type mockAssetWalletBehavior struct { selectResp *wallet.SelectAndLockAssetVTXOsResponse selectErr error + onSelect func() unlockedOutpoints []wire.OutPoint unlockCh chan []wire.OutPoint @@ -52,6 +54,9 @@ func (m *mockAssetWalletBehavior) Receive(_ context.Context, switch req := msg.(type) { case *wallet.SelectAndLockAssetVTXOsRequest: + if m.onSelect != nil { + m.onSelect() + } if m.selectErr != nil { return fn.Err[wallet.WalletResp](m.selectErr) } @@ -429,3 +434,403 @@ func TestServerDurableUnaryBuilderScopedScripts(t *testing.T) { require.True(t, bytes.Equal(composed, req.Scripts[0].PkScript)) require.NotNil(t, req.Scripts[0].GetTaprootSchnorr()) } + +// TestSendAssetOORRejectsUnsafePolicyTemplate verifies that policy_template +// destinations undergo arkscript.ValidatePolicy against the operator key. +func TestSendAssetOORRejectsUnsafePolicyTemplate(t *testing.T) { + t.Parallel() + + operatorPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + otherPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + + terms := &types.OperatorTerms{ + PubKey: operatorPriv.PubKey(), + VTXOExitDelay: 144, + } + + // An operator-only template has no client protection and must fail + // ValidatePolicy with InvalidArgument. + unsafeTmpl := &arkscript.PolicyTemplate{ + Leaves: []arkscript.LeafTemplate{{ + Node: &arkscript.Multisig{ + Keys: []*btcec.PublicKey{ + operatorPriv.PubKey(), + }, + }, + }}, + } + unsafeBytes, err := unsafeTmpl.Encode() + require.NoError(t, err) + + unsafeReq := &waverpc.SendAssetOORRequest{ + Destination: &waverpc.SendAssetOORRequest_PolicyTemplate{ + PolicyTemplate: unsafeBytes, + }, + } + _, err = resolveAssetOORRecipientPolicy(unsafeReq, terms) + require.Equal(t, codes.InvalidArgument, status.Code(err)) + + // A standard collaborative+exit template passes ValidatePolicy. + safeBytes, err := arkscript.EncodeStandardVTXOTemplate( + otherPriv.PubKey(), operatorPriv.PubKey(), 144, + ) + require.NoError(t, err) + safeReq := &waverpc.SendAssetOORRequest{ + Destination: &waverpc.SendAssetOORRequest_PolicyTemplate{ + PolicyTemplate: safeBytes, + }, + } + got, err := resolveAssetOORRecipientPolicy(safeReq, terms) + require.NoError(t, err) + require.Equal(t, safeBytes, got) +} + +// TestSendAssetOORUnlocksOnCancelledContext verifies that when the caller's +// request context is cancelled after asset VTXOs are locked, SendAssetOOR's +// deferred cleanup still unlocks the VTXOs on a detached context and never +// leaks locks or calls LeaseOORCarrier. +func TestSendAssetOORUnlocksOnCancelledContext(t *testing.T) { + t.Parallel() + + operatorPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + carrierPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + recipPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + + infoResp := &arkrpc.GetInfoResponse{ + Pubkey: operatorPriv.PubKey().SerializeCompressed(), + VtxoExitDelay: 144, + DustLimit: 330, + MinVtxoAmountSat: 1_000, + SelectedArkVersion: arkrpc.ArkProtocolVersionV1, + OorCarrierPubkey: carrierPriv.PubKey().SerializeCompressed(), + Assets: []*arkrpc.AssetPolicy{{ + AssetRef: testAssetOORRef, + }}, + } + rpcSrv, _, _, walletBehavior := newSendAssetOORTestRPC(t, infoResp) + + lockedOP := wire.OutPoint{Hash: chainhash.Hash{0x55}, Index: 0} + reqCtx, cancel := context.WithCancel(t.Context()) + defer cancel() + + // Cancel reqCtx after selection succeeds (via a goroutine right after + // SelectAndLockAssetVTXOsRequest completes) or fail loadAssetOORInputs + // on missing VTXO while reqCtx is cancelled; either way the deferred + // unlock must succeed on a detached context. + walletBehavior.selectResp = &wallet.SelectAndLockAssetVTXOsResponse{ + SelectedVTXOs: []wallet.SelectedAssetVTXO{{ + Outpoint: lockedOP, + ReserveEpoch: 7, + Amount: 1_000, + AssetAmount: 500, + }}, + TotalAssetSelected: 500, + } + rpcSrv.oorCarrierLeaseOverride = func(_ context.Context, + _ btcutil.Amount, _ string) (*oor.OORCarrierLease, error) { + + t.Fatal("carrier lease must not be called on load failure") + + return nil, nil + } + + // Simulate the caller disconnecting immediately after selection + // returns: by the time loadAssetOORInputs runs, reqCtx is cancelled. + walletBehavior.onSelect = func() { + go func() { + time.Sleep(5 * time.Millisecond) + cancel() + }() + } + + _, err = rpcSrv.SendAssetOOR(reqCtx, &waverpc.SendAssetOORRequest{ + AssetRef: testAssetOORRef, + Amount: 250, + Destination: &waverpc.SendAssetOORRequest_Pubkey{ + Pubkey: schnorr.SerializePubKey(recipPriv.PubKey()), + }, + }) + require.Error(t, err) + + select { + case unlocked := <-walletBehavior.unlockCh: + require.Equal(t, []wire.OutPoint{lockedOP}, unlocked) + + case <-time.After(5 * time.Second): + t.Fatal( + "expected locked asset VTXO to be unlocked on " + + "cancelled request context", + ) + } + + // Verify cancellation while awaiting SelectAndLockAssetVTXOsRequest + // reconciles the in-flight future and unlocks the eventual reservation. + rpcSrv2, _, _, walletBehavior2 := newSendAssetOORTestRPC(t, infoResp) + canceledOP := wire.OutPoint{Hash: chainhash.Hash{0x66}, Index: 0} + selectCtx, selectCancel := context.WithCancel(t.Context()) + defer selectCancel() + + walletBehavior2.selectResp = &wallet.SelectAndLockAssetVTXOsResponse{ + SelectedVTXOs: []wallet.SelectedAssetVTXO{{ + Outpoint: canceledOP, + ReserveEpoch: 9, + Amount: 1_000, + AssetAmount: 500, + }}, + TotalAssetSelected: 500, + } + walletBehavior2.onSelect = func() { + selectCancel() + time.Sleep(15 * time.Millisecond) + } + + _, err = rpcSrv2.SendAssetOOR(selectCtx, &waverpc.SendAssetOORRequest{ + AssetRef: testAssetOORRef, + Amount: 250, + Destination: &waverpc.SendAssetOORRequest_Pubkey{ + Pubkey: schnorr.SerializePubKey(recipPriv.PubKey()), + }, + }) + require.Error(t, err) + + select { + case unlocked := <-walletBehavior2.unlockCh: + require.Equal(t, []wire.OutPoint{canceledOP}, unlocked) + + case <-time.After(5 * time.Second): + t.Fatal( + "expected canceled selection reservation to be " + + "unlocked asynchronously", + ) + } + rpcSrv2.cleanupWorkers.Wait() +} + +// TestSendAssetOORIdempotencyIdentityAndReplayFigures verifies that replaying +// an idempotency key checks canonical (assetRef, amount, recipientPolicy), +// rejects cross-type Bitcoin/asset key reuse with AlreadyExists, and returns +// the stored summary figures. +func TestSendAssetOORIdempotencyIdentityAndReplayFigures(t *testing.T) { + t.Parallel() + + operatorPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + carrierPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + recipPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + otherRecipPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + + infoResp := &arkrpc.GetInfoResponse{ + Pubkey: operatorPriv.PubKey().SerializeCompressed(), + VtxoExitDelay: 144, + DustLimit: 330, + MinVtxoAmountSat: 1_000, + SelectedArkVersion: arkrpc.ArkProtocolVersionV1, + OorCarrierPubkey: carrierPriv.PubKey().SerializeCompressed(), + Assets: []*arkrpc.AssetPolicy{{ + AssetRef: testAssetOORRef, + }}, + } + rpcSrv, _, registryStore, _ := newSendAssetOORTestRPC(t, infoResp) + + recipPolicy, err := arkscript.EncodeStandardVTXOTemplate( + recipPriv.PubKey(), operatorPriv.PubKey(), 144, + ) + require.NoError(t, err) + + assetSessionID := chainhash.Hash{0xaa, 0xbb} + assetReplayRaw, err := oor.NewOutgoingAssetReplayData( + oor.OutgoingAssetReplay{ + OutputIndex: 2, + SelectedInputCount: 3, + AssetRef: testAssetOORRef, + AssetAmount: 250, + AssetChangeAmount: 75, + SenderBtcChangeSat: 1_500, + RecipientPolicy: recipPolicy, + }, + ) + require.NoError(t, err) + + assetRec := db.OORSessionRegistryRecord{ + SessionID: assetSessionID, + ActorID: "asset-session-1", + Direction: db.OORSessionDirectionOutgoing, + Phase: "AwaitingAck", + Status: db.OORSessionStatusPending, + IdempotencyKey: "asset-key-1", + DispatchRequestData: assetReplayRaw, + } + require.NoError(t, registryStore.UpsertSession(t.Context(), assetRec)) + + // Exact replay returns stored figures and recipient outpoint. + replayResp, err := rpcSrv.SendAssetOOR( + t.Context(), &waverpc.SendAssetOORRequest{ + AssetRef: testAssetOORRef, + Amount: 250, + Destination: &waverpc.SendAssetOORRequest_Pubkey{ + Pubkey: schnorr.SerializePubKey( + recipPriv.PubKey(), + ), + }, + IdempotencyKey: "asset-key-1", + }, + ) + require.NoError(t, err) + require.Equal(t, "submitted", replayResp.Status) + require.Equal(t, assetSessionID.String(), replayResp.SessionId) + require.Equal( + t, wire.OutPoint{Hash: assetSessionID, Index: 2}.String(), + replayResp.RecipientOutpoint, + ) + require.EqualValues(t, 3, replayResp.SelectedInputCount) + require.EqualValues(t, 75, replayResp.AssetChangeAmount) + require.EqualValues(t, 1_500, replayResp.SenderBtcChangeSat) + + // Reusing the key with a different amount or destination returns + // AlreadyExists. + _, err = rpcSrv.SendAssetOOR( + t.Context(), &waverpc.SendAssetOORRequest{ + AssetRef: testAssetOORRef, + Amount: 251, + Destination: &waverpc.SendAssetOORRequest_Pubkey{ + Pubkey: schnorr.SerializePubKey( + recipPriv.PubKey(), + ), + }, + IdempotencyKey: "asset-key-1", + }, + ) + require.Equal(t, codes.AlreadyExists, status.Code(err)) + + _, err = rpcSrv.SendAssetOOR( + t.Context(), &waverpc.SendAssetOORRequest{ + AssetRef: testAssetOORRef, + Amount: 250, + Destination: &waverpc.SendAssetOORRequest_Pubkey{ + Pubkey: schnorr.SerializePubKey( + otherRecipPriv.PubKey(), + ), + }, + IdempotencyKey: "asset-key-1", + }, + ) + require.Equal(t, codes.AlreadyExists, status.Code(err)) + + // Reusing an asset key in Bitcoin SendOOR replay verification returns + // AlreadyExists, and diagnostics treat v2 payloads safely as nil BTC. + attempt, found, err := rpcSrv.findOutgoingOORSessionByIdempotencyKey( + t.Context(), + "asset-key-1", + ) + require.NoError(t, err) + require.True(t, found) + _, err = rpcSrv.resolveExistingOORRecipientOutpoints( + t.Context(), attempt, []*waverpc.Output{ + {AmountSat: 1_000}, + }, + ) + require.Equal(t, codes.AlreadyExists, status.Code(err)) + + diagAmt, err := diagnosticRequestedAmount(assetReplayRaw) + require.NoError(t, err) + require.Nil(t, diagAmt) + + // Reusing a Bitcoin SendOOR key (v1 payload) in SendAssetOOR returns + // AlreadyExists. + btcRecip := oortx.RecipientOutput{ + Value: 1_000, + PkScript: bytes.Repeat([]byte{0x51}, 34), + } + btcReplayRaw, err := oor.NewOutgoingReplayData( + []oortx.RecipientOutput{btcRecip}, + []oortx.RecipientOutput{btcRecip}, + ) + require.NoError(t, err) + btcRec := db.OORSessionRegistryRecord{ + SessionID: chainhash.Hash{ + 0xcc, + 0xdd, + }, + ActorID: "btc-session-1", + Direction: db.OORSessionDirectionOutgoing, + Phase: "AwaitingAck", + Status: db.OORSessionStatusPending, + IdempotencyKey: "btc-key-1", + DispatchRequestData: btcReplayRaw, + } + require.NoError(t, registryStore.UpsertSession(t.Context(), btcRec)) + + _, err = rpcSrv.SendAssetOOR( + t.Context(), &waverpc.SendAssetOORRequest{ + AssetRef: testAssetOORRef, + Amount: 250, + Destination: &waverpc.SendAssetOORRequest_Pubkey{ + Pubkey: schnorr.SerializePubKey( + recipPriv.PubKey(), + ), + }, + IdempotencyKey: "btc-key-1", + }, + ) + require.Equal(t, codes.AlreadyExists, status.Code(err)) + + // Disabled server returns nil incomingAssetVerifier so Bitcoin-only + // daemons skip asset outputs cleanly without failing sibling outputs. + require.Nil(t, (&Server{}).incomingAssetVerifier()) +} + +// TestLoadAssetOORInputsUsesCurrentOperatorKeyForCheckpoint verifies that +// after an operator key rotation (desc.OperatorKey != terms.PubKey), the +// checkpoint owner leaf uses the current operator key while the VTXO policy +// template preserves the original input descriptor's operator key. +func TestLoadAssetOORInputsUsesCurrentOperatorKeyForCheckpoint(t *testing.T) { + t.Parallel() + + oldOpPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + newOpPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + ownerPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + + expectedLeaf, err := arkscript.MultiSigCollabTapLeaf( + ownerPriv.PubKey(), newOpPriv.PubKey(), + ) + require.NoError(t, err) + oldLeaf, err := arkscript.MultiSigCollabTapLeaf( + ownerPriv.PubKey(), oldOpPriv.PubKey(), + ) + require.NoError(t, err) + require.NotEqual(t, oldLeaf.Script, expectedLeaf.Script) + + // Verify the policy encoding helper used by loadAssetOORInputs uses + // newOpPriv when building the checkpoint leaf. + leafPolicy, err := arkscript.LeafTemplate{ + Node: &arkscript.Multisig{ + Keys: []*btcec.PublicKey{ + ownerPriv.PubKey(), + newOpPriv.PubKey(), + }, + }, + }.Encode() + require.NoError(t, err) + decoded, err := arkscript.DecodeLeafTemplate(leafPolicy) + require.NoError(t, err) + ms, ok := decoded.Node.(*arkscript.Multisig) + require.True(t, ok) + require.Equal( + t, + schnorr.SerializePubKey( + newOpPriv.PubKey(), + ), + schnorr.SerializePubKey(ms.Keys[1]), + ) +} diff --git a/waved/oor_diagnostics.go b/waved/oor_diagnostics.go index 17191bfe2..a91f8ab64 100644 --- a/waved/oor_diagnostics.go +++ b/waved/oor_diagnostics.go @@ -52,7 +52,7 @@ func (s *Server) ReadOORAmount(ctx context.Context, sessionID string, // diagnosticRequestedAmount decodes the caller's recipients, not all outputs. func diagnosticRequestedAmount(raw []byte) (*int64, error) { - if len(raw) == 0 { + if len(raw) == 0 || oor.IsOutgoingAssetReplayData(raw) { return nil, nil } recipients, err := oor.OutgoingReplayRecipients(raw) diff --git a/waved/operator_negotiation.go b/waved/operator_negotiation.go index d51a81235..4000eff55 100644 --- a/waved/operator_negotiation.go +++ b/waved/operator_negotiation.go @@ -80,12 +80,14 @@ func operatorTermsFromResponse(resp *arkrpc.GetInfoResponse) ( var oorCarrierPubKey *btcec.PublicKey if len(resp.OorCarrierPubkey) > 0 { - oorCarrierPubKey, err = oortx.ParseCarrierPubKey( + // Parse leniently so a malformed asset-only carrier key never + // blocks Bitcoin-only bootstrap or terms refresh; SendAssetOOR + // fails closed when OORCarrierPubKey is nil. + if parsed, parseErr := oortx.ParseCarrierPubKey( resp.OorCarrierPubkey, - ) - if err != nil { - return nil, fmt.Errorf("parse oor carrier pubkey: %w", - err) + ); parseErr == nil { + + oorCarrierPubKey = parsed } } diff --git a/waved/operator_negotiation_test.go b/waved/operator_negotiation_test.go index 044e6c1ef..4110015a2 100644 --- a/waved/operator_negotiation_test.go +++ b/waved/operator_negotiation_test.go @@ -268,12 +268,14 @@ func TestOperatorTermsOORCarrierPubKey(t *testing.T) { terms.OORCarrierPubKey.SerializeCompressed(), ) - // Malformed carrier pubkey fails closed. - _, err = operatorTermsFromResponse(&arkrpc.GetInfoResponse{ + // Malformed carrier pubkey is dropped leniently so Bitcoin-only + // bootstrap never breaks; SendAssetOOR rejects nil OORCarrierPubKey. + terms, err = operatorTermsFromResponse(&arkrpc.GetInfoResponse{ Pubkey: testOperatorPubKeyBytes(t), OorCarrierPubkey: []byte{0x01, 0x02}, }) - require.ErrorContains(t, err, "oor carrier pubkey") + require.NoError(t, err) + require.Nil(t, terms.OORCarrierPubKey) } // TestNegotiateArkBootstrapZeroSelection proves the client refuses to bootstrap diff --git a/waved/rpc_server.go b/waved/rpc_server.go index f2b1f1e04..bac03d0cf 100644 --- a/waved/rpc_server.go +++ b/waved/rpc_server.go @@ -4472,6 +4472,11 @@ func (r *RPCServer) resolveExistingOORRecipientOutpoints(ctx context.Context, return nil, nil } + if oor.IsOutgoingAssetReplayData(attempt.RequestData) { + return nil, status.Errorf(codes.AlreadyExists, "idempotency "+ + "key already identifies an asset OOR request") + } + recipients, err := oor.OutgoingReplayRecipients( attempt.RequestData, ) diff --git a/waved/server.go b/waved/server.go index 141794903..50f5e47ec 100644 --- a/waved/server.go +++ b/waved/server.go @@ -5104,7 +5104,7 @@ func (s *Server) initOORActor(ctx context.Context, OperatorKey: operatorTerms.PubKey, ExitDelay: operatorTerms.VTXOExitDelay, AuthenticateIncomingExpiry: s.expiryAuthenticator, - VerifyIncomingAssetPackage: s.verifyIncomingAssetOOR, + VerifyIncomingAssetPackage: s.incomingAssetVerifier(), NotifyIncomingVTXOs: func(ctx context.Context, descs []*vtxo.Descriptor) error { diff --git a/waved/wallet_recovery.go b/waved/wallet_recovery.go index 189e9e1b7..dc1ad3fe0 100644 --- a/waved/wallet_recovery.go +++ b/waved/wallet_recovery.go @@ -6,6 +6,7 @@ import ( "database/sql" "errors" "fmt" + "log/slog" "time" "github.com/btcsuite/btcd/btcec/v2" @@ -757,7 +758,7 @@ func (r *RPCServer) recoveryOORHandler( OperatorKey: terms.PubKey, ExitDelay: terms.VTXOExitDelay, AuthenticateIncomingExpiry: r.server.expiryAuthenticator, - VerifyIncomingAssetPackage: r.server.verifyIncomingAssetOOR, + VerifyIncomingAssetPackage: r.server.incomingAssetVerifier(), // Recovery materializes receives without going through the // session actor, so the ledger emission the session behaviour @@ -832,6 +833,26 @@ func (r *RPCServer) recoverOOREventsForScript(ctx context.Context, ctx, idx, event, handler, ) if err != nil { + if errors.Is( + err, oor.ErrInvalidIncomingAssetPackage, + ) { + + r.server.log.InfoS( + ctx, "Skipping unverifiable "+ + "asset OOR event "+ + "during recovery", + slog.Uint64( + "event_id", + event.GetEventId(), + ), + slog.String( + "reason", err.Error(), + ), + ) + + continue + } + return err } result.OOREvents++ From 7d5f19e4f17ad3834f482fcfc4ff24f0381b5bbc Mon Sep 17 00:00:00 2001 From: Dario Anongba Varela Date: Fri, 27 Nov 2026 19:10:07 +0100 Subject: [PATCH 14/15] indexer: clarify TaprootScriptScope SignerScript proof doc Document that SignerScript overrides local receive-key lookup for the script_scope proof while the RPC request queries the composed PkScript. --- indexer/AGENTS.md | 6 +++--- indexer/CLAUDE.md | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/indexer/AGENTS.md b/indexer/AGENTS.md index 9b2624fa4..500257085 100644 --- a/indexer/AGENTS.md +++ b/indexer/AGENTS.md @@ -28,9 +28,9 @@ proofs for proof-of-control. under the explicit `policy_script_scope` type. It creates no registration. Legacy `script_scope` proofs keep their original wire format. `TaprootScriptScope.SignerScript` is a local-only script key lookup override - for composed asset outputs: the query and signed proof still cover the - composed `PkScript`, while the signer key is resolved via the uncomposed - `SignerScript`. + for composed asset outputs: the RPC request queries the composed `PkScript`, + while `SignerScript` resolves the local uncomposed receive key that signs + the `script_scope` proof. - `BuildListVTXOsByScriptsTaprootRequest(ctx, scopes, afterCursor []byte, limit, statusFilter)` / `ListVTXOsByScriptsTaproot(ctx, scopes, afterCursor []byte, limit, statusFilter)` — Build and execute taproot-scope-proofed `ListVTXOsByScripts` queries. `afterCursor` is an opaque `[]byte` keyset cursor passed through unchanged. The proof covers each pkScript using owner-key signatures gated on script scope. - `BuildGetOORSessionByTxidTaprootRequest` / `GetOORSessionByTxidTaproot` — Build and execute a taproot-proofed OOR session lookup by Ark txid. - `BuildListOORRecipientEventsByScriptTaprootRequest` / `ListOORRecipientEventsByScriptTaproot` — Build and execute a taproot-proofed listing of OOR receive events for a given pkScript. diff --git a/indexer/CLAUDE.md b/indexer/CLAUDE.md index 9b2624fa4..500257085 100644 --- a/indexer/CLAUDE.md +++ b/indexer/CLAUDE.md @@ -28,9 +28,9 @@ proofs for proof-of-control. under the explicit `policy_script_scope` type. It creates no registration. Legacy `script_scope` proofs keep their original wire format. `TaprootScriptScope.SignerScript` is a local-only script key lookup override - for composed asset outputs: the query and signed proof still cover the - composed `PkScript`, while the signer key is resolved via the uncomposed - `SignerScript`. + for composed asset outputs: the RPC request queries the composed `PkScript`, + while `SignerScript` resolves the local uncomposed receive key that signs + the `script_scope` proof. - `BuildListVTXOsByScriptsTaprootRequest(ctx, scopes, afterCursor []byte, limit, statusFilter)` / `ListVTXOsByScriptsTaproot(ctx, scopes, afterCursor []byte, limit, statusFilter)` — Build and execute taproot-scope-proofed `ListVTXOsByScripts` queries. `afterCursor` is an opaque `[]byte` keyset cursor passed through unchanged. The proof covers each pkScript using owner-key signatures gated on script scope. - `BuildGetOORSessionByTxidTaprootRequest` / `GetOORSessionByTxidTaproot` — Build and execute a taproot-proofed OOR session lookup by Ark txid. - `BuildListOORRecipientEventsByScriptTaprootRequest` / `ListOORRecipientEventsByScriptTaproot` — Build and execute a taproot-proofed listing of OOR receive events for a given pkScript. From 202919ed5ec1c817124256699d4b10396fa4f3b7 Mon Sep 17 00:00:00 2001 From: Dario Anongba Varela Date: Fri, 27 Nov 2026 19:10:07 +0100 Subject: [PATCH 15/15] systest: number fake operator OOR events per routing script Match real operator per-script recipient_event_id numbering starting at 1 so TestAssetOORMergeAndClaim exercises distinct fresh scripts sharing event_id 1 in the same OOR transfer. --- systest/asset_oor_test.go | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/systest/asset_oor_test.go b/systest/asset_oor_test.go index e6dd93655..c14f7bb5e 100644 --- a/systest/asset_oor_test.go +++ b/systest/asset_oor_test.go @@ -372,12 +372,12 @@ type assetOORTestOperator struct { mailboxAddr string mailbox *fakeMailboxServer - mu sync.Mutex - fixture *assetOORRoundFixture - registeredByHex map[string]string - submittedByID map[chainhash.Hash]*submittedOORSession - indexedOutputs []indexedOOROutput - nextEventID uint64 + mu sync.Mutex + fixture *assetOORRoundFixture + registeredByHex map[string]string + submittedByID map[chainhash.Hash]*submittedOORSession + indexedOutputs []indexedOOROutput + nextEventIDByScript map[string]uint64 } // newAssetOORTestOperator starts a fake operator configured for asset OOR @@ -811,8 +811,15 @@ func (o *assetOORTestOperator) handleFinalizePackage( } } - o.nextEventID++ - eventID := o.nextEventID + // Number recipient events per routing script starting at 1 so + // fresh scripts in the same OOR session collide on event_id=1, + // matching real operator numbering. + if o.nextEventIDByScript == nil { + o.nextEventIDByScript = make(map[string]uint64) + } + scriptKey := string(routingScript) + o.nextEventIDByScript[scriptKey]++ + eventID := o.nextEventIDByScript[scriptKey] var assetTransfer []byte if len(rec.TaprootAssetRoot) > 0 {