diff --git a/.assets/go-perun.png b/.assets/go-perun.png
new file mode 100644
index 0000000..6d8787b
Binary files /dev/null and b/.assets/go-perun.png differ
diff --git a/.gitignore b/.gitignore
index 66fd13c..3a9f218 100644
--- a/.gitignore
+++ b/.gitignore
@@ -13,3 +13,6 @@
# Dependency directories (remove the comment below to include it)
# vendor/
+
+settings.json
+launch.json
\ No newline at end of file
diff --git a/Dockerfile b/Dockerfile
new file mode 100755
index 0000000..cadb8e4
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,18 @@
+# Based on Preview 7
+# https://soroban.stellar.org/docs/reference/releases
+
+FROM ubuntu:20.04
+
+RUN apt update && apt install -y curl
+
+RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs > rust_install.sh
+RUN sh rust_install.sh -y
+RUN echo $PATH
+ENV PATH="$PATH:/root/.cargo/bin"
+RUN rustup target add wasm32-unknown-unknown
+
+RUN apt install -y build-essential
+# WORKDIR /
+RUN mkdir /workspace
+WORKDIR /workspace
+ENV IS_USING_DOCKER=true
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..7a4a3ea
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
\ No newline at end of file
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..1d5a848
--- /dev/null
+++ b/README.md
@@ -0,0 +1,65 @@
+
+
+
+
+
+# [Perun](https://perun.network/) Stellar backend
+
+This repository contains the [Stellar](https://stellar.org/) backend for the [go-perun](https://github.com/perun-network/go-perun) channel library. It provides the necessary components to run our secure peer-to-peer Perun Payment Channels on the Stellar blockchain, using a [Soroban](https://soroban.stellar.org/) smart contract implementation. The payment channel implementation connects our Perun state machine with the [Perun contract](https://github.com/perun-network/perun-soroban-contract), which implements the Perun Payment Channel logic on the Stellar blockchain. To connect to the Stellar blockchain, we use the Horizon client service of the Stellar Go SDK, which is located [here](https://github.com/stellar/go).
+
+This project is financed through the Stellar Community Fund grants program.
+
+In the following sections, we will describe how to run our Payment Channels on a local instance of the Stellar blockchain.
+
+## [Setup](#setup)
+
+1. Clone this repository:
+
+```
+git clone https://github.com/perun-network/perun-stellar-backend
+cd perun-stellar-backend
+```
+
+2. Running the payment channel unit tests:
+
+To run the unit tests only, you can use the following command:
+
+```sh
+
+go test ./...
+```
+
+3. Running the payment channel tests, including the integration tests:
+
+The integration tests require running a local Stellar blockchain, a Horizon client and a Soroban RPC server. The binaries are packaged in a docker image.
+
+To install the docker image, you need to download and build it first, using the build.sh script in testdata/docker:
+
+```sh
+./testdata/docker/build.sh
+```
+
+Now you can run the docker image with
+
+```sh
+./quickstart.sh standalone
+
+```
+
+The initialization takes a few seconds. Afterwards, you can run the tests using the following command:
+
+```sh
+
+go test -tags=integration ./...
+```
+
+Note that this backend is customized to run on a local Stellar blockchain (standalone), but can be easily adapted to run on a public blockchain.
+
+
+# Payment Channel Demo
+
+A demonstrator of Perun payment channels on the Stellar blockchain can be found [here](https://github.com/perun-network/perun-stellar-demo).
+
+# Copyright
+
+Copyright 2024 PolyCrypt GmbH. Use of the source code is governed by the Apache 2.0 license that can be found in the [LICENSE file](LICENSE).
\ No newline at end of file
diff --git a/channel/adjudicator.go b/channel/adjudicator.go
new file mode 100644
index 0000000..f48aca1
--- /dev/null
+++ b/channel/adjudicator.go
@@ -0,0 +1,311 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package channel
+
+import (
+ "context"
+ "errors"
+ "fmt"
+
+ "github.com/stellar/go/xdr"
+ "perun.network/go-perun/log"
+
+ pchannel "perun.network/go-perun/channel"
+ pwallet "perun.network/go-perun/wallet"
+ "perun.network/perun-stellar-backend/channel/env"
+ "perun.network/perun-stellar-backend/wallet"
+ "perun.network/perun-stellar-backend/wire"
+ "perun.network/perun-stellar-backend/wire/scval"
+ "time"
+)
+
+var ErrChannelAlreadyClosed = errors.New("channel is already closed")
+
+type Adjudicator struct {
+ log log.Embedding
+ stellarClient *env.StellarClient
+ acc *wallet.Account
+ assetID xdr.ScAddress
+ perunID xdr.ScAddress
+ maxIters int
+ pollingInterval time.Duration
+}
+
+// NewAdjudicator returns a new Adjudicator.
+
+func NewAdjudicator(acc *wallet.Account, stellarClient *env.StellarClient, perunID xdr.ScAddress, assetID xdr.ScAddress) *Adjudicator {
+ return &Adjudicator{
+ stellarClient: stellarClient,
+ acc: acc,
+ perunID: perunID,
+ assetID: assetID,
+ maxIters: MaxIterationsUntilAbort,
+ pollingInterval: DefaultPollingInterval,
+ log: log.MakeEmbedding(log.Default()),
+ }
+}
+
+func (a *Adjudicator) GetPerunID() xdr.ScAddress {
+ return a.perunID
+}
+
+func (a *Adjudicator) GetAssetID() xdr.ScAddress {
+ return a.assetID
+}
+
+func (a *Adjudicator) Subscribe(ctx context.Context, cid pchannel.ID) (pchannel.AdjudicatorSubscription, error) {
+ c := a.stellarClient
+ perunID := a.GetPerunID()
+ assetID := a.GetAssetID()
+ return NewAdjudicatorSub(ctx, cid, c, perunID, assetID)
+}
+
+func (a *Adjudicator) Withdraw(ctx context.Context, req pchannel.AdjudicatorReq, smap pchannel.StateMap) error {
+
+ if req.Tx.State.IsFinal {
+ log.Println("Withdraw called")
+
+ if err := a.Close(ctx, req.Tx.ID, req.Tx.State, req.Tx.Sigs); err != nil {
+ chanControl, errChanState := a.GetChannelState(ctx, req.Tx.State)
+ if errChanState != nil {
+ return errChanState
+ }
+
+ if chanControl.Control.Closed {
+ return a.withdraw(ctx, req)
+ }
+ return err
+ }
+
+ return a.withdraw(ctx, req)
+
+ } else {
+ err := a.ForceClose(ctx, req.Tx.ID, req.Tx.State, req.Tx.Sigs, req.Params)
+ log.Println("ForceClose called")
+ if errors.Is(err, ErrChannelAlreadyClosed) {
+ return a.withdraw(ctx, req)
+ }
+ if err != nil {
+ return err
+ }
+
+ err = a.withdraw(ctx, req)
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (a *Adjudicator) GetChannelState(ctx context.Context, state *pchannel.State) (wire.Channel, error) {
+
+ contractAddress := a.GetPerunID()
+ chanId := state.ID
+
+ getchTxArgs, err := env.BuildGetChannelTxArgs(chanId)
+ if err != nil {
+ return wire.Channel{}, errors.New("error while building get_channel tx")
+ }
+ txMeta, err := a.stellarClient.InvokeAndProcessHostFunction("get_channel", getchTxArgs, contractAddress)
+ if err != nil {
+ return wire.Channel{}, errors.New("error while processing and submitting get_channel tx")
+ }
+
+ retVal := txMeta.V3.SorobanMeta.ReturnValue
+ var getChan wire.Channel
+
+ err = getChan.FromScVal(retVal)
+ if err != nil {
+ return wire.Channel{}, errors.New("error while decoding return value")
+ }
+ return getChan, nil
+}
+
+func (a *Adjudicator) BuildWithdrawTxArgs(req pchannel.AdjudicatorReq) (xdr.ScVec, error) {
+
+ chanIDStellar := req.Tx.ID[:]
+ partyIdx := req.Idx
+ var withdrawIdx xdr.ScVal
+ if partyIdx == 0 {
+ withdrawIdx = scval.MustWrapBool(false)
+ } else if partyIdx == 1 {
+ withdrawIdx = scval.MustWrapBool(true)
+ } else {
+ return xdr.ScVec{}, errors.New("invalid party index")
+ }
+ var chanid xdr.ScBytes
+ copy(chanid, chanIDStellar)
+ channelID, err := scval.WrapScBytes(chanIDStellar)
+ if err != nil {
+ return xdr.ScVec{}, err
+ }
+
+ withdrawArgs := xdr.ScVec{
+ channelID,
+ withdrawIdx,
+ }
+ return withdrawArgs, nil
+
+}
+
+func (a *Adjudicator) withdraw(ctx context.Context, req pchannel.AdjudicatorReq) error {
+
+ perunAddress := a.GetPerunID()
+ withdrawTxArgs, err := a.BuildWithdrawTxArgs(req)
+ if err != nil {
+ return errors.New("error while building fund tx")
+ }
+ txMeta, err := a.stellarClient.InvokeAndProcessHostFunction("withdraw", withdrawTxArgs, perunAddress)
+ if err != nil {
+ return errors.New("error while invoking and processing host function: withdraw")
+ }
+
+ _, err = DecodeEventsPerun(txMeta)
+ if err != nil {
+ return errors.New("error while decoding events")
+ }
+
+ return nil
+}
+
+func (a *Adjudicator) Close(ctx context.Context, id pchannel.ID, state *pchannel.State, sigs []pwallet.Sig) error {
+
+ log.Println("Close called")
+ contractAddress := a.GetPerunID()
+ closeTxArgs, err := BuildCloseTxArgs(*state, sigs)
+ if err != nil {
+ return errors.New("error while building fund tx")
+ }
+ txMeta, err := a.stellarClient.InvokeAndProcessHostFunction("close", closeTxArgs, contractAddress)
+ if err != nil {
+ return errors.New("error while invoking and processing host function: close")
+ }
+
+ _, err = DecodeEventsPerun(txMeta)
+ if err != nil {
+ return errors.New("error while decoding events")
+ }
+
+ return nil
+}
+
+// Register registers and disputes a channel.
+func (a *Adjudicator) Register(ctx context.Context, req pchannel.AdjudicatorReq, states []pchannel.SignedState) error {
+ log.Println("Register called")
+ sigs := req.Tx.Sigs
+ state := req.Tx.State
+ err := a.Dispute(ctx, state, sigs)
+ if err != nil {
+ return fmt.Errorf("error while disputing channel: %w", err)
+ }
+ return nil
+}
+
+func (a *Adjudicator) Dispute(ctx context.Context, state *pchannel.State, sigs []pwallet.Sig) error {
+ contractAddress := a.GetPerunID()
+ closeTxArgs, err := BuildDisputeTxArgs(*state, sigs)
+ if err != nil {
+ return errors.New("error while building fund tx")
+ }
+ txMeta, err := a.stellarClient.InvokeAndProcessHostFunction("dispute", closeTxArgs, contractAddress)
+ if err != nil {
+ return errors.New("error while invoking and processing host function: dispute")
+ }
+ _, err = DecodeEventsPerun(txMeta)
+ if err != nil {
+ return errors.New("error while decoding events")
+ }
+ return nil
+}
+
+func (a *Adjudicator) ForceClose(ctx context.Context, id pchannel.ID, state *pchannel.State, sigs []pwallet.Sig, params *pchannel.Params) error {
+ log.Println("ForceClose called")
+ contractAddress := a.GetPerunID()
+ // kp := a.kpFull
+ forceCloseTxArgs, err := env.BuildForceCloseTxArgs(id)
+ if err != nil {
+ return errors.New("error while building fund tx")
+ }
+ txMeta, err := a.stellarClient.InvokeAndProcessHostFunction("force_close", forceCloseTxArgs, contractAddress)
+ if err != nil {
+ return errors.New("error while invoking and processing host function")
+ }
+ _, err = DecodeEventsPerun(txMeta)
+ if err != nil {
+ return errors.New("error while decoding events")
+ }
+ return nil
+}
+
+func BuildCloseTxArgs(state pchannel.State, sigs []pwallet.Sig) (xdr.ScVec, error) {
+
+ wireState, err := wire.MakeState(state)
+ if err != nil {
+ return xdr.ScVec{}, err
+ }
+
+ sigAXdr, err := scval.WrapScBytes(sigs[0])
+ if err != nil {
+ return xdr.ScVec{}, err
+ }
+ sigBXdr, err := scval.WrapScBytes(sigs[1])
+ if err != nil {
+ return xdr.ScVec{}, err
+ }
+ xdrState, err := wireState.ToScVal()
+ if err != nil {
+ return xdr.ScVec{}, err
+ }
+
+ fundArgs := xdr.ScVec{
+ xdrState,
+ sigAXdr,
+ sigBXdr,
+ }
+ return fundArgs, nil
+}
+
+func BuildDisputeTxArgs(state pchannel.State, sigs []pwallet.Sig) (xdr.ScVec, error) {
+
+ wireState, err := wire.MakeState(state)
+ if err != nil {
+ return xdr.ScVec{}, err
+ }
+
+ sigAXdr, err := scval.WrapScBytes(sigs[0])
+ if err != nil {
+ return xdr.ScVec{}, err
+ }
+ sigBXdr, err := scval.WrapScBytes(sigs[1])
+ if err != nil {
+ return xdr.ScVec{}, err
+ }
+ xdrState, err := wireState.ToScVal()
+ if err != nil {
+ return xdr.ScVec{}, err
+ }
+
+ fundArgs := xdr.ScVec{
+ xdrState,
+ sigAXdr,
+ sigBXdr,
+ }
+ return fundArgs, nil
+}
+
+func (a Adjudicator) Progress(ctx context.Context, req pchannel.ProgressReq) error {
+ // only relevant for AppChannels
+ return nil
+}
diff --git a/channel/adjudicator_sub.go b/channel/adjudicator_sub.go
new file mode 100644
index 0000000..42f739c
--- /dev/null
+++ b/channel/adjudicator_sub.go
@@ -0,0 +1,233 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package channel
+
+import (
+ "context"
+ "errors"
+ "github.com/stellar/go/xdr"
+ pchannel "perun.network/go-perun/channel"
+ log "perun.network/go-perun/log"
+ "perun.network/perun-stellar-backend/channel/env"
+ "perun.network/perun-stellar-backend/wire"
+ pkgsync "polycry.pt/poly-go/sync"
+ "time"
+)
+
+const (
+ DefaultBufferSize = 1024
+ DefaultSubscriptionPollingInterval = time.Duration(5) * time.Second
+)
+
+type AdjEvent interface {
+ // Sets the necessary event data from the channel information
+ EventDataFromChannel(cchanState wire.Channel, timestamp uint64) error
+ ID() pchannel.ID
+ Timeout() pchannel.Timeout
+ Version() Version
+ Tstamp() uint64
+}
+
+// AdjudicatorSub implements the AdjudicatorSubscription interface.
+type AdjEventSub struct {
+ queryChanArgs xdr.ScVec
+ stellarClient *env.StellarClient
+ chanControl wire.Control
+ cid pchannel.ID
+ perunID xdr.ScAddress
+ assetID xdr.ScAddress
+ events chan AdjEvent
+ subErrors chan error
+ err error
+ cancel context.CancelFunc
+ closer *pkgsync.Closer
+ pollInterval time.Duration
+ log log.Embedding
+}
+
+func NewAdjudicatorSub(ctx context.Context, cid pchannel.ID, stellarClient *env.StellarClient, perunID xdr.ScAddress, assetID xdr.ScAddress) (*AdjEventSub, error) {
+ getChanArgs, err := env.BuildGetChannelTxArgs(cid)
+ if err != nil {
+ return nil, err
+ }
+
+ sub := &AdjEventSub{
+ queryChanArgs: getChanArgs,
+ stellarClient: stellarClient,
+ chanControl: wire.Control{},
+ cid: cid,
+ perunID: perunID,
+ assetID: assetID,
+ events: make(chan AdjEvent, DefaultBufferSize),
+ subErrors: make(chan error, 1),
+ pollInterval: DefaultSubscriptionPollingInterval,
+ closer: new(pkgsync.Closer),
+ log: log.MakeEmbedding(log.Default()),
+ }
+
+ ctx, sub.cancel = context.WithCancel(ctx)
+ go sub.run(ctx)
+ return sub, nil
+
+}
+
+func (s *AdjEventSub) run(ctx context.Context) {
+ s.log.Log().Info("Listening for channel state changes")
+ chanControl, err := s.getChanControl()
+ if err != nil {
+ s.subErrors <- err
+ }
+ s.chanControl = chanControl
+ finish := func(err error) {
+ s.err = err
+ close(s.events)
+ }
+polling:
+ for {
+ s.log.Log().Debug("AdjudicatorSub is listening for Adjudicator Events")
+ select {
+ case err := <-s.subErrors:
+ finish(err)
+ return
+ case <-ctx.Done():
+ finish(nil)
+ return
+ case <-time.After(s.pollInterval):
+
+ newChanControl, err := s.getChanControl()
+
+ if err != nil {
+
+ s.subErrors <- err
+ }
+ adjEvent, err := DifferencesInControls(s.chanControl, newChanControl)
+ if err != nil {
+ s.subErrors <- err
+ }
+
+ if adjEvent == nil {
+ s.chanControl = newChanControl
+ s.log.Log().Debug("No events yet, continuing polling...")
+ continue polling
+
+ } else {
+ s.log.Log().Debug("Event detected, evaluating events...")
+ s.log.Log().Debugf("Found event: %v", adjEvent)
+ s.events <- adjEvent
+ return
+ }
+ }
+ }
+}
+
+func (s *AdjEventSub) GetChannelState(chanArgs xdr.ScVec) (wire.Channel, error) {
+ contractAddress := s.perunID
+ txMeta, err := s.stellarClient.InvokeAndProcessHostFunction("get_channel", chanArgs, contractAddress)
+ if err != nil {
+ return wire.Channel{}, errors.New("error while processing and submitting get_channel tx")
+ }
+
+ retVal := txMeta.V3.SorobanMeta.ReturnValue
+ var getChan wire.Channel
+
+ err = getChan.FromScVal(retVal)
+ if err != nil {
+ return wire.Channel{}, errors.New("error while decoding return value")
+ }
+ return getChan, nil
+
+}
+
+func (s *AdjEventSub) getChanControl() (wire.Control, error) {
+ getChanArgs, err := env.BuildGetChannelTxArgs(s.cid)
+ if err != nil {
+ return wire.Control{}, err
+ }
+
+ chanParams, err := s.GetChannelState(getChanArgs)
+ if err != nil {
+ return wire.Control{}, err
+ }
+ chanControl := chanParams.Control
+
+ return chanControl, nil
+}
+
+func DifferencesInControls(controlCurr, controlNext wire.Control) (AdjEvent, error) {
+
+ if controlCurr.FundedA != controlNext.FundedA {
+ if controlCurr.FundedA {
+ return nil, errors.New("channel cannot be unfunded A before withdrawal")
+ }
+ if controlNext.WithdrawnA && controlNext.WithdrawnB {
+ return &FundEvent{}, nil
+ }
+ }
+
+ if controlCurr.FundedB != controlNext.FundedB {
+ if controlCurr.FundedB {
+ return nil, errors.New("channel cannot be unfunded B before withdrawal")
+ }
+ if controlNext.WithdrawnA && controlNext.WithdrawnB {
+ return &FundEvent{}, nil
+ }
+ }
+
+ if controlCurr.Closed != controlNext.Closed {
+ if controlCurr.Closed {
+ return nil, errors.New("channel cannot be reopened after closing")
+ }
+ if !controlCurr.Closed && controlNext.Closed {
+ return &CloseEvent{}, nil
+ }
+ return &CloseEvent{}, nil
+ }
+
+ if controlCurr.WithdrawnA != controlNext.WithdrawnA {
+ if controlCurr.WithdrawnA {
+ return nil, errors.New("channel cannot be unwithdrawn")
+ }
+ if controlNext.WithdrawnA && controlNext.WithdrawnB {
+ return &WithdrawnEvent{}, nil
+ }
+ }
+
+ if controlCurr.WithdrawnB != controlNext.WithdrawnB {
+ if controlCurr.WithdrawnB {
+ return nil, errors.New("channel cannot be unwithdrawn")
+ }
+ if controlNext.WithdrawnA && controlNext.WithdrawnB {
+ return &WithdrawnEvent{}, nil
+ }
+ }
+
+ if controlCurr.Disputed != controlNext.Disputed {
+ if controlCurr.Disputed {
+ return nil, errors.New("channel cannot be undisputed")
+ }
+ return &DisputedEvent{}, nil
+ }
+
+ return nil, nil
+}
+
+func IdenticalControls(controlCurr, controlNext wire.Control) bool {
+ return controlCurr.FundedA == controlNext.FundedA &&
+ controlCurr.FundedB == controlNext.FundedB &&
+ controlCurr.Closed == controlNext.Closed &&
+ controlCurr.WithdrawnA == controlNext.WithdrawnA &&
+ controlCurr.WithdrawnB == controlNext.WithdrawnB &&
+ controlCurr.Disputed == controlNext.Disputed
+}
diff --git a/channel/adjudicator_test.go b/channel/adjudicator_test.go
new file mode 100644
index 0000000..93d2a20
--- /dev/null
+++ b/channel/adjudicator_test.go
@@ -0,0 +1,101 @@
+// Copyright 2024 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//go:build integration
+// +build integration
+
+package channel_test
+
+import (
+ "github.com/stretchr/testify/require"
+ pchannel "perun.network/go-perun/channel"
+ pwallet "perun.network/go-perun/wallet"
+ "perun.network/perun-stellar-backend/channel"
+ chtest "perun.network/perun-stellar-backend/channel/test"
+ "testing"
+)
+
+func TestHappyChannel(t *testing.T) {
+ setup := chtest.NewTestSetup(t)
+ stellarAsset := setup.GetTokenAsset()
+ accs := setup.GetAccounts()
+ addrAlice := accs[0].Address()
+ addrBob := accs[1].Address()
+ addrList := []pwallet.Address{addrAlice, addrBob}
+ perunParams, perunState := chtest.NewParamsWithAddressStateWithAsset(t, addrList, stellarAsset)
+
+ freqAlice := pchannel.NewFundingReq(perunParams, perunState, 0, perunState.Balances)
+ freqBob := pchannel.NewFundingReq(perunParams, perunState, 1, perunState.Balances)
+
+ freqs := []*pchannel.FundingReq{freqAlice, freqBob}
+
+ funders := setup.GetFunders()
+ ctx := setup.NewCtx()
+ err := chtest.FundAll(ctx, funders, freqs)
+ require.NoError(t, err)
+
+ // funding complete
+
+ // Withdrawal
+ {
+ adjAlice := setup.GetAdjudicators()[0]
+ adjBob := setup.GetAdjudicators()[1]
+
+ ctxAliceWithdraw := setup.NewCtx()
+ ctxBobWithdraw := setup.NewCtx()
+
+ adjState := perunState
+ next := adjState.Clone()
+ next.Version++
+ next.IsFinal = true
+ encodedState, err := channel.EncodeState(next)
+ require.NoError(t, err)
+ signAlice, err := accs[0].SignData(encodedState)
+ require.NoError(t, err)
+ signBob, err := accs[1].SignData(encodedState)
+ require.NoError(t, err)
+ sigs := []pwallet.Sig{signAlice, signBob}
+ tx := pchannel.Transaction{State: next, Sigs: sigs}
+
+ reqAlice := pchannel.AdjudicatorReq{
+ Params: perunParams,
+ Tx: tx,
+ Acc: accs[0],
+ Idx: pchannel.Index(0),
+ Secondary: false}
+
+ reqBob := pchannel.AdjudicatorReq{
+ Params: perunParams,
+ Tx: tx,
+ Acc: accs[1],
+ Idx: pchannel.Index(1),
+ Secondary: false}
+
+ require.NoError(t, adjAlice.Withdraw(ctxAliceWithdraw, reqAlice, nil))
+ stellarChanAlice, err := adjAlice.GetChannelState(ctx, next)
+
+ require.True(t, stellarChanAlice.Control.WithdrawnA)
+
+ require.NoError(t, err)
+ require.NoError(t, adjBob.Withdraw(ctx, reqBob, nil))
+
+ stellarChanBob, err := adjBob.GetChannelState(ctxBobWithdraw, next)
+
+ require.NoError(t, err)
+
+ require.True(t, stellarChanBob.Control.WithdrawnB)
+
+ }
+
+}
diff --git a/channel/backend.go b/channel/backend.go
index 59ec995..80b5551 100644
--- a/channel/backend.go
+++ b/channel/backend.go
@@ -1,3 +1,17 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
package channel
import (
diff --git a/channel/deploy.go b/channel/deploy.go
new file mode 100644
index 0000000..cfba7aa
--- /dev/null
+++ b/channel/deploy.go
@@ -0,0 +1,81 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package channel
+
+import (
+ "crypto/sha256"
+ "github.com/stellar/go/txnbuild"
+ "github.com/stellar/go/xdr"
+ "os"
+)
+
+const PerunContractPath = "../testdata/perun_soroban_contract.wasm"
+
+func AssembleInstallContractCodeOp(sourceAccount string, wasmFileName string) *txnbuild.InvokeHostFunction {
+ // Assemble the InvokeHostFunction UploadContractWasm operation:
+ // CAP-0047 - https://github.com/stellar/stellar-protocol/blob/master/core/cap-0047.md#creating-a-contract-using-invokehostfunctionop
+
+ contract, err := os.ReadFile(wasmFileName)
+ if err != nil {
+ panic(err)
+ }
+
+ return &txnbuild.InvokeHostFunction{
+ HostFunction: xdr.HostFunction{
+ Type: xdr.HostFunctionTypeHostFunctionTypeUploadContractWasm,
+ Wasm: &contract,
+ },
+ SourceAccount: sourceAccount,
+ }
+}
+
+func AssembleCreateContractOp(sourceAccount string, wasmFileName string, contractSalt string, passPhrase string) *txnbuild.InvokeHostFunction {
+ // Assemble the InvokeHostFunction CreateContract operation:
+ // CAP-0047 - https://github.com/stellar/stellar-protocol/blob/master/core/cap-0047.md#creating-a-contract-using-invokehostfunctionop
+
+ contract, err := os.ReadFile(wasmFileName)
+ if err != nil {
+ panic(err)
+ }
+
+ salt := sha256.Sum256([]byte(contractSalt))
+ saltParameter := xdr.Uint256(salt)
+
+ accountId := xdr.MustAddress(sourceAccount)
+ contractHash := xdr.Hash(sha256.Sum256(contract))
+
+ return &txnbuild.InvokeHostFunction{
+ HostFunction: xdr.HostFunction{
+ Type: xdr.HostFunctionTypeHostFunctionTypeCreateContract,
+ CreateContract: &xdr.CreateContractArgs{
+ ContractIdPreimage: xdr.ContractIdPreimage{
+ Type: xdr.ContractIdPreimageTypeContractIdPreimageFromAddress,
+ FromAddress: &xdr.ContractIdPreimageFromAddress{
+ Address: xdr.ScAddress{
+ Type: xdr.ScAddressTypeScAddressTypeAccount,
+ AccountId: &accountId,
+ },
+ Salt: saltParameter,
+ },
+ },
+ Executable: xdr.ContractExecutable{
+ Type: xdr.ContractExecutableTypeContractExecutableWasm,
+ WasmHash: &contractHash,
+ },
+ },
+ },
+ SourceAccount: sourceAccount,
+ }
+}
diff --git a/channel/doc.go b/channel/doc.go
new file mode 100644
index 0000000..b7c939f
--- /dev/null
+++ b/channel/doc.go
@@ -0,0 +1,18 @@
+// Copyright 2024 - See NOTICE file for copyright holders.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package channel contains all relevant components to generate, utilize and conclude payment channels on the Stellar blockchain.
+// These main components consist of the Funder and Adjudicator interfaces that govern the interaction between the channel users.
+// Additionally, the AdjEventSub interface processes the emitted events from the Soroban smart contracts, using the interfaces from go-perun.
+package channel
diff --git a/channel/env/client.go b/channel/env/client.go
new file mode 100644
index 0000000..d24a11c
--- /dev/null
+++ b/channel/env/client.go
@@ -0,0 +1,98 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package env
+
+import (
+ "github.com/stellar/go/clients/horizonclient"
+ "github.com/stellar/go/keypair"
+ "github.com/stellar/go/protocols/horizon"
+ "github.com/stellar/go/txnbuild"
+)
+
+const HorizonURL = "http://localhost:8000"
+const NETWORK_PASSPHRASE = "Standalone Network ; February 2017"
+
+type StellarClient struct {
+ hzClient *horizonclient.Client
+ keyHolder keyHolder
+}
+
+type keyHolder struct {
+ kp *keypair.Full
+}
+
+func NewHorizonClient() *horizonclient.Client {
+ return &horizonclient.Client{HorizonURL: HorizonURL}
+}
+
+func newKeyHolder(kp *keypair.Full) keyHolder {
+ return keyHolder{kp}
+}
+
+func NewStellarClient(kp *keypair.Full) *StellarClient {
+ return &StellarClient{
+ hzClient: NewHorizonClient(),
+ keyHolder: newKeyHolder(kp),
+ }
+}
+
+func NewHorizonMasterClient() *StellarClient {
+ sourceKey := keypair.Root(NETWORK_PASSPHRASE)
+ return &StellarClient{
+ hzClient: &horizonclient.Client{HorizonURL: HorizonURL},
+ keyHolder: newKeyHolder(sourceKey),
+ }
+}
+
+func (c *StellarClient) GetHorizonClient() *horizonclient.Client {
+ return c.hzClient
+}
+
+func (h *StellarClient) GetAccount() (horizon.Account, error) {
+ accountReq := horizonclient.AccountRequest{AccountID: h.GetAddress()}
+ hzAccount, err := h.hzClient.AccountDetail(accountReq)
+ if err != nil {
+ return hzAccount, err
+ }
+ return hzAccount, nil
+}
+
+func (s *StellarClient) GetAddress() string {
+ return s.keyHolder.kp.Address()
+}
+
+func (s *StellarClient) GetHorizonAccount() (horizon.Account, error) {
+ accountReq := horizonclient.AccountRequest{AccountID: s.GetAddress()}
+ hzAccount, err := s.hzClient.AccountDetail(accountReq)
+ if err != nil {
+ return hzAccount, err
+ }
+ return hzAccount, nil
+}
+
+func (s *StellarClient) CreateSignedTxFromParams(txParams txnbuild.TransactionParams) (*txnbuild.Transaction, error) {
+
+ txUnsigned, err := txnbuild.NewTransaction(txParams)
+ if err != nil {
+ return nil, err
+ }
+
+ tx, err := txUnsigned.Sign(NETWORK_PASSPHRASE, s.keyHolder.kp)
+ if err != nil {
+ return nil, err
+ }
+
+ return tx, nil
+}
diff --git a/channel/env/doc.go b/channel/env/doc.go
new file mode 100644
index 0000000..97b57fd
--- /dev/null
+++ b/channel/env/doc.go
@@ -0,0 +1,16 @@
+// Copyright 2024 - See NOTICE file for copyright holders.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package env provides the functionality to connect to the Stellar blockchain and broadcast transactions to the network and decode its response.
+package env
diff --git a/channel/env/transaction.go b/channel/env/transaction.go
new file mode 100644
index 0000000..211a502
--- /dev/null
+++ b/channel/env/transaction.go
@@ -0,0 +1,323 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package env
+
+import (
+ "context"
+ "errors"
+ "github.com/creachadair/jrpc2"
+ "github.com/creachadair/jrpc2/jhttp"
+ "github.com/stellar/go/clients/horizonclient"
+ "github.com/stellar/go/keypair"
+ "github.com/stellar/go/protocols/horizon"
+ "github.com/stellar/go/txnbuild"
+ "github.com/stellar/go/xdr"
+ pchannel "perun.network/go-perun/channel"
+ "perun.network/perun-stellar-backend/wire"
+ "perun.network/perun-stellar-backend/wire/scval"
+ "strconv"
+ "sync"
+ "time"
+)
+
+var sharedMtx sync.Mutex
+
+const sorobanRPCPort = 8000
+
+type RPCSimulateTxResponse struct {
+ Error string `json:"error,omitempty"`
+ TransactionData string `json:"transactionData"`
+ Results []RPCSimulateHostFunctionResult `json:"results"`
+ MinResourceFee int64 `json:"minResourceFee,string"`
+}
+
+type RPCSimulateHostFunctionResult struct {
+ Auth []string `json:"auth"`
+ XDR string `json:"xdr"`
+}
+
+func PreflightHostFunctions(hzClient *horizonclient.Client,
+ sourceAccount txnbuild.Account, function txnbuild.InvokeHostFunction,
+) (txnbuild.InvokeHostFunction, int64) {
+ result, transactionData := simulateTransaction(hzClient, sourceAccount, &function)
+
+ function.Ext = xdr.TransactionExt{
+ V: 1,
+ SorobanData: &transactionData,
+ }
+ var funAuth []xdr.SorobanAuthorizationEntry
+ for _, res := range result.Results {
+ var decodedRes xdr.ScVal
+ err := xdr.SafeUnmarshalBase64(res.XDR, &decodedRes)
+ if err != nil {
+ panic(err)
+ }
+ for _, authBase64 := range res.Auth {
+ var authEntry xdr.SorobanAuthorizationEntry
+ err = xdr.SafeUnmarshalBase64(authBase64, &authEntry)
+ if err != nil {
+ panic(err)
+ }
+ funAuth = append(funAuth, authEntry)
+ }
+ }
+ function.Auth = funAuth
+
+ return function, result.MinResourceFee
+}
+
+func simulateTransaction(hzClient *horizonclient.Client,
+ sourceAccount txnbuild.Account, op txnbuild.Operation,
+) (RPCSimulateTxResponse, xdr.SorobanTransactionData) {
+ // Before preflighting, make sure soroban-rpc is in sync with Horizon
+ root, err := hzClient.Root()
+ if err != nil {
+ panic(err)
+ }
+ syncWithSorobanRPC(uint32(root.HorizonSequence))
+
+ ch := jhttp.NewChannel("http://localhost:"+strconv.Itoa(sorobanRPCPort)+"/soroban/rpc", nil)
+ sorobanRPCClient := jrpc2.NewClient(ch, nil)
+ txParams := GetBaseTransactionParamsWithFee(sourceAccount, txnbuild.MinBaseFee, op)
+ txParams.IncrementSequenceNum = false
+ tx, err := txnbuild.NewTransaction(txParams)
+ if err != nil {
+ panic(err)
+ }
+ base64, err := tx.Base64()
+ if err != nil {
+ panic(err)
+ }
+ result := RPCSimulateTxResponse{}
+ err = sorobanRPCClient.CallResult(context.Background(), "simulateTransaction", struct {
+ Transaction string `json:"transaction"`
+ }{base64}, &result)
+ if err != nil {
+ panic(err)
+ }
+ var transactionData xdr.SorobanTransactionData
+ err = xdr.SafeUnmarshalBase64(result.TransactionData, &transactionData)
+ if err != nil {
+ panic(err)
+ }
+ return result, transactionData
+}
+func syncWithSorobanRPC(ledgerToWaitFor uint32) {
+ for j := 0; j < 20; j++ {
+ result := struct {
+ Sequence uint32 `json:"sequence"`
+ }{}
+ ch := jhttp.NewChannel("http://localhost:"+strconv.Itoa(sorobanRPCPort)+"/soroban/rpc", nil) ///soroban/rpc:
+ sorobanRPCClient := jrpc2.NewClient(ch, nil)
+ err := sorobanRPCClient.CallResult(context.Background(), "getLatestLedger", nil, &result)
+ if err != nil {
+ panic(err)
+ }
+ if result.Sequence >= ledgerToWaitFor {
+ return
+ }
+ time.Sleep(500 * time.Millisecond)
+ }
+ panic("Time out waiting for soroban-rpc to sync")
+}
+
+func GetBaseTransactionParamsWithFee(source txnbuild.Account, fee int64, ops ...txnbuild.Operation) txnbuild.TransactionParams {
+ return txnbuild.TransactionParams{
+ SourceAccount: source,
+ Operations: ops,
+ BaseFee: fee,
+ Preconditions: txnbuild.Preconditions{TimeBounds: txnbuild.NewInfiniteTimeout()},
+ IncrementSequenceNum: true,
+ }
+}
+
+func CreateSignedTransactionWithParams(signers []*keypair.Full, txParams txnbuild.TransactionParams,
+) (*txnbuild.Transaction, error) {
+ tx, err := txnbuild.NewTransaction(txParams)
+ if err != nil {
+ return nil, err
+ }
+
+ for _, signer := range signers {
+ tx, err = tx.Sign(NETWORK_PASSPHRASE, signer)
+ if err != nil {
+ return nil, err
+ }
+ }
+ return tx, nil
+}
+
+func BuildOpenTxArgs(params *pchannel.Params, state *pchannel.State) (xdr.ScVec, error) {
+ paramsStellar, err := wire.MakeParams(*params)
+ if err != nil {
+ return xdr.ScVec{}, err
+ }
+ stateStellar, err := wire.MakeState(*state)
+ if err != nil {
+ return xdr.ScVec{}, err
+ }
+ paramsXdr, err := paramsStellar.ToScVal()
+ if err != nil {
+ return xdr.ScVec{}, err
+ }
+ stateXdr, err := stateStellar.ToScVal()
+ if err != nil {
+ return xdr.ScVec{}, err
+ }
+ openArgs := xdr.ScVec{
+ paramsXdr,
+ stateXdr,
+ }
+ return openArgs, nil
+}
+
+func BuildMintTokenArgs(mintTo xdr.ScAddress, amount xdr.ScVal) (xdr.ScVec, error) {
+
+ mintToSc, err := scval.WrapScAddress(mintTo)
+ if err != nil {
+ return xdr.ScVec{}, err
+ }
+
+ MintTokenArgs := xdr.ScVec{
+ mintToSc,
+ amount,
+ }
+
+ return MintTokenArgs, nil
+}
+
+func BuildGetTokenBalanceArgs(balanceOf xdr.ScAddress) (xdr.ScVec, error) {
+
+ balanceOfSc, err := scval.WrapScAddress(balanceOf)
+ if err != nil {
+ return xdr.ScVec{}, err
+ }
+
+ GetTokenBalanceArgs := xdr.ScVec{
+ balanceOfSc,
+ }
+
+ return GetTokenBalanceArgs, nil
+}
+
+func BuildFundTxArgs(chanID pchannel.ID, funderIdx bool) (xdr.ScVec, error) {
+
+ chanIDStellar := chanID[:]
+ var chanid xdr.ScBytes
+ copy(chanid[:], chanIDStellar)
+ channelID, err := scval.WrapScBytes(chanIDStellar)
+ if err != nil {
+ return xdr.ScVec{}, err
+ }
+
+ userIdStellar, err := scval.WrapBool(funderIdx)
+ if err != nil {
+ return xdr.ScVec{}, err
+ }
+
+ fundArgs := xdr.ScVec{
+ channelID,
+ userIdStellar,
+ }
+ return fundArgs, nil
+}
+
+func BuildGetChannelTxArgs(chanID pchannel.ID) (xdr.ScVec, error) {
+
+ chanIDStellar := chanID[:]
+ var chanid xdr.ScBytes
+ copy(chanid[:], chanIDStellar)
+ channelID, err := scval.WrapScBytes(chanIDStellar)
+ if err != nil {
+ return xdr.ScVec{}, err
+ }
+
+ getChannelArgs := xdr.ScVec{
+ channelID,
+ }
+ return getChannelArgs, nil
+}
+
+func BuildForceCloseTxArgs(chanID pchannel.ID) (xdr.ScVec, error) {
+
+ chanIDStellar := chanID[:]
+ var chanid xdr.ScBytes
+ copy(chanid[:], chanIDStellar)
+ channelID, err := scval.WrapScBytes(chanIDStellar)
+ if err != nil {
+ return xdr.ScVec{}, err
+ }
+
+ getChannelArgs := xdr.ScVec{
+ channelID,
+ }
+ return getChannelArgs, nil
+}
+
+func (s *StellarClient) InvokeAndProcessHostFunction(fname string, callTxArgs xdr.ScVec, contractAddr xdr.ScAddress) (xdr.TransactionMeta, error) {
+ sharedMtx.Lock()
+ defer sharedMtx.Unlock()
+ fnameXdr := xdr.ScSymbol(fname)
+ hzAcc, err := s.GetHorizonAccount()
+ if err != nil {
+ return xdr.TransactionMeta{}, err
+ }
+ hzClient := s.GetHorizonClient()
+
+ invokeHostFunctionOp := BuildContractCallOp(hzAcc, fnameXdr, callTxArgs, contractAddr)
+ preFlightOp, minFee := PreflightHostFunctions(hzClient, &hzAcc, *invokeHostFunctionOp)
+
+ txParams := GetBaseTransactionParamsWithFee(&hzAcc, minFee, &preFlightOp)
+ txSigned, err := s.CreateSignedTxFromParams(txParams)
+ if err != nil {
+ return xdr.TransactionMeta{}, err
+ }
+ tx, err := hzClient.SubmitTransaction(txSigned)
+ if err != nil {
+ return xdr.TransactionMeta{}, err
+ }
+ // Decode transaction metadata
+ txMeta, err := DecodeTxMeta(tx)
+ if err != nil {
+ return xdr.TransactionMeta{}, errors.New("error while decoding tx meta")
+ }
+ _ = txMeta.V3.SorobanMeta.ReturnValue
+
+ return txMeta, nil
+}
+
+func BuildContractCallOp(caller horizon.Account, fName xdr.ScSymbol, callArgs xdr.ScVec, contractIdAddress xdr.ScAddress) *txnbuild.InvokeHostFunction {
+
+ return &txnbuild.InvokeHostFunction{
+ HostFunction: xdr.HostFunction{
+ Type: xdr.HostFunctionTypeHostFunctionTypeInvokeContract,
+ InvokeContract: &xdr.InvokeContractArgs{
+ ContractAddress: contractIdAddress,
+ FunctionName: fName,
+ Args: callArgs,
+ },
+ },
+ SourceAccount: caller.AccountID,
+ }
+}
+func DecodeTxMeta(tx horizon.Transaction) (xdr.TransactionMeta, error) {
+ var transactionMeta xdr.TransactionMeta
+ err := xdr.SafeUnmarshalBase64(tx.ResultMetaXdr, &transactionMeta)
+ if err != nil {
+ return xdr.TransactionMeta{}, err
+ }
+
+ return transactionMeta, nil
+}
diff --git a/channel/event.go b/channel/event.go
new file mode 100644
index 0000000..d91bc32
--- /dev/null
+++ b/channel/event.go
@@ -0,0 +1,403 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package channel
+
+import (
+ "errors"
+ "fmt"
+ "github.com/stellar/go/xdr"
+ pchannel "perun.network/go-perun/channel"
+ "perun.network/perun-stellar-backend/wire"
+ "time"
+)
+
+type Version = uint64
+type Event = xdr.ContractEvent
+type EventType int
+
+const (
+ EventTypeOpen EventType = iota
+ EventTypeFundChannel // participant/s funding channel
+ EventTypeFundedChannel // participants have funded channel
+ EventTypeClosed // channel closed -> withdrawing enabled
+ EventTypeWithdrawing // participant/s withdrawing
+ EventTypeWithdrawn // participants have withdrawn
+ EventTypeForceClosed // participant has force closed the channel
+ EventTypeDisputed // participant has disputed the channel
+)
+
+const AssertPerunSymbol = "perun"
+
+var (
+ STELLAR_PERUN_CHANNEL_CONTRACT_TOPICS = map[xdr.ScSymbol]EventType{
+ xdr.ScSymbol("open"): EventTypeOpen,
+ xdr.ScSymbol("fund"): EventTypeFundChannel,
+ xdr.ScSymbol("fund_c"): EventTypeFundedChannel,
+ xdr.ScSymbol("closed"): EventTypeClosed,
+ xdr.ScSymbol("withdraw"): EventTypeWithdrawing,
+ xdr.ScSymbol("pay_c"): EventTypeWithdrawn,
+ xdr.ScSymbol("f_closed"): EventTypeForceClosed,
+ xdr.ScSymbol("dispute"): EventTypeDisputed,
+ }
+
+ ErrNotStellarPerunContract = errors.New("event was not from a Perun payment channel contract")
+ ErrEventUnsupported = errors.New("this type of event is unsupported")
+ ErrEventIntegrity = errors.New("contract ID does not match payment channel + passphrase")
+)
+
+type controlsState map[string]bool
+
+type (
+ PerunEvent interface {
+ ID() pchannel.ID
+ Timeout() pchannel.Timeout
+ Version() Version
+ }
+
+ OpenEvent struct {
+ Channel wire.Channel
+ IDV pchannel.ID
+ VersionV Version
+ Timestamp uint64
+ }
+ FundEvent struct {
+ Channel wire.Channel
+ IDV pchannel.ID
+ VersionV Version
+ Timestamp uint64
+ }
+
+ CloseEvent struct {
+ Channel wire.Channel
+ IDV pchannel.ID
+ VersionV Version
+ Timestamp uint64
+ }
+
+ WithdrawnEvent struct {
+ Channel wire.Channel
+ IDV pchannel.ID
+ VersionV Version
+ Timestamp uint64
+ }
+
+ DisputedEvent struct {
+ Channel wire.Channel
+ IDV pchannel.ID
+ VersionV Version
+ Timestamp uint64
+ }
+)
+
+type StellarEvent struct {
+ Type EventType
+ ChannelState wire.Channel
+}
+
+func (e *StellarEvent) GetType() EventType {
+ return e.Type
+}
+
+func (e *OpenEvent) GetChannel() wire.Channel {
+ return e.Channel
+}
+
+func (e *OpenEvent) ID() pchannel.ID {
+ return e.IDV
+}
+func (e *OpenEvent) Version() Version {
+ return e.VersionV
+}
+func (e *OpenEvent) Tstamp() uint64 {
+ return e.Timestamp
+}
+
+func (e *OpenEvent) Timeout() pchannel.Timeout {
+ when := time.Now().Add(10 * time.Second)
+ pollInterval := 1 * time.Second
+ return NewTimeout(when, pollInterval)
+}
+
+func (e *WithdrawnEvent) GetChannel() wire.Channel {
+ return e.Channel
+}
+
+func (e *WithdrawnEvent) ID() pchannel.ID {
+ return e.IDV
+}
+func (e *WithdrawnEvent) Version() Version {
+ return e.VersionV
+}
+func (e WithdrawnEvent) Tstamp() uint64 {
+ return e.Timestamp
+}
+
+func (e *WithdrawnEvent) Timeout() pchannel.Timeout {
+ when := time.Now().Add(10 * time.Second)
+ pollInterval := 1 * time.Second
+ return NewTimeout(when, pollInterval)
+}
+
+func (e *CloseEvent) GetChannel() wire.Channel {
+ return e.Channel
+}
+
+func (e *CloseEvent) ID() pchannel.ID {
+ return e.IDV
+}
+func (e *CloseEvent) Version() Version {
+ return e.VersionV
+}
+func (e *CloseEvent) Tstamp() uint64 {
+ return e.Timestamp
+}
+
+func (e *CloseEvent) Timeout() pchannel.Timeout {
+ when := time.Now().Add(10 * time.Second)
+ pollInterval := 1 * time.Second
+ return NewTimeout(when, pollInterval)
+}
+
+func (e *FundEvent) Timeout() pchannel.Timeout {
+ when := time.Now().Add(10 * time.Second)
+ pollInterval := 1 * time.Second
+ return NewTimeout(when, pollInterval)
+}
+
+func (e *FundEvent) ID() pchannel.ID {
+ return e.IDV
+}
+func (e *FundEvent) Version() Version {
+ return e.VersionV
+}
+func (e *FundEvent) Tstamp() uint64 {
+ return e.Timestamp
+}
+
+func (e *DisputedEvent) Timeout() pchannel.Timeout {
+ when := time.Now().Add(10 * time.Second)
+ pollInterval := 1 * time.Second
+ return NewTimeout(when, pollInterval)
+}
+
+func (e *DisputedEvent) ID() pchannel.ID {
+ return e.IDV
+}
+func (e *DisputedEvent) Version() Version {
+ return e.VersionV
+}
+func (e *DisputedEvent) Tstamp() uint64 {
+ return e.Timestamp
+}
+
+func DecodeEventsPerun(txMeta xdr.TransactionMeta) ([]PerunEvent, error) {
+ evs := make([]PerunEvent, 0)
+
+ txEvents := txMeta.V3.SorobanMeta.Events
+
+ for _, ev := range txEvents {
+ sev := StellarEvent{}
+ topics := ev.Body.V0.Topics
+
+ if len(topics) < 2 {
+ return []PerunEvent{}, ErrNotStellarPerunContract
+ }
+ perunString, ok := topics[0].GetSym()
+
+ if perunString == "transfer" {
+ continue
+ }
+
+ if perunString != AssertPerunSymbol {
+ return []PerunEvent{}, ErrNotStellarPerunContract
+ }
+ if !ok {
+ return []PerunEvent{}, ErrNotStellarPerunContract
+ }
+
+ fn, ok := topics[1].GetSym()
+ if !ok {
+ return []PerunEvent{}, ErrNotStellarPerunContract
+ }
+
+ if eventType, found := STELLAR_PERUN_CHANNEL_CONTRACT_TOPICS[fn]; !found {
+ return []PerunEvent{}, ErrNotStellarPerunContract
+ } else {
+ sev.Type = eventType
+ }
+
+ switch sev.GetType() {
+ case EventTypeOpen:
+
+ openEventchanStellar, err := GetChannelFromEvents(ev.Body.V0.Data)
+ if err != nil {
+ return []PerunEvent{}, err
+ }
+
+ controlsOpen := initControlState(openEventchanStellar.Control)
+
+ err = checkOpen(controlsOpen)
+ if err != nil {
+ fmt.Println(err)
+ }
+
+ openEvent := OpenEvent{
+ Channel: openEventchanStellar,
+ }
+
+ evs = append(evs, &openEvent)
+
+ case EventTypeFundChannel:
+ fundEventchanStellar, _, err := GetChannelBoolFromEvents(ev.Body.V0.Data)
+ if err != nil {
+ return []PerunEvent{}, err
+ }
+
+ fundEvent := FundEvent{
+ Channel: fundEventchanStellar,
+ }
+ evs = append(evs, &fundEvent)
+ case EventTypeClosed:
+ closedEventchanStellar, err := GetChannelFromEvents(ev.Body.V0.Data)
+ if err != nil {
+ return []PerunEvent{}, err
+ }
+
+ closeEvent := CloseEvent{
+ Channel: closedEventchanStellar,
+ }
+ evs = append(evs, &closeEvent)
+ case EventTypeWithdrawn:
+ withdrawnEventchanStellar, err := GetChannelFromEvents(ev.Body.V0.Data)
+ if err != nil {
+ return []PerunEvent{}, err
+ }
+ withdrawnEvent := WithdrawnEvent{
+ Channel: withdrawnEventchanStellar,
+ }
+ evs = append(evs, &withdrawnEvent)
+ }
+
+ }
+ return evs, nil
+}
+
+func initControlState(control wire.Control) controlsState {
+ return controlsState{
+ "ControlFundedA": control.FundedA,
+ "ControlFundedB": control.FundedB,
+ "ControlClosed": control.Closed,
+ "ControlWithdrawnA": control.WithdrawnA,
+ "ControlWithdrawnB": control.WithdrawnB,
+ "ControlDisputed": control.Disputed,
+ }
+}
+
+func GetChannelFromEvents(evData xdr.ScVal) (wire.Channel, error) {
+ var chanStellar wire.Channel
+
+ err := chanStellar.FromScVal(evData)
+ if err != nil {
+ return wire.Channel{}, err
+ }
+
+ if err != nil {
+ return wire.Channel{}, err
+
+ }
+
+ return chanStellar, nil
+}
+
+func GetChannelBoolFromEvents(evData xdr.ScVal) (wire.Channel, bool, error) {
+ var chanStellar wire.Channel
+
+ mvec, ok := evData.GetVec()
+ if !ok {
+ return wire.Channel{}, false, errors.New("expected vec")
+ }
+
+ vecVals := *mvec
+ eventBool := vecVals[1]
+ eventControl := vecVals[0]
+ err := chanStellar.FromScVal(eventControl)
+ if err != nil {
+ return wire.Channel{}, false, err
+ }
+
+ boolIdx, ok := eventBool.GetB()
+ if !ok {
+ return wire.Channel{}, false, errors.New("expected bool")
+ }
+
+ return chanStellar, boolIdx, nil
+}
+
+func checkOpen(cState controlsState) error {
+ for key, val := range cState {
+ if val {
+ return errors.New(key + " is not false")
+ }
+ }
+ return nil
+}
+
+func (e *CloseEvent) EventDataFromChannel(chanState wire.Channel, timestamp uint64) error {
+
+ chanID := chanState.State.ChannelID
+ var cid [32]byte
+ copy(cid[:], chanID[:])
+
+ e.IDV = cid
+ e.Timestamp = timestamp
+ e.Channel = chanState
+ return nil
+}
+
+func (e *FundEvent) EventDataFromChannel(chanState wire.Channel, timestamp uint64) error {
+
+ chanID := chanState.State.ChannelID
+ var cid [32]byte
+ copy(cid[:], chanID[:])
+
+ e.IDV = cid
+ e.Timestamp = timestamp
+ e.Channel = chanState
+ return nil
+}
+
+func (e *WithdrawnEvent) EventDataFromChannel(chanState wire.Channel, timestamp uint64) error {
+
+ chanID := chanState.State.ChannelID
+ var cid [32]byte
+ copy(cid[:], chanID[:])
+
+ e.IDV = cid
+ e.Timestamp = timestamp
+ e.Channel = chanState
+ return nil
+}
+
+func (e *DisputedEvent) EventDataFromChannel(chanState wire.Channel, timestamp uint64) error {
+
+ chanID := chanState.State.ChannelID
+ var cid [32]byte
+ copy(cid[:], chanID[:])
+
+ e.IDV = cid
+ e.Timestamp = timestamp
+ e.Channel = chanState
+ return nil
+}
diff --git a/channel/funder.go b/channel/funder.go
new file mode 100644
index 0000000..92bddfb
--- /dev/null
+++ b/channel/funder.go
@@ -0,0 +1,232 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package channel
+
+import (
+ "context"
+ "errors"
+ "github.com/stellar/go/xdr"
+ "log"
+ pchannel "perun.network/go-perun/channel"
+ "perun.network/perun-stellar-backend/channel/env"
+ "perun.network/perun-stellar-backend/wallet"
+ "perun.network/perun-stellar-backend/wire"
+ "time"
+)
+
+const MaxIterationsUntilAbort = 20
+const DefaultPollingInterval = time.Duration(6) * time.Second
+
+type Funder struct {
+ stellarClient *env.StellarClient
+ perunID xdr.ScAddress
+ assetID xdr.ScAddress
+ maxIters int
+ pollingInterval time.Duration
+}
+
+func NewFunder(acc *wallet.Account, stellarClient *env.StellarClient, perunID xdr.ScAddress, assetID xdr.ScAddress) *Funder {
+ return &Funder{
+ stellarClient: stellarClient,
+ perunID: perunID,
+ assetID: assetID,
+ maxIters: MaxIterationsUntilAbort,
+ pollingInterval: DefaultPollingInterval,
+ }
+}
+
+func (f *Funder) GetPerunID() xdr.ScAddress {
+ return f.perunID
+}
+
+func (f *Funder) GetAssetID() xdr.ScAddress {
+ return f.assetID
+}
+
+func (f *Funder) Fund(ctx context.Context, req pchannel.FundingReq) error {
+ log.Println("Fund called")
+
+ if req.Idx != 0 && req.Idx != 1 {
+ return errors.New("req.Idx must be 0 or 1")
+ }
+
+ if req.Idx == pchannel.Index(0) {
+ err := f.openChannel(ctx, req)
+ if err != nil {
+ return err
+ }
+ }
+
+ return f.fundParty(ctx, req)
+}
+func (f *Funder) fundParty(ctx context.Context, req pchannel.FundingReq) error {
+
+ party := getPartyByIndex(req.Idx)
+
+ log.Printf("%s: Funding channel...\n", party)
+
+ for i := 0; i < f.maxIters; i++ {
+ select {
+ case <-ctx.Done():
+ return f.AbortChannel(ctx, req.Params, req.State)
+ case <-time.After(f.pollingInterval):
+
+ log.Printf("%s: Polling for opened channel...\n", party)
+ chanState, err := f.GetChannelState(ctx, req.Params, req.State)
+ if err != nil {
+ log.Printf("%s: Error while polling for opened channel: %v\n", party, err)
+ continue
+ }
+
+ log.Printf("%s: Found opened channel!\n", party)
+ if chanState.Control.FundedA && chanState.Control.FundedB {
+ return nil
+ }
+
+ if req.Idx == pchannel.Index(0) && !chanState.Control.FundedA {
+ err := f.FundChannel(ctx, req.Params, req.State, false)
+ if err != nil {
+ return err
+ }
+ continue
+ }
+ if req.Idx == pchannel.Index(1) && !chanState.Control.FundedB {
+ err := f.FundChannel(ctx, req.Params, req.State, true)
+ if err != nil {
+ return err
+ }
+ continue
+ }
+ }
+ }
+ return f.AbortChannel(ctx, req.Params, req.State)
+}
+
+func (f *Funder) openChannel(ctx context.Context, req pchannel.FundingReq) error {
+ err := f.OpenChannel(ctx, req.Params, req.State)
+ if err != nil {
+ return errors.New("error while opening channel in party A")
+ }
+ return nil
+}
+
+func (f *Funder) OpenChannel(ctx context.Context, params *pchannel.Params, state *pchannel.State) error {
+
+ perunAddress := f.GetPerunID()
+ openTxArgs, err := env.BuildOpenTxArgs(params, state)
+ if err != nil {
+ return errors.New("error while building open tx")
+ }
+ txMeta, err := f.stellarClient.InvokeAndProcessHostFunction("open", openTxArgs, perunAddress)
+ if err != nil {
+ return errors.New("error while invoking and processing host function: open")
+ }
+
+ _, err = DecodeEventsPerun(txMeta)
+ if err != nil {
+ return errors.New("error while decoding events")
+ }
+
+ return nil
+}
+
+func (f *Funder) FundChannel(ctx context.Context, params *pchannel.Params, state *pchannel.State, funderIdx bool) error {
+
+ perunAddress := f.GetPerunID()
+ tokenAddress := f.GetAssetID()
+
+ chanId := state.ID
+
+ fundTxArgs, err := env.BuildFundTxArgs(chanId, funderIdx)
+ if err != nil {
+ return errors.New("error while building fund tx")
+ }
+ balsStellar, err := wire.MakeBalances(state.Allocation)
+ if err != nil {
+ return errors.New("error while making balances")
+ }
+
+ tokenIDAddrFromBals := balsStellar.Token
+
+ sameContractTokenID := tokenIDAddrFromBals.Equals(tokenAddress)
+ if !sameContractTokenID {
+ return errors.New("tokenIDAddrFromBals not equal to tokenContractAddress")
+ }
+
+ txMeta, err := f.stellarClient.InvokeAndProcessHostFunction("fund", fundTxArgs, perunAddress)
+ if err != nil {
+ return errors.New("error while invoking and processing host function: fund")
+ }
+
+ _, err = DecodeEventsPerun(txMeta)
+ if err != nil {
+ return errors.New("error while decoding events")
+ }
+
+ return nil
+}
+
+func (f *Funder) AbortChannel(ctx context.Context, params *pchannel.Params, state *pchannel.State) error {
+
+ contractAddress := f.GetPerunID()
+ chanId := state.ID
+
+ openTxArgs, err := env.BuildGetChannelTxArgs(chanId)
+ if err != nil {
+ return errors.New("error while building get_channel tx")
+ }
+ txMeta, err := f.stellarClient.InvokeAndProcessHostFunction("abort_funding", openTxArgs, contractAddress)
+ if err != nil {
+ return errors.New("error while invoking and processing host function: abort_funding")
+ }
+
+ _, err = DecodeEventsPerun(txMeta)
+ if err != nil {
+ return errors.New("error while decoding events")
+ }
+
+ return nil
+}
+
+func (f *Funder) GetChannelState(ctx context.Context, params *pchannel.Params, state *pchannel.State) (wire.Channel, error) {
+
+ contractAddress := f.GetPerunID()
+ chanId := state.ID
+
+ getchTxArgs, err := env.BuildGetChannelTxArgs(chanId)
+ if err != nil {
+ return wire.Channel{}, errors.New("error while building get_channel tx")
+ }
+ txMeta, err := f.stellarClient.InvokeAndProcessHostFunction("get_channel", getchTxArgs, contractAddress)
+ if err != nil {
+ return wire.Channel{}, errors.New("error while processing and submitting get_channel tx")
+ }
+
+ retVal := txMeta.V3.SorobanMeta.ReturnValue
+ var getChan wire.Channel
+
+ err = getChan.FromScVal(retVal)
+ if err != nil {
+ return wire.Channel{}, errors.New("error while decoding return value")
+ }
+ return getChan, nil
+}
+
+func getPartyByIndex(funderIdx pchannel.Index) string {
+ if funderIdx == 1 {
+ return "Party B"
+ }
+ return "Party A"
+}
diff --git a/channel/funder_test.go b/channel/funder_test.go
new file mode 100644
index 0000000..ef2c031
--- /dev/null
+++ b/channel/funder_test.go
@@ -0,0 +1,46 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//go:build integration
+// +build integration
+
+package channel_test
+
+import (
+ "github.com/stretchr/testify/require"
+ pchannel "perun.network/go-perun/channel"
+ pwallet "perun.network/go-perun/wallet"
+ chtest "perun.network/perun-stellar-backend/channel/test"
+ "testing"
+)
+
+func TestFunding(t *testing.T) {
+ setup := chtest.NewTestSetup(t)
+ stellarAsset := setup.GetTokenAsset()
+ accs := setup.GetAccounts()
+ addrAlice := accs[0].Address()
+ addrBob := accs[1].Address()
+ addrList := []pwallet.Address{addrAlice, addrBob}
+ perunParams, perunState := chtest.NewParamsWithAddressStateWithAsset(t, addrList, stellarAsset)
+
+ freqAlice := pchannel.NewFundingReq(perunParams, perunState, 0, perunState.Balances)
+ freqBob := pchannel.NewFundingReq(perunParams, perunState, 1, perunState.Balances)
+
+ freqs := []*pchannel.FundingReq{freqAlice, freqBob}
+
+ funders := setup.GetFunders()
+ ctx := setup.NewCtx()
+ err := chtest.FundAll(ctx, funders, freqs)
+ require.NoError(t, err)
+}
diff --git a/channel/subscribe.go b/channel/subscribe.go
new file mode 100644
index 0000000..44e44d0
--- /dev/null
+++ b/channel/subscribe.go
@@ -0,0 +1,85 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package channel
+
+import (
+ "log"
+ pchannel "perun.network/go-perun/channel"
+ "reflect"
+)
+
+func (s *AdjEventSub) Next() pchannel.AdjudicatorEvent {
+ if s.closer.IsClosed() {
+ return nil
+ }
+
+ if s.getEvents() == nil {
+ return nil
+ }
+
+ select {
+ case event := <-s.getEvents():
+ if event == nil {
+ return nil
+ }
+
+ timestamp := event.Tstamp()
+
+ switch e := event.(type) {
+ case *DisputedEvent:
+ log.Println("DisputedEvent received")
+ dispEvent := pchannel.AdjudicatorEventBase{
+ VersionV: e.Version(),
+ IDV: e.ID(),
+ TimeoutV: MakeTimeout(timestamp),
+ }
+ ddn := &pchannel.RegisteredEvent{AdjudicatorEventBase: dispEvent, State: nil, Sigs: nil}
+ s.closer.Close()
+ return ddn
+
+ case *CloseEvent:
+
+ log.Println("CloseEvent received")
+ conclEvent := pchannel.AdjudicatorEventBase{
+ VersionV: e.Version(),
+ IDV: e.ID(),
+ TimeoutV: MakeTimeout(timestamp),
+ }
+ ccn := &pchannel.ConcludedEvent{AdjudicatorEventBase: conclEvent}
+ s.closer.Close()
+ return ccn
+
+ default:
+ log.Printf("Received an unknown event type: %v\n", reflect.TypeOf(e))
+ return nil
+ }
+
+ case <-s.closer.Closed():
+ return nil
+ }
+}
+
+func (s *AdjEventSub) Close() error {
+ s.closer.Close()
+ return nil
+}
+
+func (s *AdjEventSub) getEvents() <-chan AdjEvent {
+ return s.events
+}
+
+func (s *AdjEventSub) Err() error {
+ return s.err
+}
diff --git a/channel/test/fund.go b/channel/test/fund.go
new file mode 100644
index 0000000..2907a24
--- /dev/null
+++ b/channel/test/fund.go
@@ -0,0 +1,37 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package test
+
+import (
+ "context"
+ pchannel "perun.network/go-perun/channel"
+ "perun.network/perun-stellar-backend/channel"
+ pkgerrors "polycry.pt/poly-go/errors"
+)
+
+func FundAll(ctx context.Context, funders []*channel.Funder, reqs []*pchannel.FundingReq) error {
+ g := pkgerrors.NewGatherer()
+ for i := range funders {
+ i := i
+ g.Go(func() error {
+ return funders[i].Fund(ctx, *reqs[i])
+ })
+ }
+
+ if g.WaitDoneOrFailedCtx(ctx) {
+ return ctx.Err()
+ }
+ return g.Err()
+}
diff --git a/channel/test/init.go b/channel/test/init.go
index a39657d..692fb4f 100644
--- a/channel/test/init.go
+++ b/channel/test/init.go
@@ -1,7 +1,27 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
package test
-import "perun.network/go-perun/channel/test"
+import (
+ pchtest "perun.network/go-perun/channel/test"
+ pwtest "perun.network/go-perun/wallet/test"
+ wtest "perun.network/perun-stellar-backend/wallet/test"
+)
func init() {
- test.SetRandomizer(&Randomizer{})
+ pchtest.SetRandomizer(&Randomizer{})
+ walletRdz := wtest.Randomizer{}
+ pwtest.SetRandomizer(&walletRdz)
}
diff --git a/channel/test/randomizer.go b/channel/test/randomizer.go
index 92cb05f..685244f 100644
--- a/channel/test/randomizer.go
+++ b/channel/test/randomizer.go
@@ -1,3 +1,17 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
package test
import (
diff --git a/channel/test/setup.go b/channel/test/setup.go
new file mode 100644
index 0000000..125e19f
--- /dev/null
+++ b/channel/test/setup.go
@@ -0,0 +1,265 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package test
+
+import (
+ "context"
+ "crypto/rand"
+ "encoding/binary"
+ "github.com/stellar/go/clients/horizonclient"
+ "github.com/stellar/go/keypair"
+ "github.com/stellar/go/txnbuild"
+ "github.com/stellar/go/xdr"
+ "github.com/stretchr/testify/require"
+ "log"
+ "math/big"
+ mathrand "math/rand"
+ pchannel "perun.network/go-perun/channel"
+ ptest "perun.network/go-perun/channel/test"
+ pwallet "perun.network/go-perun/wallet"
+ "perun.network/perun-stellar-backend/channel"
+ "perun.network/perun-stellar-backend/channel/env"
+ "perun.network/perun-stellar-backend/channel/types"
+ "perun.network/perun-stellar-backend/wallet"
+ pkgtest "polycry.pt/poly-go/test"
+ "testing"
+ "time"
+)
+
+const (
+ PerunContractPath = "../testdata/perun_soroban_contract.wasm"
+ StellarAssetContractPath = "../testdata/perun_soroban_token.wasm"
+ initLumensBalance = "10000000"
+ initTokenBalance = uint64(2000000)
+ DefaultTestTimeout = 200
+)
+
+type Setup struct {
+ t *testing.T
+ accs []*wallet.Account
+ stellarClients []*env.StellarClient
+ Rng *mathrand.Rand
+ funders []*channel.Funder
+ adjs []*channel.Adjudicator
+ assetID pchannel.Asset
+}
+
+func (s *Setup) GetStellarClients() []*env.StellarClient {
+ return s.stellarClients
+}
+
+func (s *Setup) GetFunders() []*channel.Funder {
+ return s.funders
+}
+
+func (s *Setup) GetAdjudicators() []*channel.Adjudicator {
+ return s.adjs
+}
+
+func (s *Setup) GetTokenAsset() pchannel.Asset {
+ return s.assetID
+}
+
+func (s *Setup) GetAccounts() []*wallet.Account {
+ return s.accs
+}
+
+func NewTestSetup(t *testing.T) *Setup {
+
+ accs, kpsToFund := MakeRandPerunAccs(4)
+ require.NoError(t, CreateFundStellarAccounts(kpsToFund, initLumensBalance))
+
+ depTokenKp := kpsToFund[2]
+ depPerunKp := kpsToFund[3]
+
+ tokenAddress, _ := Deploy(t, depTokenKp, StellarAssetContractPath)
+ perunAddress, _ := Deploy(t, depPerunKp, PerunContractPath)
+
+ require.NoError(t, InitTokenContract(depTokenKp, tokenAddress))
+
+ setupAccountsAndContracts(t, depTokenKp, kpsToFund[:2], tokenAddress, initTokenBalance)
+
+ assetContractID, err := types.NewStellarAssetFromScAddress(tokenAddress)
+ require.NoError(t, err)
+
+ stellarClients := NewStellarClients(kpsToFund)
+
+ aliceClient := stellarClients[0]
+ bobClient := stellarClients[1]
+ channelAccs := []*wallet.Account{accs[0], accs[1]}
+ channelClients := []*env.StellarClient{aliceClient, bobClient}
+
+ funders, adjs := createFundersAndAdjudicators(channelAccs, stellarClients, perunAddress, tokenAddress)
+
+ setup := Setup{
+ t: t,
+ accs: channelAccs,
+ stellarClients: channelClients,
+ funders: funders,
+ adjs: adjs,
+ assetID: assetContractID,
+ }
+
+ return &setup
+}
+
+func setupAccountsAndContracts(t *testing.T, deployerKp *keypair.Full, kps []*keypair.Full, tokenAddress xdr.ScAddress, tokenBalance uint64) {
+ for _, kp := range kps {
+ addr, err := types.MakeAccountAddress(kp)
+ require.NoError(t, err)
+ require.NoError(t, MintToken(deployerKp, tokenAddress, tokenBalance, addr))
+ }
+}
+
+func createFundersAndAdjudicators(accs []*wallet.Account, clients []*env.StellarClient, perunAddress, tokenAddress xdr.ScAddress) ([]*channel.Funder, []*channel.Adjudicator) {
+ funders := make([]*channel.Funder, len(accs))
+ adjs := make([]*channel.Adjudicator, len(accs))
+ for i, acc := range accs {
+ funders[i] = channel.NewFunder(acc, clients[i], perunAddress, tokenAddress)
+ adjs[i] = channel.NewAdjudicator(acc, clients[i], perunAddress, tokenAddress)
+ }
+ return funders, adjs
+}
+
+func NewStellarClients(kps []*keypair.Full) []*env.StellarClient {
+ clients := make([]*env.StellarClient, len(kps))
+ for i, kp := range kps {
+ clients[i] = env.NewStellarClient(kp)
+ }
+ return clients
+}
+
+func MakeRandPerunAccs(count int) ([]*wallet.Account, []*keypair.Full) {
+ accs := make([]*wallet.Account, count)
+ kps := make([]*keypair.Full, count)
+
+ for i := 0; i < count; i++ {
+ acc, kp := MakeRandPerunAcc()
+ accs[i] = acc
+ kps[i] = kp
+ }
+ return accs, kps
+}
+
+func MakeRandPerunAcc() (*wallet.Account, *keypair.Full) {
+ w := wallet.NewEphemeralWallet()
+
+ var b [8]byte
+ _, err := rand.Read(b[:])
+ if err != nil {
+ panic(err)
+ }
+
+ seed := binary.LittleEndian.Uint64(b[:])
+
+ r := mathrand.New(mathrand.NewSource(int64(seed)))
+
+ acc, kp, err := w.AddNewAccount(r)
+ if err != nil {
+ panic(err)
+ }
+ return acc, kp
+}
+
+func CreateFundStellarAccounts(pairs []*keypair.Full, initialBalance string) error {
+
+ numKps := len(pairs)
+
+ masterClient := env.NewHorizonMasterClient()
+ masterHzClient := masterClient.GetHorizonClient()
+ sourceKey := keypair.Root(env.NETWORK_PASSPHRASE)
+
+ hzClient := env.NewHorizonClient()
+
+ ops := make([]txnbuild.Operation, numKps)
+
+ accReq := horizonclient.AccountRequest{AccountID: masterClient.GetAddress()}
+ sourceAccount, err := masterHzClient.AccountDetail(accReq)
+ if err != nil {
+ panic(err)
+ }
+
+ masterAccount := txnbuild.SimpleAccount{
+ AccountID: masterClient.GetAddress(),
+ Sequence: sourceAccount.Sequence,
+ }
+
+ for i := 0; i < numKps; i++ {
+ pair := pairs[i]
+
+ ops[i] = &txnbuild.CreateAccount{
+ SourceAccount: masterAccount.AccountID,
+ Destination: pair.Address(),
+ Amount: initialBalance,
+ }
+ }
+
+ txParams := env.GetBaseTransactionParamsWithFee(&masterAccount, txnbuild.MinBaseFee, ops...)
+
+ txSigned, err := env.CreateSignedTransactionWithParams([]*keypair.Full{sourceKey}, txParams)
+
+ if err != nil {
+ panic(err)
+ }
+ _, err = hzClient.SubmitTransaction(txSigned)
+ if err != nil {
+ panic(err)
+ }
+
+ accounts := make([]txnbuild.Account, numKps)
+ for i, kp := range pairs {
+ request := horizonclient.AccountRequest{AccountID: kp.Address()}
+ account, err := hzClient.AccountDetail(request)
+ if err != nil {
+ panic(err)
+ }
+
+ accounts[i] = &account
+ }
+
+ for _, keys := range pairs {
+ log.Printf("Funded %s (%s) with %s XLM.\n",
+ keys.Seed(), keys.Address(), initialBalance)
+ }
+
+ return nil
+}
+
+func NewParamsWithAddressStateWithAsset(t *testing.T, partsAddr []pwallet.Address, asset pchannel.Asset) (*pchannel.Params, *pchannel.State) {
+
+ rng := pkgtest.Prng(t)
+
+ numParts := 2
+
+ return ptest.NewRandomParamsAndState(rng, ptest.WithNumLocked(0).Append(
+ ptest.WithAssets(asset),
+ ptest.WithVersion(0),
+ ptest.WithNumParts(numParts),
+ ptest.WithParts(partsAddr...),
+ ptest.WithIsFinal(false),
+ ptest.WithLedgerChannel(true),
+ ptest.WithVirtualChannel(false),
+ ptest.WithNumAssets(1),
+ ptest.WithoutApp(),
+ ptest.WithBalancesInRange(big.NewInt(0).Mul(big.NewInt(1), big.NewInt(100_000)), big.NewInt(0).Mul(big.NewInt(1), big.NewInt(100_000))),
+ ))
+}
+
+func (s *Setup) NewCtx() context.Context {
+ timeout := time.Duration(float64(DefaultTestTimeout) * float64(time.Second))
+ ctx, cancel := context.WithTimeout(context.Background(), timeout)
+ s.t.Cleanup(cancel)
+ return ctx
+}
diff --git a/channel/test/token.go b/channel/test/token.go
new file mode 100644
index 0000000..1c8a18b
--- /dev/null
+++ b/channel/test/token.go
@@ -0,0 +1,223 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package test
+
+import (
+ "github.com/stellar/go/clients/horizonclient"
+ "github.com/stellar/go/keypair"
+ "github.com/stellar/go/xdr"
+ "github.com/stretchr/testify/require"
+ "perun.network/perun-stellar-backend/channel"
+ "perun.network/perun-stellar-backend/channel/env"
+ "perun.network/perun-stellar-backend/channel/types"
+ "perun.network/perun-stellar-backend/wire/scval"
+ "testing"
+)
+
+const tokenDecimals = uint32(7)
+const tokenName = "PerunToken"
+const tokenSymbol = "PRN"
+
+type TokenParams struct {
+ decimals uint32
+ name string
+ symbol string
+}
+
+func NewTokenParams() *TokenParams {
+ return &TokenParams{
+ decimals: tokenDecimals,
+ name: tokenName,
+ symbol: tokenSymbol,
+ }
+}
+
+func (t *TokenParams) GetDecimals() uint32 {
+ return t.decimals
+}
+
+func (t *TokenParams) GetName() string {
+ return t.name
+}
+
+func (t *TokenParams) GetSymbol() string {
+ return t.symbol
+}
+
+func BuildInitTokenArgs(adminAddr xdr.ScAddress, decimals uint32, tokenName string, tokenSymbol string) (xdr.ScVec, error) {
+
+ adminScAddr, err := scval.WrapScAddress(adminAddr)
+ if err != nil {
+ panic(err)
+ }
+
+ decim := xdr.Uint32(decimals)
+ scvaltype := xdr.ScValTypeScvU32
+ decimSc, err := xdr.NewScVal(scvaltype, decim)
+ if err != nil {
+ panic(err)
+ }
+
+ tokenNameScString := xdr.ScString(tokenName)
+ tokenNameXdr := scval.MustWrapScString(tokenNameScString)
+
+ tokenSymbolString := xdr.ScString(tokenSymbol)
+ tokenSymbolXdr := scval.MustWrapScString(tokenSymbolString)
+
+ initTokenArgs := xdr.ScVec{
+ adminScAddr,
+ decimSc,
+ tokenNameXdr,
+ tokenSymbolXdr,
+ }
+
+ return initTokenArgs, nil
+}
+
+func InitTokenContract(kp *keypair.Full, contractIDAddress xdr.ScAddress) error {
+
+ stellarClient := env.NewStellarClient(kp)
+ adminScAddr, err := types.MakeAccountAddress(kp)
+ if err != nil {
+ panic(err)
+ }
+
+ tokenParams := NewTokenParams()
+ decimals := tokenParams.GetDecimals()
+ name := tokenParams.GetName()
+ symbol := tokenParams.GetSymbol()
+
+ initArgs, err := BuildInitTokenArgs(adminScAddr, decimals, name, symbol)
+ if err != nil {
+ panic(err)
+ }
+ _, err = stellarClient.InvokeAndProcessHostFunction("initialize", initArgs, contractIDAddress)
+ if err != nil {
+ panic(err)
+ }
+
+ return nil
+}
+
+func GetTokenName(kp *keypair.Full, contractAddress xdr.ScAddress) error {
+
+ stellarClient := env.NewStellarClient(kp)
+ TokenNameArgs := xdr.ScVec{}
+
+ _, err := stellarClient.InvokeAndProcessHostFunction("name", TokenNameArgs, contractAddress)
+ if err != nil {
+ panic(err)
+ }
+
+ return nil
+}
+
+func BuildGetTokenBalanceArgs(balanceOf xdr.ScAddress) (xdr.ScVec, error) {
+
+ recScAddr, err := scval.WrapScAddress(balanceOf)
+ if err != nil {
+ panic(err)
+ }
+
+ GetTokenBalanceArgs := xdr.ScVec{
+ recScAddr,
+ }
+
+ return GetTokenBalanceArgs, nil
+}
+
+func BuildTransferTokenArgs(from xdr.ScAddress, to xdr.ScAddress, amount xdr.Int128Parts) (xdr.ScVec, error) {
+
+ fromScAddr, err := scval.WrapScAddress(from)
+ if err != nil {
+ panic(err)
+ }
+
+ toScAddr, err := scval.WrapScAddress(to)
+ if err != nil {
+ panic(err)
+ }
+
+ amountSc, err := scval.WrapInt128Parts(amount)
+ if err != nil {
+ panic(err)
+ }
+
+ GetTokenBalanceArgs := xdr.ScVec{
+ fromScAddr,
+ toScAddr,
+ amountSc,
+ }
+
+ return GetTokenBalanceArgs, nil
+}
+
+func Deploy(t *testing.T, kp *keypair.Full, contractPath string) (xdr.ScAddress, xdr.Hash) {
+ deployerClient := env.NewStellarClient(kp)
+ hzClient := deployerClient.GetHorizonClient()
+ deployerAccReq := horizonclient.AccountRequest{AccountID: kp.Address()}
+ deployerAcc, err := hzClient.AccountDetail(deployerAccReq)
+
+ require.NoError(t, err)
+
+ installContractOpInstall := channel.AssembleInstallContractCodeOp(kp.Address(), contractPath)
+ preFlightOp, minFeeInstall := env.PreflightHostFunctions(hzClient, &deployerAcc, *installContractOpInstall)
+ txParamsInstall := env.GetBaseTransactionParamsWithFee(&deployerAcc, int64(minFeeInstall), &preFlightOp)
+ txSignedInstall, err := env.CreateSignedTransactionWithParams([]*keypair.Full{kp}, txParamsInstall)
+ require.NoError(t, err)
+
+ _, err = hzClient.SubmitTransaction(txSignedInstall)
+
+ require.NoError(t, err)
+
+ createContractOp := channel.AssembleCreateContractOp(kp.Address(), contractPath, "a1", env.NETWORK_PASSPHRASE)
+ preFlightOpCreate, minFeeCreate := env.PreflightHostFunctions(hzClient, &deployerAcc, *createContractOp)
+ txParamsCreate := env.GetBaseTransactionParamsWithFee(&deployerAcc, int64(minFeeCreate), &preFlightOpCreate)
+ txSignedCreate, err := env.CreateSignedTransactionWithParams([]*keypair.Full{kp}, txParamsCreate)
+
+ require.NoError(t, err)
+
+ _, err = hzClient.SubmitTransaction(txSignedCreate)
+ require.NoError(t, err)
+
+ contractID := preFlightOpCreate.Ext.SorobanData.Resources.Footprint.ReadWrite[0].MustContractData().Contract.ContractId
+ contractHash := preFlightOpCreate.Ext.SorobanData.Resources.Footprint.ReadOnly[0].MustContractCode().Hash
+ contractIDAddress := xdr.ScAddress{
+ Type: xdr.ScAddressTypeScAddressTypeContract,
+ ContractId: contractID,
+ }
+
+ return contractIDAddress, contractHash
+}
+
+func MintToken(kp *keypair.Full, contractAddr xdr.ScAddress, amount uint64, recipientAddr xdr.ScAddress) error {
+ stellarClient := env.NewStellarClient(kp)
+
+ amountTo128Xdr := xdr.Int128Parts{Hi: 0, Lo: xdr.Uint64(amount)}
+
+ amountSc, err := xdr.NewScVal(xdr.ScValTypeScvI128, amountTo128Xdr)
+ if err != nil {
+ panic(err)
+ }
+ mintTokenArgs, err := env.BuildMintTokenArgs(recipientAddr, amountSc)
+ if err != nil {
+ panic(err)
+ }
+ _, err = stellarClient.InvokeAndProcessHostFunction("mint", mintTokenArgs, contractAddr)
+ if err != nil {
+ panic(err)
+ }
+ return nil
+}
diff --git a/channel/timeout.go b/channel/timeout.go
new file mode 100644
index 0000000..7c35892
--- /dev/null
+++ b/channel/timeout.go
@@ -0,0 +1,102 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package channel
+
+import (
+ "context"
+ "perun.network/go-perun/log"
+ "time"
+)
+
+type (
+ // ExpiredTimeout is always expired.
+ // Implements the Perun Timeout interface.
+ ExpiredTimeout struct{}
+
+ // Timeout can be used to wait until a specific timepoint is reached by
+ // the blockchain. Implements the Perun Timeout interface.
+ Timeout struct {
+ log.Embedding
+
+ when time.Time
+ pollInterval time.Duration
+ }
+
+ // TimePoint as defined by pallet Timestamp.
+ TimePoint uint64
+)
+
+// DefaultTimeoutPollInterval default value for the PollInterval of a Timeout.
+const DefaultTimeoutPollInterval = 1 * time.Second
+
+// NewExpiredTimeout returns a new ExpiredTimeout.
+func NewExpiredTimeout() *ExpiredTimeout {
+ return &ExpiredTimeout{}
+}
+
+func (*ExpiredTimeout) IsElapsed(context.Context) bool {
+ return true
+}
+
+// Wait returns nil.
+func (*ExpiredTimeout) Wait(context.Context) error {
+ return nil
+}
+
+// NewTimeout returns a new Timeout which expires at the given time.
+func NewTimeout(when time.Time, pollInterval time.Duration) *Timeout {
+ return &Timeout{log.MakeEmbedding(log.Default()), when, pollInterval}
+}
+
+// IsElapsed returns whether the timeout is elapsed.
+func (t *Timeout) IsElapsed(ctx context.Context) bool {
+ now := time.Now()
+
+ elapsed := t.when.Before(now) || t.when.Equal(now)
+
+ delta := now.Sub(t.when)
+ if elapsed {
+ t.Log().Printf("Timeout elapsed since %v", delta)
+ } else {
+ t.Log().Printf("Timeout target in %v", delta)
+ }
+
+ return elapsed
+}
+
+// Wait waits for the timeout or until the context is cancelled.
+func (t *Timeout) Wait(ctx context.Context) error {
+ for {
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-time.After(t.pollInterval):
+ if t.IsElapsed(ctx) {
+ return nil
+ }
+ }
+ }
+}
+
+// MakeTimeout creates a new timeout.
+func MakeTimeout(challDurSec uint64) *Timeout {
+ expirationTime := time.Now().Add(MakeTime(challDurSec))
+ return NewTimeout(expirationTime, DefaultTimeoutPollInterval)
+}
+
+// MakeTime creates a new time from the argument.
+func MakeTime(challDurSec uint64) time.Duration {
+ return time.Duration(challDurSec) * time.Second
+}
diff --git a/channel/types/asset.go b/channel/types/asset.go
index 362b4d5..7875650 100644
--- a/channel/types/asset.go
+++ b/channel/types/asset.go
@@ -1,3 +1,17 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
package types
import (
diff --git a/channel/types/asset_test.go b/channel/types/asset_test.go
index 0285035..bbc9e30 100644
--- a/channel/types/asset_test.go
+++ b/channel/types/asset_test.go
@@ -1,3 +1,17 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
package types_test
import (
@@ -5,7 +19,6 @@ import (
"github.com/stellar/go/xdr"
"github.com/stretchr/testify/require"
"perun.network/perun-stellar-backend/channel/types"
-
"testing"
)
diff --git a/channel/types/doc.go b/channel/types/doc.go
new file mode 100644
index 0000000..9d847ae
--- /dev/null
+++ b/channel/types/doc.go
@@ -0,0 +1,16 @@
+// Copyright 2024 - See NOTICE file for copyright holders.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package types defines the stellar asset that is used in payment channels.
+package types
diff --git a/go.mod b/go.mod
index 3687df9..f624fe4 100644
--- a/go.mod
+++ b/go.mod
@@ -2,19 +2,31 @@ module perun.network/perun-stellar-backend
go 1.19
-require github.com/stellar/go v0.0.0-20230905170723-6e18a2f2f583
+require github.com/stellar/go v0.0.0-20231212225359-bc7173e667a6
require (
- github.com/stellar/go-xdr v0.0.0-20211103144802-8017fc4bdfee
- github.com/stretchr/testify v1.8.1
+ github.com/creachadair/jrpc2 v1.1.0
+ github.com/stellar/go-xdr v0.0.0-20231122183749-b53fb00bcac2
+ github.com/stretchr/testify v1.8.4
perun.network/go-perun v0.10.6
- polycry.pt/poly-go v0.0.0-20220222131629-aa4bdbaab60b
+ polycry.pt/poly-go v0.0.0-20220301085937-fb9d71b45a37
)
require (
- github.com/davecgh/go-spew v1.1.1 // indirect
- github.com/kr/pretty v0.3.1 // indirect
+ github.com/creachadair/mds v0.0.1 // indirect
+ github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
+ github.com/go-chi/chi v4.1.2+incompatible // indirect
+ github.com/go-errors/errors v1.5.1 // indirect
+ github.com/gorilla/schema v1.2.0 // indirect
+ github.com/kr/pretty v0.1.0 // indirect
+ github.com/manucorporat/sse v0.0.0-20160126180136-ee05b128a739 // indirect
github.com/pkg/errors v0.9.1 // indirect
- github.com/pmezard/go-difflib v1.0.0 // indirect
+ github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
+ github.com/segmentio/go-loggly v0.5.1-0.20171222203950-eb91657e62b2 // indirect
+ github.com/sirupsen/logrus v1.9.3 // indirect
+ github.com/stretchr/objx v0.5.1 // indirect
+ golang.org/x/crypto v0.14.0 // indirect
+ golang.org/x/sync v0.4.0 // indirect
+ golang.org/x/sys v0.13.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
diff --git a/go.sum b/go.sum
index ddebfba..69db35a 100644
--- a/go.sum
+++ b/go.sum
@@ -1,45 +1,92 @@
-github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
+github.com/ajg/form v0.0.0-20160822230020-523a5da1a92f h1:zvClvFQwU++UpIUBGC8YmDlfhUrweEy1R1Fj1gu5iIM=
+github.com/andybalholm/brotli v1.0.4 h1:V7DdXeJtZscaqfNuAdSRuRFzuiKlHSC/Zh3zl9qY3JY=
+github.com/creachadair/jrpc2 v1.1.0 h1:SgpJf0v1rVCZx68+4APv6dgsTFsIHlpgFD1NlQAWA0A=
+github.com/creachadair/jrpc2 v1.1.0/go.mod h1:5jN7MKwsm8qvgfTsTzLX3JIfidsAkZ1c8DZSQmp+g38=
+github.com/creachadair/mds v0.0.1 h1:2nX6Sww4dXpScx3b6aYjH1n7iuEH715+jj+cKkKw9BY=
+github.com/creachadair/mds v0.0.1/go.mod h1:caBACU+n1Q/rZ252FTzfnG0/H+ZUi+UnIQtEOraMv/g=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
-github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
+github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/fatih/structs v1.0.0 h1:BrX964Rv5uQ3wwS+KRUAJCBBw5PQmgJfJ6v4yly5QwU=
+github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw=
github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY=
+github.com/gavv/monotime v0.0.0-20161010190848-47d58efa6955 h1:gmtGRvSexPU4B1T/yYo0sLOKzER1YT+b4kPxPpm0Ty4=
+github.com/go-chi/chi v4.1.2+incompatible h1:fGFk2Gmi/YKXk0OmGfBh0WgmN3XB8lVnEyNz34tQRec=
+github.com/go-chi/chi v4.1.2+incompatible/go.mod h1:eB3wogJHnLi3x/kFX2A+IbTBlXxmMeXJVKy9tTv1XzQ=
+github.com/go-errors/errors v1.5.1 h1:ZwEMSLRCapFLflTpT7NKaAc7ukJ8ZPEjzlxt8rPN8bk=
+github.com/go-errors/errors v1.5.1/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
-github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
-github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
+github.com/google/go-querystring v0.0.0-20160401233042-9235644dd9e5 h1:oERTZ1buOUYlpmKaqlO5fYmz8cZ1rYu5DieJzF4ZVmU=
+github.com/gorilla/schema v1.2.0 h1:YufUaxZYCKGFuAq3c96BOhjgd5nmXiOY9NGzF247Tsc=
+github.com/gorilla/schema v1.2.0/go.mod h1:kgLaKoK1FELgZqMAVxx/5cbj0kT+57qxUrAlIO2eleU=
+github.com/imkira/go-interpol v1.1.0 h1:KIiKr0VSG2CUW1hl1jpiyuzuJeKUUpC8iM1AIE7N1Vk=
+github.com/jarcoal/httpmock v0.0.0-20161210151336-4442edb3db31 h1:Aw95BEvxJ3K6o9GGv5ppCd1P8hkeIeEJ30FO+OhOJpM=
+github.com/klauspost/compress v1.17.0 h1:Rnbp4K9EjcDuVuHtd0dgA4qNuv9yKDYKK1ulpJwgrqM=
+github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
+github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
+github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
+github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
-github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
+github.com/manucorporat/sse v0.0.0-20160126180136-ee05b128a739 h1:ykXz+pRRTibcSjG1yRhpdSHInF8yZY/mfn+Rz2Nd1rE=
+github.com/manucorporat/sse v0.0.0-20160126180136-ee05b128a739/go.mod h1:zUx1mhth20V3VKgL5jbd1BSQcW4Fy6Qs4PZvQwRFwzM=
+github.com/moul/http2curl v0.0.0-20161031194548-4e24498b31db h1:eZgFHVkk9uOTaOQLC6tgjkzdp7Ays8eEVecBcfHZlJQ=
github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=
github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE=
github.com/onsi/gomega v1.27.10 h1:naR28SdDFlqrG6kScpT8VWpu1xWY5nJRCF3XaYyBjhI=
-github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
-github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
-github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
-github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M=
-github.com/stellar/go v0.0.0-20230905170723-6e18a2f2f583 h1:oC7naR8IBqtWV/b+G91gTOe+jR52+GpkXhCxEyYawYY=
-github.com/stellar/go v0.0.0-20230905170723-6e18a2f2f583/go.mod h1:5/qoLl0pexA5OPi0BZvDsOc3532CJlHuRg1dnBxbsGg=
-github.com/stellar/go-xdr v0.0.0-20211103144802-8017fc4bdfee h1:fbVs0xmXpBvVS4GBeiRmAE3Le70ofAqFMch1GTiq/e8=
-github.com/stellar/go-xdr v0.0.0-20211103144802-8017fc4bdfee/go.mod h1:yoxyU/M8nl9LKeWIoBrbDPQ7Cy+4jxRcWcOayZ4BMps=
+github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
+github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/segmentio/go-loggly v0.5.1-0.20171222203950-eb91657e62b2 h1:S4OC0+OBKz6mJnzuHioeEat74PuQ4Sgvbf8eus695sc=
+github.com/segmentio/go-loggly v0.5.1-0.20171222203950-eb91657e62b2/go.mod h1:8zLRYR5npGjaOXgPSKat5+oOh+UHd8OdbS18iqX9F6Y=
+github.com/sergi/go-diff v0.0.0-20161205080420-83532ca1c1ca h1:oR/RycYTFTVXzND5r4FdsvbnBn0HJXSVeNAnwaTXRwk=
+github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
+github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
+github.com/stellar/go v0.0.0-20231212225359-bc7173e667a6 h1:LcQ01nwgxVoCmzAthjGSbxun9z/mxuqDy4uYETw4jEQ=
+github.com/stellar/go v0.0.0-20231212225359-bc7173e667a6/go.mod h1:PAWie4LYyDzJXqDVG4Qcj1Nt+uNk7sjzgSCXndQYsBA=
+github.com/stellar/go-xdr v0.0.0-20231122183749-b53fb00bcac2 h1:OzCVd0SV5qE3ZcDeSFCmOWLZfEWZ3Oe8KtmSOYKEVWE=
+github.com/stellar/go-xdr v0.0.0-20231122183749-b53fb00bcac2/go.mod h1:yoxyU/M8nl9LKeWIoBrbDPQ7Cy+4jxRcWcOayZ4BMps=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
+github.com/stretchr/objx v0.5.1 h1:4VhoImhV/Bm0ToFkXFi8hXNXwpDRZ/ynw3amt82mzq0=
+github.com/stretchr/objx v0.5.1/go.mod h1:/iHQpkQwBD6DLUmQ4pE+s1TXdob1mORJ4/UFdrifcy0=
+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
-github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
-github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
+github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
+github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
+github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
+github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
+github.com/valyala/fasthttp v1.34.0 h1:d3AAQJ2DRcxJYHm7OXNXtXt2as1vMDfxeIcFvhmGGm4=
github.com/xdrpp/goxdr v0.1.1 h1:E1B2c6E8eYhOVyd7yEpOyopzTPirUeF6mVOfXfGyJyc=
-golang.org/x/net v0.14.0 h1:BONx9s002vGdD9umnlX1Po8vOZmrgH34qlHcD1MfK14=
-golang.org/x/sys v0.11.0 h1:eG7RXZHdqOJ1i+0lgLgCpSXAp6M3LYlAo6osgSi0xOM=
-golang.org/x/text v0.12.0 h1:k+n5B8goJNdU7hSvEtMUz3d1Q6D/XW4COJSJR6fN0mc=
+github.com/xeipuuv/gojsonpointer v0.0.0-20151027082146-e0fe6f683076 h1:KM4T3G70MiR+JtqplcYkNVoNz7pDwYaBxWBXQK804So=
+github.com/xeipuuv/gojsonreference v0.0.0-20150808065054-e02fc20de94c h1:XZWnr3bsDQWAZg4Ne+cPoXRPILrNlPNQfxBuwLl43is=
+github.com/xeipuuv/gojsonschema v0.0.0-20161231055540-f06f290571ce h1:cVSRGH8cOveJNwFEEZLXtB+XMnRqKLjUP6V/ZFYQCXI=
+github.com/yalp/jsonpath v0.0.0-20150812003900-31a79c7593bb h1:06WAhQa+mYv7BiOk13B/ywyTlkoE/S7uu6TBKU6FHnE=
+github.com/yudai/gojsondiff v0.0.0-20170107030110-7b1b7adf999d h1:yJIizrfO599ot2kQ6Af1enICnwBD3XoxgX3MrMwot2M=
+github.com/yudai/golcs v0.0.0-20150405163532-d1c525dea8ce h1:888GrqRxabUce7lj4OaoShPxodm3kXOMpSa85wdYzfY=
+go.uber.org/goleak v1.1.11 h1:wy28qYRKZgnJTxGxvye5/wgWr1EKjmUDGYox5mGlRlI=
+golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc=
+golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
+golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
+golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM=
+golang.org/x/sync v0.4.0 h1:zxkM55ReGkDlKSM+Fu41A+zmbZuaPVbGMzvvdUPznYQ=
+golang.org/x/sync v0.4.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
+golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=
+golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
+gopkg.in/gavv/httpexpect.v1 v1.0.0-20170111145843-40724cf1e4a0 h1:r5ptJ1tBxVAeqw4CrYWhXIMr0SybY3CDHuIbCg5CFVw=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
perun.network/go-perun v0.10.6 h1:uj1e33yfCSfE75DK/uwjNp+TwvGG85Qhi6HuYQ9EPrQ=
perun.network/go-perun v0.10.6/go.mod h1:BGBZC3npkX457u87pjDd0NEIXr1a4dsH4H/YpLdGGe8=
-polycry.pt/poly-go v0.0.0-20220222131629-aa4bdbaab60b h1:BJsSrLQ3kLRNYXNqly//IYeXlVmAhpI5wYbg2WD1wR0=
-polycry.pt/poly-go v0.0.0-20220222131629-aa4bdbaab60b/go.mod h1:XUBrNtqgEhN3EEOP/5gh7IBd3xVHKidCjXDZfl9+kMU=
+polycry.pt/poly-go v0.0.0-20220301085937-fb9d71b45a37 h1:iA5GzEa/hHfVlQpimEjPV09NATwHXxSjWNB0VVodtew=
+polycry.pt/poly-go v0.0.0-20220301085937-fb9d71b45a37/go.mod h1:XUBrNtqgEhN3EEOP/5gh7IBd3xVHKidCjXDZfl9+kMU=
diff --git a/quickstart.sh b/quickstart.sh
new file mode 100755
index 0000000..9189f0f
--- /dev/null
+++ b/quickstart.sh
@@ -0,0 +1,64 @@
+#!/bin/bash
+
+set -e
+
+case "$1" in
+standalone)
+ echo "Using standalone network"
+ ARGS="--local"
+ ;;
+futurenet)
+ echo "Using Futurenet network"
+ ARGS="--futurenet"
+ ;;
+*)
+ echo "Usage: $0 standalone|futurenet"
+ exit 1
+ ;;
+esac
+
+# this is set to the quickstart `soroban-dev` image annointed as the release
+# for a given Soroban Release, it is captured on Soroban Releases - https://soroban.stellar.org/docs/reference/releases
+# QUICKSTART_SOROBAN_DOCKER_SHA=stellar/quickstart:soroban-dev
+QUICKSTART_SOROBAN_DOCKER_SHA=stellar/quickstart:testing@sha256:0c756150e7b3c53603fe36bb932c4e7d7ceaef691906b2d3d952771ccc195559
+
+shift
+
+# Run the soroban-preview container
+# Remember to do:
+# make build-docker
+
+echo "Creating docker soroban network"
+(docker network inspect soroban-network -f '{{.Id}}' 2>/dev/null) \
+ || docker network create soroban-network
+
+echo "Searching for a previous soroban-preview docker container"
+containerID=$(docker ps --filter="name=soroban-preview" --all --quiet)
+if [[ ${containerID} ]]; then
+ echo "Start removing soroban-preview container."
+ docker rm --force soroban-preview
+ echo "Finished removing soroban-preview container."
+else
+ echo "No previous soroban-preview container was found"
+fi
+
+currentDir=$(pwd)
+docker run -dti \
+ --volume ${currentDir}:/workspace \
+ --name soroban-preview \
+ -p 8001:8000 \
+ --ipc=host \
+ --network soroban-network \
+ soroban-preview:10
+
+# Run the stellar quickstart image
+
+docker run --rm -ti \
+ --name stellar \
+ --pull always \
+ --network soroban-network \
+ -p 8000:8000 \
+ "$QUICKSTART_SOROBAN_DOCKER_SHA" \
+ $ARGS \
+ --enable-soroban-rpc \
+ "$@" # Pass through args from the CLI
diff --git a/testdata/docker/build.sh b/testdata/docker/build.sh
new file mode 100755
index 0000000..8f9f02d
--- /dev/null
+++ b/testdata/docker/build.sh
@@ -0,0 +1,7 @@
+#!/bin/bash
+
+# Build image and tag it with image name and version
+docker build . \
+ --tag soroban-preview:10 \
+ --force-rm \
+ --rm
diff --git a/testdata/perun_soroban_contract.wasm b/testdata/perun_soroban_contract.wasm
new file mode 100755
index 0000000..1ae547c
Binary files /dev/null and b/testdata/perun_soroban_contract.wasm differ
diff --git a/testdata/perun_soroban_token.wasm b/testdata/perun_soroban_token.wasm
new file mode 100755
index 0000000..6b5ece4
Binary files /dev/null and b/testdata/perun_soroban_token.wasm differ
diff --git a/wallet/account.go b/wallet/account.go
index e373def..dea881c 100644
--- a/wallet/account.go
+++ b/wallet/account.go
@@ -1,3 +1,17 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
package wallet
import (
diff --git a/wallet/backend.go b/wallet/backend.go
index 4a6a040..477b1e7 100644
--- a/wallet/backend.go
+++ b/wallet/backend.go
@@ -1,3 +1,17 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
package wallet
import (
@@ -35,7 +49,7 @@ func (b backend) DecodeSig(reader io.Reader) (wallet.Sig, error) {
func (b backend) VerifySignature(msg []byte, sig wallet.Sig, a wallet.Address) (bool, error) {
p, ok := a.(*types.Participant)
if !ok {
- return false, errors.New("Participant has invalid type")
+ return false, errors.New("participant has invalid type")
}
if len(sig) != ed25519.SignatureSize {
return false, errors.New("invalid signature size")
diff --git a/wallet/doc.go b/wallet/doc.go
new file mode 100644
index 0000000..cdfbc6d
--- /dev/null
+++ b/wallet/doc.go
@@ -0,0 +1,16 @@
+// Copyright 2024 - See NOTICE file for copyright holders.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package wallet provides the necessary components to use Stellar accounts for Perun payment channels.
+package wallet
diff --git a/wallet/test/init.go b/wallet/test/init.go
deleted file mode 100644
index 4117711..0000000
--- a/wallet/test/init.go
+++ /dev/null
@@ -1,10 +0,0 @@
-package test
-
-import (
- "perun.network/go-perun/wallet/test"
- _ "perun.network/perun-stellar-backend/channel/test"
-)
-
-func init() {
- test.SetRandomizer(&Randomizer{})
-}
diff --git a/wallet/test/randomizer.go b/wallet/test/randomizer.go
index 72d0f3a..8424803 100644
--- a/wallet/test/randomizer.go
+++ b/wallet/test/randomizer.go
@@ -1,3 +1,17 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
package test
import (
diff --git a/wallet/types/address.go b/wallet/types/address.go
index d311e5c..515a000 100644
--- a/wallet/types/address.go
+++ b/wallet/types/address.go
@@ -1,3 +1,17 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
package types
import (
@@ -51,7 +65,7 @@ func (p *Participant) UnmarshalBinary(data []byte) error {
// String returns the string representation of the participant as [ParticipantAddress string]:[public key hex].
func (p Participant) String() string {
- return p.AddressString() + ":" + p.PublicKeyString()
+ return p.AddressString() // + ":" + p.PublicKeyString()
}
func (p Participant) Equal(other wallet.Address) bool {
diff --git a/wallet/wallet.go b/wallet/wallet.go
index 8e502ea..1d9640f 100644
--- a/wallet/wallet.go
+++ b/wallet/wallet.go
@@ -1,3 +1,17 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
package wallet
import (
diff --git a/wallet/wallet_test.go b/wallet/wallet_test.go
index 8ee5525..2d920f8 100644
--- a/wallet/wallet_test.go
+++ b/wallet/wallet_test.go
@@ -1,3 +1,17 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
package wallet_test
import (
diff --git a/wire/balances.go b/wire/balances.go
index b63f210..ef70d86 100644
--- a/wire/balances.go
+++ b/wire/balances.go
@@ -1,3 +1,17 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
package wire
import (
@@ -131,7 +145,6 @@ func (b *Balances) UnmarshalBinary(data []byte) error {
}
func MakeBalances(alloc channel.Allocation) (Balances, error) {
- // TODO: Move all these checks into a compatibility layer
if err := alloc.Valid(); err != nil {
return Balances{}, err
}
@@ -231,6 +244,7 @@ func makeAllocation(asset channel.Asset, balA, balB *big.Int) (*channel.Allocati
alloc := channel.NewAllocation(2, asset)
alloc.SetBalance(0, asset, balA)
alloc.SetBalance(1, asset, balB)
+ alloc.Locked = make([]channel.SubAlloc, 0)
if err := alloc.Valid(); err != nil {
return nil, err
diff --git a/wire/balances_test.go b/wire/balances_test.go
index 3e6f5ee..51c16cc 100644
--- a/wire/balances_test.go
+++ b/wire/balances_test.go
@@ -1,3 +1,17 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
package wire_test
import (
diff --git a/wire/channel.go b/wire/channel.go
index a45b557..2c88095 100644
--- a/wire/channel.go
+++ b/wire/channel.go
@@ -1,3 +1,17 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
package wire
import (
diff --git a/wire/channel_test.go b/wire/channel_test.go
index dd356ad..83d5240 100644
--- a/wire/channel_test.go
+++ b/wire/channel_test.go
@@ -1,3 +1,17 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
package wire_test
import (
diff --git a/wire/control.go b/wire/control.go
index 7d352cb..bc723a0 100644
--- a/wire/control.go
+++ b/wire/control.go
@@ -1,3 +1,17 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
package wire
import (
diff --git a/wire/control_test.go b/wire/control_test.go
index 149f085..b48f6a2 100644
--- a/wire/control_test.go
+++ b/wire/control_test.go
@@ -1,3 +1,17 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
package wire_test
import (
diff --git a/wire/doc.go b/wire/doc.go
new file mode 100644
index 0000000..ece981c
--- /dev/null
+++ b/wire/doc.go
@@ -0,0 +1,17 @@
+// Copyright 2024 - See NOTICE file for copyright holders.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package wire enables communication between go-perun and the Stellar blockchain.
+// It defines the encoding of types required by go-perun and ensures the compatibility to the types used in Soroban smart contracts.
+package wire
diff --git a/wire/params.go b/wire/params.go
index 9dfc68e..bdd82dd 100644
--- a/wire/params.go
+++ b/wire/params.go
@@ -1,3 +1,17 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
package wire
import (
@@ -204,14 +218,20 @@ func ToParams(params Params) (channel.Params, error) {
if err != nil {
return channel.Params{}, err
}
- return channel.Params{
- LedgerChannel: true,
- VirtualChannel: false,
- App: channel.NoApp(),
- Parts: []wallet.Address{&participantA, &participantB},
- Nonce: ToNonce(params.Nonce),
- ChallengeDuration: uint64(params.ChallengeDuration),
- }, nil
+
+ challengeDuration := uint64(params.ChallengeDuration)
+ parts := []wallet.Address{&participantA, &participantB}
+ app := channel.NoApp()
+ nonce := ToNonce(params.Nonce)
+ ledgerChannel := true
+ virtualChannel := false
+
+ perunParams, err := channel.NewParams(challengeDuration, parts, app, nonce, ledgerChannel, virtualChannel)
+ if err != nil {
+ return channel.Params{}, err
+ }
+
+ return *perunParams, nil
}
func MakeNonce(nonce channel.Nonce) xdr.ScBytes {
diff --git a/wire/params_test.go b/wire/params_test.go
index 51ba24b..bb2987d 100644
--- a/wire/params_test.go
+++ b/wire/params_test.go
@@ -1,3 +1,17 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
package wire_test
import (
@@ -7,7 +21,7 @@ import (
ptest "perun.network/go-perun/channel/test"
schannel "perun.network/perun-stellar-backend/channel"
- _ "perun.network/perun-stellar-backend/wallet/test"
+ _ "perun.network/perun-stellar-backend/channel/test"
"perun.network/perun-stellar-backend/wire"
pkgtest "polycry.pt/poly-go/test"
diff --git a/wire/participant.go b/wire/participant.go
index b689c62..25cf0d0 100644
--- a/wire/participant.go
+++ b/wire/participant.go
@@ -1,3 +1,17 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
package wire
import (
diff --git a/wire/participant_test.go b/wire/participant_test.go
index ef82384..d565952 100644
--- a/wire/participant_test.go
+++ b/wire/participant_test.go
@@ -1,3 +1,17 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
package wire_test
import (
diff --git a/wire/scmap.go b/wire/scmap.go
index 93e6321..4965eb9 100644
--- a/wire/scmap.go
+++ b/wire/scmap.go
@@ -1,3 +1,17 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
package wire
import (
diff --git a/wire/scval/bool.go b/wire/scval/bool.go
index cec5fc4..99ee45f 100644
--- a/wire/scval/bool.go
+++ b/wire/scval/bool.go
@@ -1,3 +1,17 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
package scval
import "github.com/stellar/go/xdr"
diff --git a/wire/scval/scval.go b/wire/scval/scval.go
index 8f1f2cd..9bae5b5 100644
--- a/wire/scval/scval.go
+++ b/wire/scval/scval.go
@@ -1,3 +1,17 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
package scval
import "github.com/stellar/go/xdr"
@@ -50,6 +64,18 @@ func MustWrapScSymbol(symbol xdr.ScSymbol) xdr.ScVal {
return v
}
+func WrapScString(str xdr.ScString) (xdr.ScVal, error) {
+ return xdr.NewScVal(xdr.ScValTypeScvString, str)
+}
+
+func MustWrapScString(str xdr.ScString) xdr.ScVal {
+ v, err := WrapScString(str)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
func WrapScBytes(b xdr.ScBytes) (xdr.ScVal, error) {
return xdr.NewScVal(xdr.ScValTypeScvBytes, b)
}
diff --git a/wire/state.go b/wire/state.go
index 70c4aa8..eeaa6f9 100644
--- a/wire/state.go
+++ b/wire/state.go
@@ -1,3 +1,17 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
package wire
import (
diff --git a/wire/state_test.go b/wire/state_test.go
index 1c93888..633676d 100644
--- a/wire/state_test.go
+++ b/wire/state_test.go
@@ -1,3 +1,17 @@
+// Copyright 2023 PolyCrypt GmbH
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
package wire_test
import (
@@ -6,6 +20,7 @@ import (
"math/big"
"perun.network/go-perun/channel"
ptest "perun.network/go-perun/channel/test"
+ _ "perun.network/perun-stellar-backend/channel/test"
"perun.network/perun-stellar-backend/wire"
polytest "polycry.pt/poly-go/test"
"testing"