From be52c1dad5430f34a64fc98d1e467ac8cfa6773c Mon Sep 17 00:00:00 2001 From: YarikRevich Date: Tue, 15 Aug 2023 13:03:58 +0200 Subject: [PATCH 001/134] feature: added more test cases --- generate_mocks.sh | 3 + go.mod | 40 ++-- go.sum | 363 ++++++++++++++++------------------- wasmsdk/bridge.go | 8 +- zcnbridge/bridge.go | 136 ++++++------- zcnbridge/bridge_test.go | 187 +++++++++++++++--- zcnbridge/config.go | 29 ++- zcnbridge/ethereum_wallet.go | 110 ----------- zcnswap/utils/ethutils.go | 41 +++- 9 files changed, 476 insertions(+), 441 deletions(-) delete mode 100644 zcnbridge/ethereum_wallet.go diff --git a/generate_mocks.sh b/generate_mocks.sh index 6e619c31f..54afade72 100755 --- a/generate_mocks.sh +++ b/generate_mocks.sh @@ -10,4 +10,7 @@ mockery --output=./mocks --all cd $BASEDIR/zcncore || exit mockery --output=./mocks --all +cd $BASEDIR/zcnbridge || exit +mockery --output=./mocks --all + echo "Mocks files are generated." \ No newline at end of file diff --git a/go.mod b/go.mod index dc0c1a9e9..2d198cbf2 100644 --- a/go.mod +++ b/go.mod @@ -9,7 +9,7 @@ require ( github.com/btcsuite/btcd v0.23.4 github.com/dgraph-io/badger/v3 v3.2103.5 github.com/didip/tollbooth v4.0.2+incompatible - github.com/ethereum/go-ethereum v1.10.26 + github.com/ethereum/go-ethereum v1.12.0 github.com/google/uuid v1.3.0 github.com/gorilla/handlers v1.5.1 github.com/gorilla/mux v1.8.0 @@ -43,62 +43,70 @@ require ( gopkg.in/yaml.v3 v3.0.1 ) -require ( - github.com/deckarep/golang-set v1.8.0 // indirect - github.com/go-logfmt/logfmt v0.5.1 // indirect - github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d - github.com/rjeczalik/notify v0.9.1 // indirect - gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect -) +require github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d require ( + github.com/DataDog/zstd v1.5.2 // indirect github.com/VictoriaMetrics/fastcache v1.6.0 // indirect + github.com/beorn7/perks v1.0.1 // indirect github.com/btcsuite/btcd/btcec/v2 v2.3.2 // indirect github.com/btcsuite/btcd/chaincfg/chainhash v1.0.2 // indirect github.com/cespare/xxhash v1.1.0 // indirect github.com/cespare/xxhash/v2 v2.2.0 // indirect + github.com/cockroachdb/errors v1.9.1 // indirect + github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect + github.com/cockroachdb/pebble v0.0.0-20230209160836-829675f94811 // indirect + github.com/cockroachdb/redact v1.1.3 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect + github.com/deckarep/golang-set/v2 v2.1.0 // indirect github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 // indirect github.com/dgraph-io/ristretto v0.1.1 // indirect github.com/dustin/go-humanize v1.0.1 // indirect - github.com/edsrzf/mmap-go v1.0.0 // indirect github.com/felixge/httpsnoop v1.0.3 // indirect github.com/fjl/memsize v0.0.0-20190710130421-bcb5799ab5e5 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff // indirect + github.com/getsentry/sentry-go v0.18.0 // indirect github.com/go-ole/go-ole v1.2.6 // indirect github.com/go-stack/stack v1.8.1 // indirect + github.com/gofrs/flock v0.8.1 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang-jwt/jwt/v4 v4.3.0 // indirect github.com/golang/glog v1.0.0 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/golang/protobuf v1.5.2 // indirect - github.com/golang/snappy v0.0.4 // indirect + github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb // indirect github.com/google/flatbuffers v22.9.29+incompatible // indirect github.com/gorilla/websocket v1.5.0 // indirect github.com/hashicorp/go-bexpr v0.1.10 // indirect github.com/hashicorp/go-cleanhttp v0.5.2 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/holiman/bloomfilter/v2 v2.0.3 // indirect - github.com/holiman/uint256 v1.2.0 // indirect + github.com/holiman/uint256 v1.2.2-0.20230321075855-87b91420868c // indirect github.com/huin/goupnp v1.0.3 // indirect github.com/jackpal/go-nat-pmp v1.0.2 // indirect github.com/kr/pretty v0.3.1 // indirect + github.com/kr/text v0.2.0 // indirect github.com/labstack/gommon v0.4.0 // indirect github.com/magiconair/properties v1.8.7 // indirect github.com/matryer/is v1.4.1 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.17 // indirect github.com/mattn/go-runewidth v0.0.14 // indirect + github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect github.com/mitchellh/pointerstructure v1.2.0 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/patrickmn/go-cache v2.1.0+incompatible // indirect github.com/pelletier/go-toml/v2 v2.0.6 // indirect github.com/philhofer/fwd v1.1.2-0.20210722190033-5c56ac6d0bb9 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/prometheus/tsdb v0.7.1 // indirect + github.com/prometheus/client_golang v1.14.0 // indirect + github.com/prometheus/client_model v0.3.0 // indirect + github.com/prometheus/common v0.39.0 // indirect + github.com/prometheus/procfs v0.9.0 // indirect github.com/rivo/uniseg v0.4.3 // indirect + github.com/rogpeppe/go-internal v1.9.0 // indirect github.com/rs/cors v1.7.0 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/shirou/gopsutil v3.21.11+incompatible // indirect @@ -119,8 +127,9 @@ require ( github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect go.dedis.ch/fixbuf v1.0.3 // indirect go.opencensus.io v0.24.0 // indirect - golang.org/x/sys v0.5.0 // indirect - golang.org/x/text v0.7.0 // indirect + golang.org/x/exp v0.0.0-20230206171751-46f607a40771 // indirect + golang.org/x/sys v0.7.0 // indirect + golang.org/x/text v0.8.0 // indirect google.golang.org/protobuf v1.28.1 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce // indirect @@ -128,13 +137,12 @@ require ( require ( github.com/btcsuite/btcd/btcutil v1.1.3 - github.com/go-kit/kit v0.10.0 // indirect github.com/klauspost/compress v1.16.0 // indirect github.com/klauspost/cpuid/v2 v2.2.4 // indirect github.com/yusufpapurcu/wmi v1.2.2 // indirect go.uber.org/atomic v1.10.0 // indirect go.uber.org/multierr v1.9.0 // indirect - golang.org/x/net v0.7.0 // indirect + golang.org/x/net v0.8.0 // indirect golang.org/x/time v0.3.0 // indirect google.golang.org/genproto v0.0.0-20230216225411-c8e22ba71e44 // indirect ) diff --git a/go.sum b/go.sum index 4eed7ae32..c20718b07 100644 --- a/go.sum +++ b/go.sum @@ -44,46 +44,39 @@ github.com/0chain/common v0.0.6-0.20230127095721-8df4d1d72565 h1:z+DtCR8mBsjPnEs github.com/0chain/common v0.0.6-0.20230127095721-8df4d1d72565/go.mod h1:UyDC8Qyl5z9lGkCnf9RHJPMektnFX8XtCJZHXCCVj8E= github.com/0chain/errors v1.0.3 h1:QQZPFxTfnMcRdt32DXbzRQIfGWmBsKoEdszKQDb0rRM= github.com/0chain/errors v1.0.3/go.mod h1:xymD6nVgrbgttWwkpSCfLLEJbFO6iHGQwk/yeSuYkIc= +github.com/AndreasBriese/bbloom v0.0.0-20190306092124-e2d15f34fcf9/go.mod h1:bOvUY6CB00SOBii9/FifXqc0awNKxLFCL/+pkDPuyl8= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/CloudyKit/fastprinter v0.0.0-20200109182630-33d98a066a53/go.mod h1:+3IMCy2vIlbG1XG/0ggNQv0SvxCAIpPM5b1nCz56Xno= +github.com/CloudyKit/jet/v3 v3.0.0/go.mod h1:HKQPgSJmdK8hdoAbKUUWajkHyHo4RaU5rMdUywE7VMo= github.com/DATA-DOG/go-sqlmock v1.3.3/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= -github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= +github.com/DataDog/zstd v1.5.2 h1:vUG4lAyuPCXO0TLbXvPv7EB7cNK1QV/luu55UHLrrn8= +github.com/DataDog/zstd v1.5.2/go.mod h1:g4AWEaM3yOg3HYfnJ3YIawPnVdXJh9QME85blwSAmyw= +github.com/Joker/hpp v1.0.0/go.mod h1:8x5n+M1Hp5hC0g8okX3sR3vFQwynaX/UgSOM9MeBKzY= github.com/Luzifer/go-openssl/v3 v3.1.0 h1:QqKqo6kYXGGUsvtUoCpRZm8lHw+jDfhbzr36gVj+/gw= github.com/Luzifer/go-openssl/v3 v3.1.0/go.mod h1:liy3FXuuS8hfDlYh1T+l78AwQ/NjZflJz0NDvjKhwDs= github.com/OneOfOne/xxhash v1.2.2 h1:KMrpdQIwFcEqXDklaen+P1axHaj9BSKzvpUUfnHldSE= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= -github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo= -github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI= +github.com/Shopify/goreferrer v0.0.0-20181106222321-ec9c9a553398/go.mod h1:a1uqRtAwp2Xwc6WNPJEufxJ7fx3npB4UV/JOLmbu5I0= github.com/VictoriaMetrics/fastcache v1.6.0 h1:C/3Oi3EiBCqufydp1neRZkqcwmEiuRT9c3fqvvgKm5o= github.com/VictoriaMetrics/fastcache v1.6.0/go.mod h1:0qHz5QP0GMX4pfmMA/zt5RgfNuXJrTP0zS7DqpHGGTw= -github.com/VividCortex/gohistogram v1.0.0/go.mod h1:Pf5mBqqDxYaXu3hDrrU+w6nw50o/4+TcAqDqk/vUH7g= github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII= -github.com/afex/hystrix-go v0.0.0-20180502004556-fa1af6a1f4f5/go.mod h1:SkGFH1ia65gfNATL8TAiHDNxPzPdmEL5uirI2Uyuz6c= +github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY= github.com/ajstarks/svgo v0.0.0-20180226025133-644b8db467af/go.mod h1:K08gAheRH3/J6wwsYMMT4xOr94bZjxIelGM0+d/wbFw= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= -github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= -github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156 h1:eMwmnE/GDgah4HI848JfFxHt+iPb26b4zyfspmqY0/8= github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8= github.com/apache/arrow/go/arrow v0.0.0-20191024131854-af6fa24be0db/go.mod h1:VTxUBvSJ3s3eHAg65PNgrsn5BtqCRPdmyXh6rAfdxN0= -github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= -github.com/apache/thrift v0.13.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= -github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= -github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= -github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= -github.com/aryann/difflib v0.0.0-20170710044230-e206f873d14a/go.mod h1:DAHtR1m6lCRdSC2Tm3DSWRPvIPr6xNKyeHdqDQSQT+A= -github.com/aws/aws-lambda-go v1.13.3/go.mod h1:4UKl9IzQMoD+QF79YdCuzCwp8VbmG4VAQwij/eHl5CU= -github.com/aws/aws-sdk-go v1.27.0/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= -github.com/aws/aws-sdk-go-v2 v0.18.0/go.mod h1:JWVYvqSMppoMJC0x5wdwiImzgXTI9FuZwxzkQq9wy+g= +github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8= github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= -github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/bmizerany/pat v0.0.0-20170815010413-6226ea591a40/go.mod h1:8rLXio+WjiTceGBHIoTvn60HIbs7Hm7bcHjyrSqYB9c= github.com/boltdb/bolt v1.3.1/go.mod h1:clJnj/oiGkjum5o1McbSZDSLxVThjynRyGBgiAx27Ps= github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ= @@ -113,8 +106,6 @@ github.com/btcsuite/snappy-go v1.0.0/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY= github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs= github.com/c-bata/go-prompt v0.2.2/go.mod h1:VzqtzE2ksDBcdln8G7mk2RX9QyGjH+OVqOCSiVIqS34= -github.com/casbin/casbin/v2 v2.1.2/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ= -github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/cp v0.1.0 h1:SE+dxFebS7Iik5LK0tsi1k9ZCxEaFX4AjQmoyA+1dJk= github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko= @@ -125,37 +116,43 @@ github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XL github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= -github.com/clbanning/x2j v0.0.0-20191024224557-825249438eec/go.mod h1:jMjuTZXRI4dUb/I5gc9Hdhagfvm9+RyrPryS/auMzxE= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= -github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= -github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= +github.com/cockroachdb/datadriven v1.0.2 h1:H9MtNqVoVhvd9nCBwOyDjUEdZCREqbIdCJD93PBm/jA= +github.com/cockroachdb/datadriven v1.0.2/go.mod h1:a9RdTaap04u637JoCzcUoIcDmvwSUtcUFtT/C3kJlTU= +github.com/cockroachdb/errors v1.9.1 h1:yFVvsI0VxmRShfawbt/laCIDy/mtTqqnvoNgiy5bEV8= +github.com/cockroachdb/errors v1.9.1/go.mod h1:2sxOtL2WIc096WSZqZ5h8fa17rdDq9HZOZLBCor4mBk= +github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= +github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= +github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= +github.com/cockroachdb/pebble v0.0.0-20230209160836-829675f94811 h1:ytcWPaNPhNoGMWEhDvS3zToKcDpRsLuRolQJBVGdozk= +github.com/cockroachdb/pebble v0.0.0-20230209160836-829675f94811/go.mod h1:Nb5lgvnQ2+oGlE/EyZy4+2/CxRh9KfvCXnag1vtpxVM= +github.com/cockroachdb/redact v1.1.3 h1:AKZds10rFSIj7qADf0g46UixK8NNLwWTNdCIGS5wfSQ= +github.com/cockroachdb/redact v1.1.3/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= +github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0/go.mod h1:4Zcjuz89kmFXt9morQgcfYZAYZ5n8WHjt81YYWIwtTM= github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= -github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= -github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= -github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/dave/jennifer v1.2.0/go.mod h1:fIb+770HOpJ2fmN9EPPKOqm1vMGhB+TwXKMZhrIygKg= github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 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/deckarep/golang-set v1.8.0 h1:sk9/l/KqpunDwP7pSjUg0keiOOLEnOBHzykLrsPppp4= -github.com/deckarep/golang-set v1.8.0/go.mod h1:5nI87KwE7wgsBU1F4GKAw2Qod7p5kyS383rP6+o6qqo= +github.com/deckarep/golang-set/v2 v2.1.0 h1:g47V4Or+DUdzbs8FxCCmgb6VYd+ptPAngjM6dtGktsI= +github.com/deckarep/golang-set/v2 v2.1.0/go.mod h1:VAky9rY/yGXJOLEDv3OMci+7wtDpOF4IN+y82NBOac4= github.com/decred/dcrd/crypto/blake256 v1.0.0 h1:/8DMNYp9SGi5f0w7uCm6d6M4OU2rGFK09Y2A4Xv7EE0= github.com/decred/dcrd/crypto/blake256 v1.0.0/go.mod h1:sQl2p6Y26YV+ZOcSTP6thNdn47hh8kt6rqSlvmrXFAc= github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1/go.mod h1:hyedUtir6IdtD/7lIxGeCxkaw7y45JueMRL4DIyJDKs= github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 h1:HbphB4TFFXpv7MNrT52FGrrgVXF1owhMVTHFZIlnvd4= github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0/go.mod h1:DZGJHZMqrU4JJqFAWUS2UO1+lbSKsdiOoYi9Zzey7Fc= github.com/decred/dcrd/lru v1.0.0/go.mod h1:mxKOwFd7lFjN2GZYsiz/ecgqR6kkYAl+0pz0tEMk218= +github.com/dgraph-io/badger v1.6.0/go.mod h1:zwt7syl517jmP8s94KqSxTlM6IMsdhYy6psNgSztDR4= github.com/dgraph-io/badger/v3 v3.2103.5 h1:ylPa6qzbjYRQMU6jokoj4wzcaweHylt//CH0AKt0akg= github.com/dgraph-io/badger/v3 v3.2103.5/go.mod h1:4MPiseMeDQ3FNCYwRbbcBOGJLf5jsE0PPFzRiKjtcdw= github.com/dgraph-io/ristretto v0.1.1 h1:6CWw5tJNgpegArSHpNHJKldNeq03FQCwYvfMVWajOK8= @@ -164,75 +161,78 @@ github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZm github.com/dgryski/go-bitstream v0.0.0-20180413035011-3522498ce2c8/go.mod h1:VMaSuZ+SZcx/wljOQKvp5srsbCiKDEb6K2wC4+PiBmQ= github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2 h1:tdlZCpZ/P9DhczCTSixgIKmwPv6+wP5DGjqLYw5SUiA= github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= -github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= github.com/didip/tollbooth v4.0.2+incompatible h1:fVSa33JzSz0hoh2NxpwZtksAzAgd7zjmGO20HCZtF4M= github.com/didip/tollbooth v4.0.2+incompatible/go.mod h1:A9b0665CE6l1KmzpDws2++elm/CsuWBMa5Jv4WY0PEY= -github.com/dustin/go-humanize v0.0.0-20171111073723-bb3d318650d4/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= -github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs= -github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU= -github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I= github.com/eclipse/paho.mqtt.golang v1.2.0/go.mod h1:H9keYFcgq3Qr5OUJm/JZI/i6U7joQ8SYLhZwfeOo6Ts= -github.com/edsrzf/mmap-go v1.0.0 h1:CEBF7HpRnUCSJgGUb5h1Gm7e3VkmVDrR8lvWVLtrOFw= -github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= -github.com/envoyproxy/go-control-plane v0.6.9/go.mod h1:SBwIajubJHhxtWwsL9s8ss4safvEdbitLhGGK48rN6g= +github.com/eknkc/amber v0.0.0-20171010120322-cdade1c07385/go.mod h1:0vRUJqYpeSZifjYj7uP3BG/gKcuzL9xWVV/Y+cK33KM= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5ynNVH9qI8YYLbd1fK2po= github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= +github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/ethereum/go-ethereum v1.10.26 h1:i/7d9RBBwiXCEuyduBQzJw/mKmnvzsN14jqBmytw72s= -github.com/ethereum/go-ethereum v1.10.26/go.mod h1:EYFyF19u3ezGLD4RqOkLq+ZCXzYbLoNDdZlMt7kyKFg= -github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= +github.com/etcd-io/bbolt v1.3.3/go.mod h1:ZF2nL25h33cCyBtcyWeZ2/I3HQOfTP+0PIEvHjkjCrw= +github.com/ethereum/go-ethereum v1.12.0 h1:bdnhLPtqETd4m3mS8BGMNvBTf36bO5bx/hxE2zljOa0= +github.com/ethereum/go-ethereum v1.12.0/go.mod h1:/oo2X/dZLJjf2mJ6YT9wcWxa4nNJDBKDBU6sFIpx1Gs= +github.com/fasthttp-contrib/websocket v0.0.0-20160511215533-1f3b11f56072/go.mod h1:duJ4Jxv5lDcvg4QuQr0oowTf7dz4/CR8NtyCooz9HL8= github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w= +github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= github.com/felixge/httpsnoop v1.0.1/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/felixge/httpsnoop v1.0.3 h1:s/nj+GCswXYzN5v2DpNMuMQYe+0DDwt5WVCU6CWBdXk= github.com/felixge/httpsnoop v1.0.3/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/fjl/memsize v0.0.0-20190710130421-bcb5799ab5e5 h1:FtmdgXiUlNeRsoNMFlKLDt+S+6hbjVMEW6RGQ7aUf7c= github.com/fjl/memsize v0.0.0-20190710130421-bcb5799ab5e5/go.mod h1:VvhXpOYNQvB+uIk2RvXzuaQtkQJzzIx6lSBe1xv7hi0= github.com/fogleman/gg v1.2.1-0.20190220221249-0403632d5b90/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k= -github.com/franela/goblin v0.0.0-20200105215937-c9ffbefa60db/go.mod h1:7dvUGVsVBjqR7JHJk0brhHOZYGmfBYOrK0ZhYMEtBr4= -github.com/franela/goreq v0.0.0-20171204163338-bcd34c9993f8/go.mod h1:ZhphrRTfi2rbfLwlschooIH4+wKKDR4Pdxhh+TRoA20= github.com/frankban/quicktest v1.14.3 h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= +github.com/gavv/httpexpect v2.0.0+incompatible/go.mod h1:x+9tiU1YnrOvnB725RkpoLv1M62hOWzwo5OXotisrKc= github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff h1:tY80oXqGNY4FhTFhk+o9oFHGINQ/+vhlm8HFzi6znCI= github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff/go.mod h1:x7DCsMOv1taUwEWCzT4cmDeAkigA5/QCwUodaVOe8Ww= -github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/getsentry/sentry-go v0.12.0/go.mod h1:NSap0JBYWzHND8oMbyi0+XZhUalc1TBdRL1M71JZW2c= +github.com/getsentry/sentry-go v0.18.0 h1:MtBW5H9QgdcJabtZcuJG80BMOwaBpkRDZkxRkNC1sN0= +github.com/getsentry/sentry-go v0.18.0/go.mod h1:Kgon4Mby+FJ7ZWHFUAZgVaIa8sxHtnRJRLTXZr51aKQ= +github.com/gin-contrib/sse v0.0.0-20190301062529-5545eab6dad3/go.mod h1:VJ0WA2NBN22VlZ2dKZQPAPnyWw5XTlK1KymzLKsr59s= +github.com/gin-gonic/gin v1.4.0/go.mod h1:OW2EZn3DO8Ln9oIKOvM++LBO+5UPHJJDH72/q/3rZdM= github.com/glycerine/go-unsnap-stream v0.0.0-20180323001048-9f0cb55181dd/go.mod h1:/20jfyN9Y5QPEAprSgKAUr+glWDY39ZiUEAYOEv5dsE= github.com/glycerine/goconvey v0.0.0-20190410193231-58a59202ab31/go.mod h1:Ogl1Tioa0aV7gstGFO7KhffUsb9M4ydbEbbxpcEDc24= +github.com/go-check/check v0.0.0-20180628173108-788fd7840127/go.mod h1:9ES+weclKsC9YodN5RgxqK/VD9HM9JsCSh7rNhMZE98= +github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q= +github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-kit/kit v0.10.0 h1:dXFJfIHVvUcpSgDOV+Ne6t7jXri8Tfv2uOLHUZ2XNuo= -github.com/go-kit/kit v0.10.0/go.mod h1:xUsJbQ/Fp4kEt7AFgCuvyX4a71u8h9jB8tj/ORgOZ7o= github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= -github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= -github.com/go-logfmt/logfmt v0.5.1 h1:otpy5pqBCBZ1ng9RQ0dPu4PN7ba75Y/aA+UpowDyNVA= -github.com/go-logfmt/logfmt v0.5.1/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= +github.com/go-martini/martini v0.0.0-20170121215854-22fa46961aab/go.mod h1:/P9AEU963A2AYjv4d1V5eVL1CQbEJq6aCNHDDjibzu8= github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY= github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= -github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/go-stack/stack v1.8.1 h1:ntEHSVwIt7PNXNpgPmVfMrNhLtgjlmnZha2kOpuRiDw= github.com/go-stack/stack v1.8.1/go.mod h1:dcoOX6HbPZSZptuspn9bctJ+N/CnF5gGygcUP3XYfe4= +github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee/go.mod h1:L0fX3K22YWvt/FAX9NnzrNzcI4wNYi9Yku4O0LKYflo= +github.com/gobwas/pool v0.2.0/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= +github.com/gobwas/ws v1.0.2/go.mod h1:szmBTxLgaFppYjEmNtny/v3w89xOydFnnZMcgRRu/EM= +github.com/gofrs/flock v0.8.1 h1:+gYjHKf32LDeiEEFhQaotPbLuUXjY5ZqxKgXy7n59aw= +github.com/gofrs/flock v0.8.1/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU= github.com/gofrs/uuid v3.3.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= -github.com/gogo/googleapis v1.1.0/go.mod h1:gf4bu3Q80BeJ6H1S1vYPm8/ELATdvryBaNFGgqEef3s= +github.com/gogo/googleapis v0.0.0-20180223154316-0cd9801be74a/go.mod h1:gf4bu3Q80BeJ6H1S1vYPm8/ELATdvryBaNFGgqEef3s= +github.com/gogo/googleapis v1.4.1/go.mod h1:2lpHqI5OcWCtVElxXnPt+s8oJvMpySlOyM6xDCrzib4= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= -github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/gogo/status v1.1.0/go.mod h1:BFv9nrluPLmrS0EmGVvLaPNmRosr9KapBYd5/hpY1WM= +github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= github.com/golang-jwt/jwt/v4 v4.3.0 h1:kHL1vqdqWNfATmA0FNMdmZNMyZI1U6O31X4rlIPoBog= github.com/golang-jwt/jwt/v4 v4.3.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg= github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= @@ -240,7 +240,6 @@ github.com/golang/geo v0.0.0-20190916061304-5b978397cfec/go.mod h1:QZ0nwyI2jOfgR github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/glog v1.0.0 h1:nfP3RFugxnNRyKgeWd4oI1nYvXpxrx8ck8ZrcizshdQ= github.com/golang/glog v1.0.0/go.mod h1:EWib/APOK0SL3dFbYqvxE3UYd8E6s1ouQ7iEp/0LWV4= -github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= @@ -272,8 +271,10 @@ github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= -github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb h1:PBC98N2aIaM3XXiurYmW7fx4GZkL8feAMVq7nEjURHk= +github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/gomodule/redigo v1.7.1-0.20190724094224-574c33c3df38/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/flatbuffers v1.11.0/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8= @@ -292,6 +293,7 @@ github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= +github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= @@ -307,7 +309,6 @@ github.com/google/pprof v0.0.0-20201023163331-3e6fc7fc9c4c/go.mod h1:kpwsk12EmLe github.com/google/pprof v0.0.0-20201203190320-1bf35d6f28c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20201218002935-b9804c9f04c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= -github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= @@ -316,43 +317,24 @@ github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+ github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= -github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= github.com/gorilla/handlers v1.5.1 h1:9lRY6j8DEeeBT10CvO9hGW0gmky0BprnvDI5vfhUHH4= github.com/gorilla/handlers v1.5.1/go.mod h1:t8XrUpc4KVXb7HGyJ4/cEnwQiaxrX/hz1Zv/4g96P1Q= -github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= -github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= -github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= +github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= -github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= -github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= -github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/h2non/filetype v1.1.3 h1:FKkx9QbD7HR/zjK1Ia5XiBsq9zdLi5Kf3zGyFTAFkGg= github.com/h2non/filetype v1.1.3/go.mod h1:319b3zT68BvV+WRj7cwy856M2ehB3HqNOt6sy1HndBY= -github.com/hashicorp/consul/api v1.3.0/go.mod h1:MmDNSzIMUjNpY/mQ398R4bk2FnqQLoPndWW5VkKPlCE= -github.com/hashicorp/consul/sdk v0.3.0/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= -github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/go-bexpr v0.1.10 h1:9kuI5PFotCboP3dkDYFr/wi0gg0QVbSNz5oFRpxn4uE= github.com/hashicorp/go-bexpr v0.1.10/go.mod h1:oxlubA2vC/gFVfX1A6JGp7ls7uCDlfJn732ehYYg+g0= -github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= github.com/hashicorp/go-hclog v0.9.2/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrjA0H7acj2lQ= github.com/hashicorp/go-hclog v1.2.0 h1:La19f8d7WIlm4ogzNHB0JGqs5AUDAZ2UfCY4sJXcJdM= -github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= -github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= -github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= github.com/hashicorp/go-retryablehttp v0.7.2 h1:AcYqCvkpalPnPF2pn0KamgwamS42TqUDDYFRKq/RAd0= github.com/hashicorp/go-retryablehttp v0.7.2/go.mod h1:Jy/gPYAdjqffZ/yFGCFV2doI5wjtH1ewM9u8iYVjtX8= -github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU= -github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU= -github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4= -github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= -github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d h1:dg1dEPuWpEqDnvIw251EVy4zlP8gWbsGj4BsUKCRpYs= @@ -361,44 +343,42 @@ github.com/hashicorp/golang-lru/v2 v2.0.1 h1:5pv5N1lT1fjLg2VQ5KWc7kmucp2x/kvFOnx github.com/hashicorp/golang-lru/v2 v2.0.1/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= -github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= -github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ= -github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= -github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= github.com/herumi/bls-go-binary v1.31.0 h1:L1goQ2tMtGgpXCg5AwHAdJQpLs/pfnWWEc3Wog6OhmI= github.com/herumi/bls-go-binary v1.31.0/go.mod h1:O4Vp1AfR4raRGwFeQpr9X/PQtncEicMoOe6BQt1oX0Y= github.com/holiman/bloomfilter/v2 v2.0.3 h1:73e0e/V0tCydx14a0SCYS/EWCxgwLZ18CZcZKVu0fao= github.com/holiman/bloomfilter/v2 v2.0.3/go.mod h1:zpoh+gs7qcpqrHr3dB55AMiJwo0iURXE7ZOP9L9hSkA= -github.com/holiman/uint256 v1.2.0 h1:gpSYcPLWGv4sG43I2mVLiDZCNDh/EpGjSk8tmtxitHM= -github.com/holiman/uint256 v1.2.0/go.mod h1:y4ga/t+u+Xwd7CpDgZESaRcWy0I7XMlTMA25ApIH5Jw= +github.com/holiman/uint256 v1.2.2-0.20230321075855-87b91420868c h1:DZfsyhDK1hnSS5lH8l+JggqzEleHteTYfutAiVlSUM8= +github.com/holiman/uint256 v1.2.2-0.20230321075855-87b91420868c/go.mod h1:SC8Ryt4n+UBbPbIBKaG9zbbDlp4jOru9xFZmPzLUTxw= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= -github.com/hudl/fargo v1.3.0/go.mod h1:y3CKSmjA+wD2gak7sUSXTAoopbhU08POFhmITJgmKTg= github.com/huin/goupnp v1.0.3 h1:N8No57ls+MnjlB+JPiCVSOyy/ot7MJTqlo7rn+NYSqQ= github.com/huin/goupnp v1.0.3/go.mod h1:ZxNlw5WqJj6wSsRK5+YfflQGXYfccj5VgQsMNixHM7Y= github.com/huin/goutil v0.0.0-20170803182201-1ca381bf3150/go.mod h1:PpLOETDnJ0o3iZrZfqZzyLl6l7F3c6L1oWn7OICBi6o= +github.com/hydrogen18/memlistener v0.0.0-20200120041712-dcc25e7acd91/go.mod h1:qEIFzExnS6016fRpRfxrExeVn2gbClQA99gQhnIcdhE= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/CoI+jC3w2iA= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/influxdata/flux v0.65.1/go.mod h1:J754/zds0vvpfwuq7Gc2wRdVwEodfpCFM7mYlOw2LqY= github.com/influxdata/influxdb v1.8.3 h1:WEypI1BQFTT4teLM+1qkEcvUi0dAvopAI/ir0vAiBg8= github.com/influxdata/influxdb v1.8.3/go.mod h1:JugdFhsvvI8gadxOI6noqNeeBHvWNTbfYGtiAn+2jhI= -github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo= github.com/influxdata/influxql v1.1.1-0.20200828144457-65d3ef77d385/go.mod h1:gHp9y86a/pxhjJ+zMjNXiQAA197Xk9wLxaz+fGG+kWk= github.com/influxdata/line-protocol v0.0.0-20180522152040-32c6aa80de5e/go.mod h1:4kt73NQhadE3daL3WhR5EJ/J2ocX0PZzwxQ0gXJ7oFE= github.com/influxdata/promql/v2 v2.12.0/go.mod h1:fxOPu+DY0bqCTCECchSRtWfc+0X19ybifQhZoQNF5D8= github.com/influxdata/roaring v0.4.13-0.20180809181101-fc520f41fab6/go.mod h1:bSgUQ7q5ZLSO+bKBGqJiCBGAl+9DxyW63zLTujjUlOE= github.com/influxdata/tdigest v0.0.0-20181121200506-bf2b5ad3c0a9/go.mod h1:Js0mqiSBE6Ffsg94weZZ2c+v/ciT8QRHFOap7EKDrR0= github.com/influxdata/usage-client v0.0.0-20160829180054-6d3895376368/go.mod h1:Wbbw6tYNvwa5dlB6304Sd+82Z3f7PmVZHVKU637d4po= +github.com/iris-contrib/blackfriday v2.0.0+incompatible/go.mod h1:UzZ2bDEoaSGPbkg6SAB4att1aAwTmVIx/5gCVqeyUdI= +github.com/iris-contrib/go.uuid v2.0.0+incompatible/go.mod h1:iz2lgM/1UnEf1kP0L/+fafWORmlnuysV2EMP8MW+qe0= +github.com/iris-contrib/jade v1.1.3/go.mod h1:H/geBymxJhShH5kecoiOCSssPX7QWYH7UaeZTSWddIk= +github.com/iris-contrib/pongo2 v0.0.1/go.mod h1:Ssh+00+3GAZqSQb30AvBRNxBx7rf0GqwkjqxNd0u65g= +github.com/iris-contrib/schema v0.0.1/go.mod h1:urYA3uvUNG1TIIjOSCzHr9/LmbQo8LrOcOqfqxa4hXw= github.com/jackpal/go-nat-pmp v1.0.2 h1:KzKSgb7qkJvOUTqYl9/Hg/me3pWgBmERKrTGD7BdWus= github.com/jackpal/go-nat-pmp v1.0.2/go.mod h1:QPH045xvCAeXUZOxsnwmrtiCoxIr9eob+4orBN1SBKc= github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= -github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= -github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= github.com/jrick/logrotate v1.0.0/go.mod h1:LNinyqDIJnpAur+b8yyulnQw/wDuN1+BYKlTRt3OuAQ= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= -github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/json-iterator/go v1.1.8/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= github.com/jsternberg/zap-logfmt v1.0.0/go.mod h1:uvPs/4X51zdkcm5jXl5SYoN+4RK21K8mysFmDaM/h+o= @@ -406,16 +386,24 @@ github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfV github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= github.com/jung-kurt/gofpdf v1.0.3-0.20190309125859-24315acbbda5/go.mod h1:7Id9E/uU8ce6rXgefFLlgrJj/GYY22cpxn+r32jIOes= github.com/jwilder/encoding v0.0.0-20170811194829-b4e1701a28ef/go.mod h1:Ct9fl0F6iIOGgxJ5npU/IUOhOhqlVrGjyIZc8/MagT0= -github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= +github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88/go.mod h1:3w7q1U84EfirKl04SVQ/s7nPm1ZPhiXd34z40TNz36k= +github.com/kataras/golog v0.0.10/go.mod h1:yJ8YKCmyL+nWjERB90Qwn+bdyBZsaQwU3bTVFgkFIp8= +github.com/kataras/iris/v12 v12.1.8/go.mod h1:LMYy4VlP67TQ3Zgriz8RE2h2kMZV2SgMYbq3UhfoFmE= +github.com/kataras/neffos v0.0.14/go.mod h1:8lqADm8PnbeFfL7CLXh1WHw53dG27MC3pgi2R1rmoTE= +github.com/kataras/pio v0.0.2/go.mod h1:hAoW0t9UmXi4R5Oyq5Z4irTbaTsOemSrDGUtaTl7Dro= +github.com/kataras/sitemap v0.0.5/go.mod h1:KY2eugMKiPwsJgx7+U103YZehfvNGOXURubcGyk0Bz8= github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4= github.com/klauspost/compress v1.4.0/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= +github.com/klauspost/compress v1.8.2/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= +github.com/klauspost/compress v1.9.7/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= github.com/klauspost/compress v1.12.3/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= github.com/klauspost/compress v1.16.0 h1:iULayQNOReoYUe+1qtKOqw9CwJv3aNQu8ivo7lw1HU4= github.com/klauspost/compress v1.16.0/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/cpuid v0.0.0-20170728055534-ae7887de9fa5/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= +github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk= github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= github.com/klauspost/crc32 v0.0.0-20161016154125-cb6bfca970f6/go.mod h1:+ZoRqAPRLkC4NPOvfYeR5KNOrY6TD+/sAC3HXPZgDYg= @@ -426,23 +414,23 @@ github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxv github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= 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/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/labstack/echo v3.3.10+incompatible h1:pGRcYk231ExFAyoAjAfD85kQzRJCRI8bbnE7CX5OEgg= github.com/labstack/echo v3.3.10+incompatible/go.mod h1:0INS7j/VjnFxD4E2wkz67b8cVwCLbBmJyDaka6Cmk1s= +github.com/labstack/echo/v4 v4.5.0/go.mod h1:czIriw4a0C1dFun+ObrXp7ok03xON0N1awStJ6ArI7Y= +github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k= github.com/labstack/gommon v0.4.0 h1:y7cvthEAEbU0yHOf4axH8ZG2NH8knB9iNSoTO8dyIk8= github.com/labstack/gommon v0.4.0/go.mod h1:uW6kP17uPlLJsD3ijUYn3/M5bAxtlZhMI6m3MFxTMTM= github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= -github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM= -github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4= github.com/lithammer/shortuuid/v3 v3.0.7 h1:trX0KTHy4Pbwo/6ia8fscyHoGA+mf1jWbPJVuvyJQQ8= github.com/lithammer/shortuuid/v3 v3.0.7/go.mod h1:vMk8ke37EmiewwolSO1NLW8vP4ZaKlRuDIi8tWWmAts= -github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= github.com/machinebox/graphql v0.2.2 h1:dWKpJligYKhYKO5A2gvNhkJdQMNZeChZYyBbrZkBZfo= github.com/machinebox/graphql v0.2.2/go.mod h1:F+kbVMHuwrQ5tYgU9JXlnskM8nOaFxCAEolaQybkjWA= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= @@ -453,32 +441,34 @@ github.com/magma/augmented-networks/accounting/protos v0.1.1/go.mod h1:Hpfg8aAxl github.com/matryer/is v1.4.1 h1:55ehd8zaGABKLXQUe2awZ99BD/PTc2ls+KV/dXphgEQ= github.com/matryer/is v1.4.1/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= +github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= +github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= -github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= +github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ= +github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng= github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= github.com/mattn/go-runewidth v0.0.3/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU= github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/go-sqlite3 v1.11.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= github.com/mattn/go-tty v0.0.0-20180907095812-13ff1204f104/go.mod h1:XPvLUNfbS4fJH25nqRHfWLMa1ONC8Amw+mIA639KxkE= +github.com/mattn/goveralls v0.0.2/go.mod h1:8d1ZMHsd7fW6IRPKQh46F2WRpyib5/X4FOpevwGNQEw= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= -github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= -github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= -github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/matttproud/golang_protobuf_extensions v1.0.4 h1:mmDVorXM7PCGKw94cs5zkfA9PSy5pEvNWRP0ET0TIVo= +github.com/matttproud/golang_protobuf_extensions v1.0.4/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4= +github.com/mediocregopher/radix/v3 v3.4.2/go.mod h1:8FL3F6UQRXHXIBSPUs5h0RybMF8i4n7wVopoX3x7Bv8= +github.com/microcosm-cc/bluemonday v1.0.2/go.mod h1:iVP4YcDBq+n/5fb23BhYFvIMq/leAFZyRl6bYmGDlGc= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= -github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= -github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg= -github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY= -github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= @@ -489,25 +479,20 @@ github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/moul/http2curl v1.0.0/go.mod h1:8UbvGypXm98wA/IqH45anm5Y2Z6ep6O31QGOAZ3H0fQ= github.com/mschoch/smat v0.0.0-20160514031455-90eadee771ae/go.mod h1:qAyveg+e4CE+eKJXWVjKXM4ck2QobLqTDytGJbLLhJg= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/nats-io/jwt v0.3.0/go.mod h1:fRYCDE99xlTsqUzISS1Bi75UBJ6ljOJQOAAu5VglpSg= -github.com/nats-io/jwt v0.3.2/go.mod h1:/euKqTS1ZD+zzjYrY7pseZrTtWQSjujC7xjPc8wL6eU= -github.com/nats-io/nats-server/v2 v2.1.2/go.mod h1:Afk+wRZqkMQs/p45uXdrVLuab3gwv3Z8C4HTBu8GD/k= github.com/nats-io/nats.go v1.9.1/go.mod h1:ZjDU1L/7fJ09jvUSRVBR2e7+RnLiiIQyqyzEE/Zbp4w= github.com/nats-io/nkeys v0.1.0/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w= -github.com/nats-io/nkeys v0.1.3/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w= github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= github.com/nxadm/tail v1.4.4 h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= -github.com/oklog/oklog v0.3.2/go.mod h1:FCV+B7mhrz4o+ueLpx+KqkyXRGMWOYEvfiXtdGtbWGs= -github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= -github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= -github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.10.3/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= github.com/onsi/ginkgo v1.14.0 h1:2mOpI4JVVPBN+WQRa0WKH2eXR+Ey+uK4n7Zj0aYpIQA= github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= @@ -516,84 +501,64 @@ github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1Cpa github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.10.1 h1:o0+MgICZLuZ7xjH7Vx6zS/zcu93/BEp1VwkIW1mEXCE= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= -github.com/op/go-logging v0.0.0-20160315200505-970db520ece7/go.mod h1:HzydrMdWErDVzsI23lYNej1Htcns9BCg93Dk0bBINWk= -github.com/opentracing-contrib/go-observer v0.0.0-20170622124052-a52f23424492/go.mod h1:Ngi6UdF0k5OKD5t5wlmGhe/EDKPoUM3BXZSSfIuJbis= -github.com/opentracing/basictracer-go v1.0.0/go.mod h1:QfBfYuafItcjQuMwinw9GhYKwFXS9KnPs5lxoYwgW74= github.com/opentracing/opentracing-go v1.0.2/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= github.com/opentracing/opentracing-go v1.0.3-0.20180606204148-bd9c31933947/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= -github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= -github.com/openzipkin-contrib/zipkin-go-opentracing v0.4.5/go.mod h1:/wsWhb9smxSfWAKL3wpBW7V8scJMt8N8gnaMCS9E/cA= -github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJc5AZX7/PBEpw= -github.com/openzipkin/zipkin-go v0.2.1/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4= -github.com/openzipkin/zipkin-go v0.2.2/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4= -github.com/pact-foundation/pact-go v1.0.4/go.mod h1:uExwJY4kCzNPcHRj+hCR/HBbOOIwwtUjcrb0b5/5kLM= -github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc= github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= github.com/paulbellamy/ratecounter v0.2.0/go.mod h1:Hfx1hDpSGoqxkVVpBi/IlYD7kChlfo5C6hzIHwPqfFE= -github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pelletier/go-toml/v2 v2.0.6 h1:nrzqCb7j9cDFj2coyLNLaZuJTLjWjlaz6nvTvIwycIU= github.com/pelletier/go-toml/v2 v2.0.6/go.mod h1:eumQOmlWiOPt5WriQQqoM5y18pDHwha2N+QD+EUNTek= -github.com/performancecopilot/speed v3.0.0+incompatible/go.mod h1:/CLtqpZ5gBg1M9iaPbIdPPGyKcA8hKdoy6hAWba7Yac= github.com/peterh/liner v1.0.1-0.20180619022028-8c1271fcf47f/go.mod h1:xIteQHvHuaLYG9IFj6mSxM0fCKrs34IrEQUhOYuGPHc= github.com/philhofer/fwd v1.0.0/go.mod h1:gk3iGcWd9+svBvR0sR+KPcfE+RNWozjowpeBVG3ZVNU= github.com/philhofer/fwd v1.1.1/go.mod h1:gk3iGcWd9+svBvR0sR+KPcfE+RNWozjowpeBVG3ZVNU= github.com/philhofer/fwd v1.1.2-0.20210722190033-5c56ac6d0bb9 h1:6ob53CVz+ja2i7easAStApZJlh7sxyq3Cm7g1Di6iqA= github.com/philhofer/fwd v1.1.2-0.20210722190033-5c56ac6d0bb9/go.mod h1:gk3iGcWd9+svBvR0sR+KPcfE+RNWozjowpeBVG3ZVNU= -github.com/pierrec/lz4 v1.0.2-0.20190131084431-473cd7ce01a1/go.mod h1:3/3N9NVKO0jef7pBehbT1qWhCMrIgbYNnFAZCqQ5LRc= github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= +github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= +github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/profile v1.2.1/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA= github.com/pkg/sftp v1.13.1/go.mod h1:3HaPG6Dq1ILlpPZRO0HVMrsydcdLt6HRDccSgb87qRg= github.com/pkg/term v0.0.0-20180730021639-bffc007b7fd5/go.mod h1:eCbImbZ95eXtAUIbLAuAVnBnwf83mjf6QIVH8SHYwqQ= 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/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= -github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829/go.mod h1:p2iRAGwDERtqlqzRXnrOVns+ignqQo//hLXqYxZYVNs= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= -github.com/prometheus/client_golang v1.3.0/go.mod h1:hJaj2vgQTGQmVCsAACORcieXFeDPbaTKGT+JTgUa3og= +github.com/prometheus/client_golang v1.14.0 h1:nJdhIvne2eSX/XRAFV9PcvFFRbrjbcTUj0VP62TMhnw= +github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= -github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/client_model v0.1.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= -github.com/prometheus/common v0.2.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/client_model v0.3.0 h1:UBgGFHqYdG/TPFD1B1ogZywDqEkwp3fBMvqdiQ7Xew4= +github.com/prometheus/client_model v0.3.0/go.mod h1:LDGWKZIo7rky3hgvBe+caln+Dr3dPggB5dvjtD7w9+w= github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.6.0/go.mod h1:eBmuwkDJBwy6iBfxCBob6t6dR6ENT/y+J+Zk0j9GMYc= -github.com/prometheus/common v0.7.0/go.mod h1:DjGbpBbp5NYNiECxcL/VnbXCCaQpKd3tt26CguLLsqA= +github.com/prometheus/common v0.39.0 h1:oOyhkDq05hPZKItWVBkJ6g6AtGxi+fy7F4JvUV8uhsI= +github.com/prometheus/common v0.39.0/go.mod h1:6XBZ7lYdLCbkAVhwRsWTZn+IN5AB9F/NXd5w0BbEX0Y= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= -github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= -github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= -github.com/prometheus/tsdb v0.7.1 h1:YZcsG11NqnK4czYLrWd9mpEuAJIHVQLwdrleYfszMAA= -github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= -github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= +github.com/prometheus/procfs v0.9.0 h1:wzCHvIvM5SxWqYvwgVL7yJY8Lz3PKn49KQtpgMYJfhI= +github.com/prometheus/procfs v0.9.0/go.mod h1:+pB4zwohETzFnmlpe6yd2lSc+0/46IYZRB/chUwxUZY= github.com/retailnext/hllpp v1.0.1-0.20180308014038-101a6d2f8b52/go.mod h1:RDpi1RftBQPUCDRw6SmxeaREsAaRKnOclghuzp/WRzc= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.4.3 h1:utMvzDsuh3suAEnhH0RdHmoPbU648o6CvXxTx4SBMOw= github.com/rivo/uniseg v0.4.3/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= -github.com/rjeczalik/notify v0.9.1 h1:CLCKso/QK1snAlnhNR/CNvNiFU2saUtjV0bx3EwNeCE= -github.com/rjeczalik/notify v0.9.1/go.mod h1:rKwnCoCGeuQnwBtTSPL9Dad03Vh2n40ePRrjvIXnJho= -github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= +github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/rs/cors v1.7.0 h1:+88SsELBHx5r+hZ8TCkggzSstaWNbDvThkVK8H6f9ik= github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= -github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= -github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E= -github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= +github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= +github.com/schollz/closestmatch v2.1.0+incompatible/go.mod h1:RtP1ddjLong6gTkbtmuhtR2uUrrJOpYzYRvbcPAid+g= github.com/segmentio/kafka-go v0.1.0/go.mod h1:X6itGqS9L4jDletMsxZ7Dz+JFWxM6JHfPOCvTvk+EJo= github.com/segmentio/kafka-go v0.2.0/go.mod h1:X6itGqS9L4jDletMsxZ7Dz+JFWxM6JHfPOCvTvk+EJo= github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= @@ -603,11 +568,8 @@ github.com/shopspring/decimal v1.3.1 h1:2Usl1nmF/WZucqkFZhnfFYxxxu8LG21F6nPQBE5g github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= -github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= -github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= -github.com/sony/gobreaker v0.4.1/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJOjmxWY= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI= github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= @@ -622,7 +584,6 @@ github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tL github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= -github.com/spf13/pflag v1.0.1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= @@ -631,9 +592,6 @@ github.com/spf13/viper v1.15.0 h1:js3yy885G8xwJa6iOISGFwd+qlUo5AvyXb7CiihdtiU= github.com/spf13/viper v1.15.0/go.mod h1:fFcTBJxvhhzSJiZy8n+PeW6t8l+KeT/uTARa0jHOQLA= github.com/status-im/keycard-go v0.2.0 h1:QDLFswOQu1r5jsycloeQh3bVU8n/NatHHaZobtDnDzA= github.com/status-im/keycard-go v0.2.0/go.mod h1:wlp8ZLbsmrF6g6WjugPAx+IzoLrkdf9+mHxBEeo3Hbg= -github.com/streadway/amqp v0.0.0-20190404075320-75d898a42a94/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= -github.com/streadway/amqp v0.0.0-20190827072141-edfb9018d271/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= -github.com/streadway/handy v0.0.0-20190108123426-d5acb3125c2a/go.mod h1:qNTQ5P5JnDBl6z3cMAg/SywNDC5ABu5ApDIw6lUbRmI= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= @@ -660,31 +618,42 @@ github.com/tklauser/go-sysconf v0.3.11 h1:89WgdJhk5SNwJfu+GKyYveZ4IaJ7xAkecBo+Kd github.com/tklauser/go-sysconf v0.3.11/go.mod h1:GqXfhXY3kiPa0nAXPDIQIWzJbMCB7AmcWpGR8lSZfqI= github.com/tklauser/numcpus v0.6.0 h1:kebhY2Qt+3U6RNK7UqpYNA+tJ23IBEGKkB7JQBfDYms= github.com/tklauser/numcpus v0.6.0/go.mod h1:FEZLMke0lhOUG6w2JadTzp0a+Nl8PF/GFkQ5UVIcaL4= -github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/tyler-smith/go-bip39 v1.1.0 h1:5eUemwrMargf3BSLRRCalXT93Ns6pQJIjYQN2nyfOP8= github.com/tyler-smith/go-bip39 v1.1.0/go.mod h1:gUYDtqQw1JS3ZJ8UWVcGTGqqr6YIN3CWg+kkNaLt55U= +github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= +github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= +github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= github.com/uptrace/bunrouter v1.0.20 h1:jNvYNcJxF+lSYBQAaQjnE6I11Zs0m+3M5Ek7fq/Tp4c= github.com/uptrace/bunrouter v1.0.20/go.mod h1:TwT7Bc0ztF2Z2q/ZzMuSVkcb/Ig/d3MQeP2cxn3e1hI= -github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= -github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= github.com/urfave/cli/v2 v2.17.2-0.20221006022127-8f469abc00aa h1:5SqCsI/2Qya2bCzK15ozrqo2sZxkh0FHynJZOTVoV6Q= github.com/urfave/cli/v2 v2.17.2-0.20221006022127-8f469abc00aa/go.mod h1:1CNUng3PtjQMtRzJO4FMXBQvkGtuYRxxiR9xMa7jMwI= +github.com/urfave/negroni v1.0.0/go.mod h1:Meg73S6kFm/4PpbYdq35yYWoCZ9mS/YSx+lKnmiohz4= github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= +github.com/valyala/fasthttp v1.6.0/go.mod h1:FstJa9V+Pj9vQ7OJie2qMHdwemEDaDiSdBnvPM1Su9w= +github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8= github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo= github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= +github.com/valyala/tcplisten v0.0.0-20161114210144-ceec8f93295a/go.mod h1:v3UYOV9WzVtRmSR+PDvWpU/qWl4Wa5LApYYX4ZtKbio= github.com/willf/bitset v1.1.3/go.mod h1:RjeCKbqT1RxIR/KWY6phxZiaY1IyutSBfGjNPySAYV4= -github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= +github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= +github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= github.com/xlab/treeprint v0.0.0-20180616005107-d6fb6747feb6/go.mod h1:ce1O1j6UtZfjr22oyGxGLbauSBp2YVXpARAosm7dHBg= github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU= github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8= +github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0/go.mod h1:/LWChgwKmvncFJFHJ7Gvn9wZArjbV5/FppcK2fKk/tI= +github.com/yudai/gojsondiff v1.0.0/go.mod h1:AY32+k2cwILAkW1fbgxQ5mUmMiZFgLIV+FBNExI05xg= +github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82/go.mod h1:lgjkn3NuSvDfVJdfcVVdX+jpBxNmX4rDAzaS45IcYoM= +github.com/yudai/pp v2.0.1+incompatible/go.mod h1:PuxR/8QJ7cyCkFp/aUDS+JY727OFEZkTdatxwunjIkc= github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yusufpapurcu/wmi v1.2.2 h1:KBNDSne4vP5mbSWnJbO+51IMOXJB67QiYCSBrubbPRg= github.com/yusufpapurcu/wmi v1.2.2/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= @@ -697,10 +666,6 @@ go.dedis.ch/kyber/v3 v3.1.0/go.mod h1:kXy7p3STAurkADD+/aZcsznZGKVHEqbtmdIzvPfrs1 go.dedis.ch/protobuf v1.0.5/go.mod h1:eIV4wicvi6JK0q/QnfIEGeSFNG0ZeB24kzut5+HaRLo= go.dedis.ch/protobuf v1.0.7/go.mod h1:pv5ysfkDX/EawiPqcW3ikOxsL5t+BqnV6xHSmE79KI4= go.dedis.ch/protobuf v1.0.11/go.mod h1:97QR256dnkimeNdfmURz0wAMNVbd1VmLXhG1CrTYrJ4= -go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= -go.etcd.io/etcd v0.0.0-20191023171146-3cf2f69b5738/go.mod h1:dnLIgRNXwCJa5e+c6mIZCrds/GIG4ncV9HhK5PX7jPg= -go.opencensus.io v0.20.1/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk= -go.opencensus.io v0.20.2/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= @@ -710,27 +675,21 @@ go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= -go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ= go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A= go.uber.org/goleak v1.1.11 h1:wy28qYRKZgnJTxGxvye5/wgWr1EKjmUDGYox5mGlRlI= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= -go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI= go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ= -go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= go.uber.org/zap v1.9.1/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= -go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= -go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM= go.uber.org/zap v1.19.0/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI= go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60= go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg= golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190123085648-057139ce5d2b/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= @@ -738,7 +697,9 @@ golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191227163750-53104e6ec876/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= @@ -757,6 +718,8 @@ golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u0 golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= +golang.org/x/exp v0.0.0-20230206171751-46f607a40771 h1:xP7rWLUr1e1n2xkK5YB4LI0hPEy3LJC6Wk+D4pGlOJg= +golang.org/x/exp v0.0.0-20230206171751-46f607a40771/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc= golang.org/x/image v0.0.0-20180708004352-c73c2afc3b81/go.mod h1:ux5Hcp/YLpHSI86hEcLt0YII63i6oz57MZXIpbrjZUs= golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= @@ -773,6 +736,7 @@ golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRu golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= @@ -783,19 +747,18 @@ golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190125091013-d26f9f9a57f3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190327091125-710a502c58a2/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= @@ -804,7 +767,7 @@ golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLL golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -827,9 +790,11 @@ golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwY golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= +golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.7.0 h1:rJrUqqhjsgNp7KqAIc25s9pZnjU7TUcSY7HcVZjdn1g= -golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= +golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -853,36 +818,33 @@ golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190124100055-b90733256f2e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190826190057-c7b8b68b1456/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191220142924-d4481acd189f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200107162124-548cf772de50/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -905,11 +867,17 @@ golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210225134936-a50acf3fe073/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210324051608-47abb6519492/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211103235746-7861aae1554b/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -917,8 +885,8 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20221010170243-090e33056c14/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU= -golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -927,26 +895,29 @@ golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3 golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.7.0 h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68= +golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180525024113-a5b4c53f6e8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20181221001348-537d06c36207/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190206041539-40960b6deb8e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190327201419-c70d86f8b7cf/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= @@ -957,8 +928,6 @@ golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgw golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= @@ -967,7 +936,6 @@ golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200103221440-774c71fcf114/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200108203644-89082a384178/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= @@ -997,6 +965,7 @@ golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4f golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210108195828-e2f9c7f1fc8e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= +golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -1009,7 +978,6 @@ gonum.org/v1/gonum v0.6.0/go.mod h1:9mxDZsDKxgMAuccQkewq682L+0eCu4dCN2yonUJTCLU= gonum.org/v1/netlib v0.0.0-20181029234149-ec6d1f5cefe6/go.mod h1:wa6Ws7BG/ESfp6dHfk7C6KdzKA7wR7u/rKwOGE66zvw= gonum.org/v1/netlib v0.0.0-20190313105609-8cb42192e0e0/go.mod h1:wa6Ws7BG/ESfp6dHfk7C6KdzKA7wR7u/rKwOGE66zvw= gonum.org/v1/plot v0.0.0-20190515093506-e2840ee46a6b/go.mod h1:Wt8AAjI+ypCyYX3nZBvf6cAIx93T+c/OS2HFAYskSZc= -google.golang.org/api v0.3.1/go.mod h1:6wY9I6uQWHQ8EM57III9mq/AjF+i8G65rmVagqKMtkk= google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= @@ -1030,19 +998,18 @@ google.golang.org/api v0.35.0/go.mod h1:/XrVsuzM0rZmrsbjJutiuftIzeuTQcEeaYcSk/mQ google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34qYtE= google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= -google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/genproto v0.0.0-20180518175338-11a468237815/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190530194941-fb225487d101/go.mod h1:z3L6/3dTEVtUr6QSP8miRzeRqwQOioJ9I66odjN4I7s= google.golang.org/genproto v0.0.0-20190716160619-c506a9f90610/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= @@ -1076,17 +1043,14 @@ google.golang.org/genproto v0.0.0-20201210142538-e3217bee35cc/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210108203827-ffc7fda8c3d7/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210226172003-ab064af71705/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24= google.golang.org/genproto v0.0.0-20230216225411-c8e22ba71e44 h1:EfLuoKW5WfkgVdDy7dTK8qSbH37AX5mj/MFh+bGPz14= google.golang.org/genproto v0.0.0-20230216225411-c8e22ba71e44/go.mod h1:8B0gmkoRebU8ukX6HP+4wrVQUY1+6PkQ44BSyIlflHA= -google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= +google.golang.org/grpc v1.12.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= -google.golang.org/grpc v1.20.0/go.mod h1:chYK+tFQF0nDUGJgXMSgLCQk3phJEuONr2DCgLDdAQM= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= -google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= -google.golang.org/grpc v1.22.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= -google.golang.org/grpc v1.23.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= @@ -1099,6 +1063,7 @@ google.golang.org/grpc v1.31.1/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA51WJ8= google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= +google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= google.golang.org/grpc v1.53.0 h1:LAv2ds7cmFV/XTS3XG1NneeENYrXGmorPxsBbptIjNc= google.golang.org/grpc v1.53.0/go.mod h1:OnIrk0ipVdj4N5d9IUoFUx72/VlD7+jUsHwZgwSMQpw= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= @@ -1120,24 +1085,22 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8 gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= -gopkg.in/cheggaaa/pb.v1 v1.0.25/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= gopkg.in/cheggaaa/pb.v1 v1.0.28 h1:n1tBJnnK2r7g9OW2btFH91V92STTUevLXYFb8gy9EMk= gopkg.in/cheggaaa/pb.v1 v1.0.28/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= -gopkg.in/gcfg.v1 v1.2.3/go.mod h1:yesOnuUOFQAhST5vPY4nbZsb/huCgGGXlipJsBn0b3o= +gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8bDuhia5mkpMnE= +gopkg.in/go-playground/validator.v8 v8.18.2/go.mod h1:RX2a/7Ha8BgOhfk7j780h4/u/RRjR0eouCJSH80/M2Y= +gopkg.in/ini.v1 v1.51.1/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce h1:+JknDZhAj8YMt7GC73Ei8pv4MzjDUNPHgQWJdtMAaDU= gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce/go.mod h1:5AcXVHNjg+BDxry382+8OKon8SEWiKktQR07RKPsv1c= -gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= -gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI= -gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= @@ -1145,11 +1108,11 @@ gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20191120175047-4206685974f2/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/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= -honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= @@ -1161,5 +1124,3 @@ rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8 rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= -sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= -sourcegraph.com/sourcegraph/appdash v0.0.0-20190731080439-ebfcffb1b5c0/go.mod h1:hI742Nqp5OhwiqlzhgfbWU4mW4yO10fP+LoT9WOswdU= diff --git a/wasmsdk/bridge.go b/wasmsdk/bridge.go index 80b236f4c..2c5599547 100644 --- a/wasmsdk/bridge.go +++ b/wasmsdk/bridge.go @@ -10,6 +10,7 @@ import ( "github.com/0chain/gosdk/zcnbridge/errors" "github.com/0chain/gosdk/zcnbridge/wallet" "github.com/0chain/gosdk/zcncore" + "github.com/ethereum/go-ethereum/ethclient" ) var bridge *zcnbridge.BridgeClient @@ -28,16 +29,21 @@ func initBridge( return errors.New("wallet_error", "wallet is not set") } + ethereumClient, err := ethclient.Dial(ethereumNodeURL) + if err != nil { + return errors.New("wallet_error", err.Error()) + } + bridge = &zcnbridge.BridgeClient{ EthereumAddress: ethereumAddress, BridgeAddress: bridgeAddress, AuthorizersAddress: authorizersAddress, TokenAddress: tokenAddress, Password: "", - EthereumNodeURL: ethereumNodeURL, Homedir: ".", GasLimit: gasLimit, ConsensusThreshold: consensusThreshold, + EthereumClient: ethereumClient, } return nil diff --git a/zcnbridge/bridge.go b/zcnbridge/bridge.go index d46000e6a..4628af26d 100644 --- a/zcnbridge/bridge.go +++ b/zcnbridge/bridge.go @@ -16,8 +16,6 @@ import ( "github.com/0chain/gosdk/zcnbridge/ethereum/erc20" "github.com/0chain/gosdk/zcnbridge/log" "github.com/0chain/gosdk/zcncore" - hdw "github.com/0chain/gosdk/zcncore/ethhdwallet" - "github.com/spf13/viper" "github.com/0chain/gosdk/zcnbridge/transaction" "github.com/0chain/gosdk/zcnbridge/wallet" @@ -61,12 +59,55 @@ var ( } ) -func (b *BridgeClient) prepareAuthorizers(ctx context.Context, method string, params ...interface{}) (*authorizers.Authorizers, *bind.TransactOpts, error) { - etherClient, err := b.CreateEthClient() +func (b *BridgeClient) CreateSignedTransactionFromKeyStore(client EthereumClient, gasLimitUnits uint64) *bind.TransactOpts { + var ( + signerAddress = common.HexToAddress(b.EthereumAddress) + password = b.Password + ) + + keyDir := path.Join(b.Homedir, EthereumWalletStorageDir) + ks := keystore.NewKeyStore(keyDir, keystore.StandardScryptN, keystore.StandardScryptP) + signer := accounts.Account{ + Address: signerAddress, + } + signerAcc, err := ks.Find(signer) if err != nil { - return nil, nil, errors.Wrap(err, "failed to create etherClient") + Logger.Fatal(errors.Wrapf(err, "signer: %s", signerAddress.Hex())) } + chainID, err := client.ChainID(context.Background()) + if err != nil { + Logger.Fatal(errors.Wrap(err, "failed to get chain ID")) + } + + nonce, err := client.PendingNonceAt(context.Background(), signerAddress) + if err != nil { + Logger.Fatal(err) + } + + gasPriceWei, err := client.SuggestGasPrice(context.Background()) + if err != nil { + Logger.Fatal(err) + } + + err = ks.TimedUnlock(signer, password, time.Second*2) + if err != nil { + Logger.Fatal(err) + } + + opts, err := bind.NewKeyStoreTransactorWithChainID(ks, signerAcc, chainID) + if err != nil { + Logger.Fatal(err) + } + + opts.Nonce = big.NewInt(int64(nonce)) + opts.GasLimit = gasLimitUnits // in units + opts.GasPrice = gasPriceWei // wei + + return opts +} + +func (b *BridgeClient) prepareAuthorizers(ctx context.Context, method string, params ...interface{}) (*authorizers.Authorizers, *bind.TransactOpts, error) { // To (contract) contractAddress := common.HexToAddress(b.AuthorizersAddress) @@ -85,7 +126,7 @@ func (b *BridgeClient) prepareAuthorizers(ctx context.Context, method string, pa from := common.HexToAddress(b.EthereumAddress) // Gas limits in units - gasLimitUnits, err := etherClient.EstimateGas(ctx, eth.CallMsg{ + gasLimitUnits, err := b.EthereumClient.EstimateGas(ctx, eth.CallMsg{ To: &contractAddress, From: from, Data: pack, @@ -97,10 +138,10 @@ func (b *BridgeClient) prepareAuthorizers(ctx context.Context, method string, pa // Update gas limits + 10% gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() - transactOpts := b.CreateSignedTransactionFromKeyStore(etherClient, gasLimitUnits) + transactOpts := b.CreateSignedTransactionFromKeyStore(b.EthereumClient, gasLimitUnits) // Authorizers instance - authorizersInstance, err := authorizers.NewAuthorizers(contractAddress, etherClient) + authorizersInstance, err := authorizers.NewAuthorizers(contractAddress, b.EthereumClient) if err != nil { return nil, nil, errors.Wrap(err, "failed to create authorizers instance") } @@ -140,50 +181,6 @@ func (b *BridgeClient) RemoveEthereumAuthorizer(ctx context.Context, address com return tran, err } -func (b *BridgeClient) AddEthereumAuthorizers(configDir string) { - cfg := viper.New() - cfg.AddConfigPath(configDir) - cfg.SetConfigName("authorizers") - if err := cfg.ReadInConfig(); err != nil { - fmt.Println(err) - return - } - - mnemonics := cfg.GetStringSlice("authorizers") - - for _, mnemonic := range mnemonics { - wallet, err := hdw.NewFromMnemonic(mnemonic) - if err != nil { - fmt.Printf("failed to read mnemonic: %v", err) - continue - } - - pathD := hdw.MustParseDerivationPath("m/44'/60'/0'/0/0") - account, err := wallet.Derive(pathD, true) - if err != nil { - fmt.Println(err) - continue - } - - transaction, err := b.AddEthereumAuthorizer(context.TODO(), account.Address) - if err != nil || transaction == nil { - fmt.Printf("AddAuthorizer error: %v, Address: %s", err, account.Address.Hex()) - continue - } - - status, err := ConfirmEthereumTransaction(transaction.Hash().String(), 100, time.Second*10) - if err != nil { - fmt.Println(err) - } - - if status == 1 { - fmt.Printf("Authorizer has been added: %s\n", mnemonic) - } else { - fmt.Printf("Authorizer has failed to be added: %s\n", mnemonic) - } - } -} - // IncreaseBurnerAllowance Increases allowance for bridge contract address to transfer // WZCN tokens on behalf of the token owner to the Burn TokenPool // During the burn the script transfers amount from token owner to the bridge burn token pool @@ -199,11 +196,6 @@ func (b *BridgeClient) IncreaseBurnerAllowance(ctx context.Context, amountWei We return nil, errors.New("amount must be greater than zero") } - etherClient, err := b.CreateEthClient() - if err != nil { - return nil, errors.Wrap(err, "failed to create etherClient") - } - // 1. Data Parameter (spender) spenderAddress := common.HexToAddress(b.BridgeAddress) @@ -223,7 +215,7 @@ func (b *BridgeClient) IncreaseBurnerAllowance(ctx context.Context, amountWei We return nil, errors.Wrap(err, "failed to pack arguments") } - gasLimitUnits, err := etherClient.EstimateGas(ctx, eth.CallMsg{ + gasLimitUnits, err := b.EthereumClient.EstimateGas(ctx, eth.CallMsg{ To: &tokenAddress, From: fromAddress, Data: pack, @@ -234,9 +226,9 @@ func (b *BridgeClient) IncreaseBurnerAllowance(ctx context.Context, amountWei We gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() - transactOpts := b.CreateSignedTransactionFromKeyStore(etherClient, gasLimitUnits) + transactOpts := b.CreateSignedTransactionFromKeyStore(b.EthereumClient, gasLimitUnits) - wzcnTokenInstance, err := erc20.NewERC20(tokenAddress, etherClient) + wzcnTokenInstance, err := erc20.NewERC20(tokenAddress, b.EthereumClient) if err != nil { return nil, errors.Wrap(err, "failed to initialize WZCN-ERC20 instance") } @@ -273,15 +265,10 @@ func (b *BridgeClient) IncreaseBurnerAllowance(ctx context.Context, amountWei We // GetBalance returns balance of the current client func (b *BridgeClient) GetBalance() (*big.Int, error) { - etherClient, err := b.CreateEthClient() - if err != nil { - return nil, errors.Wrap(err, "failed to create etherClient") - } - tokenAddress := common.HexToAddress(b.TokenAddress) fromAddress := common.HexToAddress(b.EthereumAddress) - wzcnTokenInstance, err := erc20.NewERC20(tokenAddress, etherClient) + wzcnTokenInstance, err := erc20.NewERC20(tokenAddress, b.EthereumClient) if err != nil { return nil, errors.Wrap(err, "failed to initialize WZCN-ERC20 instance") } @@ -328,15 +315,11 @@ func (b *BridgeClient) SignWithEthereumChain(message string) ([]byte, error) { // GetUserNonceMinted Returns nonce for a specified Ethereum address func (b *BridgeClient) GetUserNonceMinted(ctx context.Context, rawEthereumAddress string) (*big.Int, error) { ethereumAddress := common.HexToAddress(rawEthereumAddress) - etherClient, err := b.CreateEthClient() - if err != nil { - return nil, errors.Wrap(err, "failed to create etherClient") - } contractAddress := common.HexToAddress(b.BridgeAddress) var bridgeInstance *binding.Bridge - bridgeInstance, err = binding.NewBridge(contractAddress, etherClient) + bridgeInstance, err := binding.NewBridge(contractAddress, b.EthereumClient) if err != nil { return nil, errors.Wrap(err, "failed to create bridge instance") } @@ -531,11 +514,6 @@ func (b *BridgeClient) BurnZCN(ctx context.Context, amount, txnfee uint64) (*tra } func (b *BridgeClient) prepareBridge(ctx context.Context, ethereumAddress, method string, params ...interface{}) (*binding.Bridge, *bind.TransactOpts, error) { - etherClient, err := b.CreateEthClient() - if err != nil { - return nil, nil, errors.Wrap(err, "failed to create etherClient") - } - // To (contract) contractAddress := common.HexToAddress(b.BridgeAddress) @@ -554,7 +532,7 @@ func (b *BridgeClient) prepareBridge(ctx context.Context, ethereumAddress, metho //Gas limits in units fromAddress := common.HexToAddress(ethereumAddress) - gasLimitUnits, err := etherClient.EstimateGas(ctx, eth.CallMsg{ + gasLimitUnits, err := b.EthereumClient.EstimateGas(ctx, eth.CallMsg{ To: &contractAddress, From: fromAddress, Data: pack, @@ -566,10 +544,10 @@ func (b *BridgeClient) prepareBridge(ctx context.Context, ethereumAddress, metho //Update gas limits + 10% gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() - transactOpts := b.CreateSignedTransactionFromKeyStore(etherClient, gasLimitUnits) + transactOpts := b.CreateSignedTransactionFromKeyStore(b.EthereumClient, gasLimitUnits) // BridgeClient instance - bridgeInstance, err := binding.NewBridge(contractAddress, etherClient) + bridgeInstance, err := binding.NewBridge(contractAddress, b.EthereumClient) if err != nil { return nil, nil, errors.Wrap(err, "failed to create bridge instance") } diff --git a/zcnbridge/bridge_test.go b/zcnbridge/bridge_test.go index 7f9120aa3..9d1e6c1b1 100644 --- a/zcnbridge/bridge_test.go +++ b/zcnbridge/bridge_test.go @@ -1,35 +1,77 @@ package zcnbridge import ( + "context" "encoding/json" + "log" + "math/big" + "os" "strconv" "testing" - "github.com/0chain/gosdk/core/common" + sdkcommon "github.com/0chain/gosdk/core/common" + "github.com/0chain/gosdk/zcnbridge/ethereum" + "github.com/0chain/gosdk/zcnbridge/mocks" + "github.com/ethereum/go-ethereum/common" + "github.com/spf13/viper" + "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" ) -type AuthorizerConfigTarget struct { - Fee common.Balance `json:"fee"` +const ( + ETHEREUM_MNEMONIC = "symbol alley celery diesel donate moral almost opinion achieve since diamond page" + + ETHEREUM_ADDRESS = "0xD8c9156e782C68EE671C09b6b92de76C97948432" + PASSWORD = "\"02289b9\"" + + BRIDGE_ADDRESS = "0x7bbbEa24ac1751317D7669f05558632c4A9113D7" + TOKEN_ADDRESS = "0x2ec8F26ccC678c9faF0Df20208aEE3AF776160CD" + AUTHORIZER_ADDRESS = "0xEAe8229c0E457efBA1A1769e7F8c20110fF68E61" + + ZCNTxnID = "b26abeb31fcee5d2e75b26717722938a06fa5ce4a5b5e68ddad68357432caace" + Amount = 1e10 + To = "0x2ec8F26ccC678c9faF0Df20208aEE3AF776160CD" + Nonce = 1 +) + +var ( + Signatures = []*ethereum.AuthorizerSignature{ + { + ID: "0x2ec8F26ccC678c9faF0Df20208aEE3AF776160CD", + Signature: []byte("0xEAe8229c0E457efBA1A1769e7F8c20110fF68E61"), + }, + } +) + +type ethereumClientMock struct { + mock.TestingT +} + +func (ecm *ethereumClientMock) Cleanup(callback func()) { + callback() } -type AuthorizerNodeTarget struct { +type authorizerConfigTarget struct { + Fee sdkcommon.Balance `json:"fee"` +} + +type authorizerNodeTarget struct { ID string `json:"id"` PublicKey string `json:"public_key"` URL string `json:"url"` - Config *AuthorizerConfigTarget `json:"config"` + Config *authorizerConfigTarget `json:"config"` } -type AuthorizerConfigSource struct { +type authorizerConfigSource struct { Fee string `json:"fee"` } -type AuthorizerNodeSource struct { +type authorizerNodeSource struct { ID string `json:"id"` - Config *AuthorizerConfigSource `json:"config"` + Config *authorizerConfigSource `json:"config"` } -func (an *AuthorizerNodeTarget) Decode(input []byte) error { +func (an *authorizerNodeTarget) decode(input []byte) error { var objMap map[string]*json.RawMessage err := json.Unmarshal(input, &objMap) if err != nil { @@ -68,8 +110,8 @@ func (an *AuthorizerNodeTarget) Decode(input []byte) error { rawCfg, ok := objMap["config"] if ok { - var cfg = &AuthorizerConfigTarget{} - err = cfg.Decode(*rawCfg) + var cfg = &authorizerConfigTarget{} + err = cfg.decode(*rawCfg) if err != nil { return err } @@ -80,7 +122,7 @@ func (an *AuthorizerNodeTarget) Decode(input []byte) error { return nil } -func (c *AuthorizerConfigTarget) Decode(input []byte) (err error) { +func (c *authorizerConfigTarget) decode(input []byte) (err error) { const ( Fee = "fee" ) @@ -104,29 +146,118 @@ func (c *AuthorizerConfigTarget) Decode(input []byte) (err error) { return err } - c.Fee = common.Balance(balance) + c.Fee = sdkcommon.Balance(balance) } return nil } -func Test_UpdateAuthorizerConfigTest(t *testing.T) { - source := &AuthorizerNodeSource{ - ID: "12345678", - Config: &AuthorizerConfigSource{ - Fee: "999", - }, +func getEthereumClient(t mock.TestingT) *mocks.EthereumClient { + return mocks.NewEthereumClient(ðereumClientMock{t}) +} + +func getBridgeClient(ethereumClient EthereumClient) *BridgeClient { + cfg := viper.New() + + tempConfigFile, err := os.CreateTemp(".", "config.yaml") + if err != nil { + log.Fatalln(err) } - target := &AuthorizerNodeTarget{} - bytes, err := json.Marshal(source) - require.NoError(t, err) + defer os.Remove(tempConfigFile.Name()) + + cfg.SetConfigFile(tempConfigFile.Name()) + + cfg.SetDefault("bridge.bridge_address", BRIDGE_ADDRESS) + cfg.SetDefault("bridge.token_address", TOKEN_ADDRESS) + cfg.SetDefault("bridge.authorizers_address", AUTHORIZER_ADDRESS) + cfg.SetDefault("bridge.ethereum_address", ETHEREUM_ADDRESS) + cfg.SetDefault("bridge.password", PASSWORD) + cfg.SetDefault("bridge.gas_limit", 0) + cfg.SetDefault("bridge.consensus_threshold", 0) + + return CreateBridgeClient(cfg, ethereumClient) +} + +func prepareGeneralMockCalls(m *mock.Mock) { + m.On("EstimateGas", mock.Anything, mock.Anything).Return(uint64(400000), nil) + m.On("ChainID", mock.Anything).Return(big.NewInt(400000), nil) + m.On("PendingNonceAt", mock.Anything, mock.Anything).Return(uint64(Nonce), nil) + m.On("SuggestGasPrice", mock.Anything).Return(big.NewInt(400000), nil) + m.On("SendTransaction", mock.Anything, mock.Anything).Return(nil) +} + +func Test_ZCNBridge(t *testing.T) { + ethereumClient := getEthereumClient(t) + + prepareGeneralMockCalls(ðereumClient.Mock) + + bridgeClient := getBridgeClient(ethereumClient) + + t.Run("should update authorizer config.", func(t *testing.T) { + source := &authorizerNodeSource{ + ID: "12345678", + Config: &authorizerConfigSource{ + Fee: "999", + }, + } + target := &authorizerNodeTarget{} + + bytes, err := json.Marshal(source) + require.NoError(t, err) + + err = target.decode(bytes) + require.NoError(t, err) + + require.Equal(t, "", target.URL) + require.Equal(t, "", target.PublicKey) + require.Equal(t, "12345678", target.ID) + require.Equal(t, sdkcommon.Balance(999), target.Config.Fee) + }) + + t.Run("should check signature and other data formating in MintWZCN", func(t *testing.T) { + ctx := context.Background() + + _, err := bridgeClient.MintWZCN(ctx, ðereum.MintPayload{ + ZCNTxnID: ZCNTxnID, + Amount: Amount, + To: To, + Nonce: Nonce, + Signatures: Signatures, + }) + require.NoError(t, err) + + var sigs [][]byte + for _, signature := range Signatures { + sigs = append(sigs, signature.Signature) + } + + ethereumClient.AssertCalled( + t, + "prepareBridge", + ctx, + To, + "mint", + common.HexToAddress(To), + big.NewInt(Amount), + DefaultClientIDEncoder(ZCNTxnID), + big.NewInt(Nonce), + sigs) + }) + + t.Run("should check data formating in BurnWZCN", func(t *testing.T) { + + }) + + t.Run("should check data used by BurnZCN", func(t *testing.T) { + + }) + + t.Run("should check data used by IncreaseBurnerAllowance", func(t *testing.T) { + + }) - err = target.Decode(bytes) - require.NoError(t, err) + t.Run("should check data used by CreateSignedTransactionFromKeyStore", func(t *testing.T) { - require.Equal(t, "", target.URL) - require.Equal(t, "", target.PublicKey) - require.Equal(t, "12345678", target.ID) - require.Equal(t, common.Balance(999), target.Config.Fee) + }) } diff --git a/zcnbridge/config.go b/zcnbridge/config.go index 7d5e06e72..020882484 100644 --- a/zcnbridge/config.go +++ b/zcnbridge/config.go @@ -1,10 +1,14 @@ package zcnbridge import ( + "context" "fmt" + "math/big" "path" "github.com/0chain/gosdk/zcnbridge/log" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/viper" ) @@ -24,20 +28,29 @@ type BridgeSDKConfig struct { } type BridgeClient struct { + EthereumClient + BridgeAddress, TokenAddress, AuthorizersAddress, EthereumAddress, Password, - EthereumNodeURL, Homedir string ConsensusThreshold float64 GasLimit uint64 } -func CreateBridgeClient(cfg *viper.Viper) *BridgeClient { +// EthereumClient describes Ethereum JSON-RPC client generealized interface +type EthereumClient interface { + bind.ContractBackend + + ChainID(ctx context.Context) (*big.Int, error) +} +// CreateBridgeClient initializes new bridge client with the help of the given +// Ethereum JSON-RPC client and locally-defined confiruration. +func CreateBridgeClient(cfg *viper.Viper, ethereumClient EthereumClient) *BridgeClient { homedir := path.Dir(cfg.ConfigFileUsed()) if homedir == "" { log.Logger.Fatal("homedir is required") @@ -49,10 +62,10 @@ func CreateBridgeClient(cfg *viper.Viper) *BridgeClient { AuthorizersAddress: cfg.GetString("bridge.authorizers_address"), EthereumAddress: cfg.GetString("bridge.ethereum_address"), Password: cfg.GetString("bridge.password"), - EthereumNodeURL: cfg.GetString("ethereum_node_url"), GasLimit: cfg.GetUint64("bridge.gas_limit"), ConsensusThreshold: cfg.GetFloat64("bridge.consensus_threshold"), Homedir: homedir, + EthereumClient: ethereumClient, } } @@ -60,7 +73,15 @@ func CreateBridgeClient(cfg *viper.Viper) *BridgeClient { // 0Chain SDK initialization is required func SetupBridgeClientSDK(cfg *BridgeSDKConfig) *BridgeClient { log.InitLogging(*cfg.Development, *cfg.LogPath, *cfg.LogLevel) - bridgeClient := CreateBridgeClient(initChainConfig(cfg)) + + chainCfg := initChainConfig(cfg) + + ethereumClient, err := ethclient.Dial(chainCfg.GetString("ethereum_node_url")) + if err != nil { + Logger.Error(err) + } + + bridgeClient := CreateBridgeClient(chainCfg, ethereumClient) return bridgeClient } diff --git a/zcnbridge/ethereum_wallet.go b/zcnbridge/ethereum_wallet.go deleted file mode 100644 index 59e166f66..000000000 --- a/zcnbridge/ethereum_wallet.go +++ /dev/null @@ -1,110 +0,0 @@ -package zcnbridge - -import ( - "context" - "crypto/ecdsa" - "math/big" - "path" - "time" - - "github.com/ethereum/go-ethereum/accounts" - - "github.com/ethereum/go-ethereum/accounts/keystore" - - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/ethclient" - "github.com/ethereum/go-ethereum/params" - "github.com/pkg/errors" - - "github.com/ethereum/go-ethereum/common" -) - -func (b *BridgeClient) CreateEthClient() (*ethclient.Client, error) { - client, err := ethclient.Dial(b.EthereumNodeURL) - if err != nil { - Logger.Error(err) - } - return client, err -} - -// _allowances[owner][spender] = amount; -// as a spender, ERC20 WZCN token must increase allowance for the bridge to make burn on behalf of WZCN owner -func CreateSignedTransaction( - chainID *big.Int, - client *ethclient.Client, - fromAddress common.Address, - privateKey *ecdsa.PrivateKey, - gasLimitUnits uint64, -) *bind.TransactOpts { - nonce, err := client.PendingNonceAt(context.Background(), fromAddress) - if err != nil { - Logger.Fatal(err) - } - - gasPriceWei, err := client.SuggestGasPrice(context.Background()) - if err != nil { - Logger.Fatal(err) - } - - opts, err := bind.NewKeyedTransactorWithChainID(privateKey, chainID) - if err != nil { - Logger.Fatal(err) - } - - valueWei := new(big.Int).Mul(big.NewInt(0), big.NewInt(params.Wei)) - - opts.Nonce = big.NewInt(int64(nonce)) - opts.Value = valueWei // in wei - opts.GasLimit = gasLimitUnits // in units - opts.GasPrice = gasPriceWei // wei - - return opts -} - -func (b *BridgeClient) CreateSignedTransactionFromKeyStore(client *ethclient.Client, gasLimitUnits uint64) *bind.TransactOpts { - var ( - signerAddress = common.HexToAddress(b.EthereumAddress) - password = b.Password - ) - - keyDir := path.Join(b.Homedir, EthereumWalletStorageDir) - ks := keystore.NewKeyStore(keyDir, keystore.StandardScryptN, keystore.StandardScryptP) - signer := accounts.Account{ - Address: signerAddress, - } - signerAcc, err := ks.Find(signer) - if err != nil { - Logger.Fatal(errors.Wrapf(err, "signer: %s", signerAddress.Hex())) - } - - chainID, err := client.ChainID(context.Background()) - if err != nil { - Logger.Fatal(errors.Wrap(err, "failed to get chain ID")) - } - - nonce, err := client.PendingNonceAt(context.Background(), signerAddress) - if err != nil { - Logger.Fatal(err) - } - - gasPriceWei, err := client.SuggestGasPrice(context.Background()) - if err != nil { - Logger.Fatal(err) - } - - err = ks.TimedUnlock(signer, password, time.Second*2) - if err != nil { - Logger.Fatal(err) - } - - opts, err := bind.NewKeyStoreTransactorWithChainID(ks, signerAcc, chainID) - if err != nil { - Logger.Fatal(err) - } - - opts.Nonce = big.NewInt(int64(nonce)) - opts.GasLimit = gasLimitUnits // in units - opts.GasPrice = gasPriceWei // wei - - return opts -} diff --git a/zcnswap/utils/ethutils.go b/zcnswap/utils/ethutils.go index 1aa83fd47..7157d844d 100755 --- a/zcnswap/utils/ethutils.go +++ b/zcnswap/utils/ethutils.go @@ -8,11 +8,11 @@ import ( "github.com/0chain/errors" l "github.com/0chain/gosdk/zboxcore/logger" - "github.com/0chain/gosdk/zcnbridge" hdwallet "github.com/0chain/gosdk/zcncore/ethhdwallet" eth "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" cmn "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" "github.com/ethereum/go-ethereum/params" @@ -25,6 +25,39 @@ const ( STATUS_SUCCESS = 0 ) +// createSignedTransaction creates basic Ethereum transaction. +func createSignedTransaction( + chainID *big.Int, + client *ethclient.Client, + fromAddress common.Address, + privateKey *ecdsa.PrivateKey, + gasLimitUnits uint64, +) (*bind.TransactOpts, error) { + nonce, err := client.PendingNonceAt(context.Background(), fromAddress) + if err != nil { + return nil, err + } + + gasPriceWei, err := client.SuggestGasPrice(context.Background()) + if err != nil { + return nil, err + } + + opts, err := bind.NewKeyedTransactorWithChainID(privateKey, chainID) + if err != nil { + return nil, err + } + + valueWei := new(big.Int).Mul(big.NewInt(0), big.NewInt(params.Wei)) + + opts.Nonce = big.NewInt(int64(nonce)) + opts.Value = valueWei // in wei + opts.GasLimit = gasLimitUnits // in units + opts.GasPrice = gasPriceWei // wei + + return opts, nil +} + func ConfirmEthereumTransaction(hash string, times int, duration time.Duration, client *ethclient.Client) (int, error) { var ( res = 0 @@ -84,7 +117,11 @@ func NewSignedTransaction(pack []byte, from, to string, value *big.Int, privateK return nil, err } - opts := zcnbridge.CreateSignedTransaction(chainID, client, fromAddress, privateKey, gasLimitUnits) + opts, err := createSignedTransaction(chainID, client, fromAddress, privateKey, gasLimitUnits) + if err != nil { + return nil, err + } + valueWei := new(big.Int).Mul(value, big.NewInt(params.Wei)) opts.Nonce = big.NewInt(int64(nonce)) From d675c7a9ec6f2ef60f1c9ab46ffda4b0ac6d5bb9 Mon Sep 17 00:00:00 2001 From: YarikRevich Date: Fri, 25 Aug 2023 00:53:16 +0200 Subject: [PATCH 002/134] fix: fixed existing test cases --- generate_mocks.sh | 3 + zcnbridge/bridge.go | 23 ++++-- zcnbridge/bridge_test.go | 119 ++++++++++++++++++++++++----- zcnbridge/transaction/functions.go | 24 ++++-- zcnbridge/transaction/txn.go | 72 +++++++++++++---- 5 files changed, 195 insertions(+), 46 deletions(-) diff --git a/generate_mocks.sh b/generate_mocks.sh index 54afade72..47bc8e63f 100755 --- a/generate_mocks.sh +++ b/generate_mocks.sh @@ -13,4 +13,7 @@ mockery --output=./mocks --all cd $BASEDIR/zcnbridge || exit mockery --output=./mocks --all +cd $BASEDIR/zcnbridge/transaction || exit +mockery --output=./mocks --all + echo "Mocks files are generated." \ No newline at end of file diff --git a/zcnbridge/bridge.go b/zcnbridge/bridge.go index 4628af26d..73895c186 100644 --- a/zcnbridge/bridge.go +++ b/zcnbridge/bridge.go @@ -59,14 +59,23 @@ var ( } ) +// createTransactionEntity HOC for 0chain transaction entity creation. +func (b *BridgeClient) createTransactionEntity(txnfee uint64) (transaction.Transaction, error) { + return transaction.NewTransactionEntity(txnfee) +} + +// getKeyStore reutrns key storage located in the given path. +func (b *BridgeClient) getKeyStore(path string) *keystore.KeyStore { + return keystore.NewKeyStore(path, keystore.StandardScryptN, keystore.StandardScryptP) +} + func (b *BridgeClient) CreateSignedTransactionFromKeyStore(client EthereumClient, gasLimitUnits uint64) *bind.TransactOpts { var ( signerAddress = common.HexToAddress(b.EthereumAddress) password = b.Password ) - keyDir := path.Join(b.Homedir, EthereumWalletStorageDir) - ks := keystore.NewKeyStore(keyDir, keystore.StandardScryptN, keystore.StandardScryptP) + ks := b.getKeyStore(path.Join(b.Homedir, EthereumWalletStorageDir)) signer := accounts.Account{ Address: signerAddress, } @@ -282,7 +291,7 @@ func (b *BridgeClient) GetBalance() (*big.Int, error) { } // VerifyZCNTransaction verifies 0CHain transaction -func (b *BridgeClient) VerifyZCNTransaction(ctx context.Context, hash string) (*transaction.Transaction, error) { +func (b *BridgeClient) VerifyZCNTransaction(ctx context.Context, hash string) (transaction.Transaction, error) { return transaction.Verify(ctx, hash) } @@ -363,6 +372,8 @@ func (b *BridgeClient) MintWZCN(ctx context.Context, payload *ethereum.MintPaylo toAddress := common.HexToAddress(payload.To) + fmt.Println(ctx, payload.To, "mint", toAddress, amount, zcnTxd, nonce, sigs) + bridgeInstance, transactOpts, err := b.prepareBridge(ctx, payload.To, "mint", toAddress, amount, zcnTxd, nonce, sigs) if err != nil { return nil, errors.Wrap(err, "failed to prepare bridge") @@ -467,12 +478,12 @@ func (b *BridgeClient) MintZCN(ctx context.Context, payload *zcnsc.MintPayload) } // BurnZCN burns ZCN tokens before conversion from ZCN to WZCN as a first step -func (b *BridgeClient) BurnZCN(ctx context.Context, amount, txnfee uint64) (*transaction.Transaction, error) { +func (b *BridgeClient) BurnZCN(ctx context.Context, amount, txnfee uint64) (transaction.Transaction, error) { payload := zcnsc.BurnPayload{ - EthereumAddress: b.EthereumAddress, // TODO: this should be receiver address not the bridge + EthereumAddress: b.EthereumAddress, } - trx, err := transaction.NewTransactionEntity(txnfee) + trx, err := b.createTransactionEntity(txnfee) if err != nil { log.Logger.Fatal("failed to create new transaction", zap.Error(err)) } diff --git a/zcnbridge/bridge_test.go b/zcnbridge/bridge_test.go index 9d1e6c1b1..019138ee8 100644 --- a/zcnbridge/bridge_test.go +++ b/zcnbridge/bridge_test.go @@ -11,7 +11,11 @@ import ( sdkcommon "github.com/0chain/gosdk/core/common" "github.com/0chain/gosdk/zcnbridge/ethereum" - "github.com/0chain/gosdk/zcnbridge/mocks" + binding "github.com/0chain/gosdk/zcnbridge/ethereum/bridge" + bridgemocks "github.com/0chain/gosdk/zcnbridge/mocks" + transactionmocks "github.com/0chain/gosdk/zcnbridge/transaction/mocks" + "github.com/0chain/gosdk/zcncore" + eth "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/spf13/viper" "github.com/stretchr/testify/mock" @@ -30,7 +34,7 @@ const ( ZCNTxnID = "b26abeb31fcee5d2e75b26717722938a06fa5ce4a5b5e68ddad68357432caace" Amount = 1e10 - To = "0x2ec8F26ccC678c9faF0Df20208aEE3AF776160CD" + TxnFee = 1 Nonce = 1 ) @@ -51,6 +55,14 @@ func (ecm *ethereumClientMock) Cleanup(callback func()) { callback() } +type transactionEntityMock struct { + mock.TestingT +} + +func (tem *transactionEntityMock) Cleanup(callback func()) { + callback() +} + type authorizerConfigTarget struct { Fee sdkcommon.Balance `json:"fee"` } @@ -152,8 +164,8 @@ func (c *authorizerConfigTarget) decode(input []byte) (err error) { return nil } -func getEthereumClient(t mock.TestingT) *mocks.EthereumClient { - return mocks.NewEthereumClient(ðereumClientMock{t}) +func getEthereumClient(t mock.TestingT) *bridgemocks.EthereumClient { + return bridgemocks.NewEthereumClient(ðereumClientMock{t}) } func getBridgeClient(ethereumClient EthereumClient) *BridgeClient { @@ -179,7 +191,7 @@ func getBridgeClient(ethereumClient EthereumClient) *BridgeClient { return CreateBridgeClient(cfg, ethereumClient) } -func prepareGeneralMockCalls(m *mock.Mock) { +func prepareEthereumClientGeneralMockCalls(m *mock.Mock) { m.On("EstimateGas", mock.Anything, mock.Anything).Return(uint64(400000), nil) m.On("ChainID", mock.Anything).Return(big.NewInt(400000), nil) m.On("PendingNonceAt", mock.Anything, mock.Anything).Return(uint64(Nonce), nil) @@ -187,13 +199,24 @@ func prepareGeneralMockCalls(m *mock.Mock) { m.On("SendTransaction", mock.Anything, mock.Anything).Return(nil) } +func getTransactionEntity(t mock.TestingT) *transactionmocks.Transaction { + return transactionmocks.NewTransaction(&transactionEntityMock{t}) +} + +func prepareTransactionEntityGeneralMockCalls(m *mock.Mock) { + m.On("ExecuteSmartContract", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(ZCNTxnID, nil) + m.On("Verify").Return(nil) +} + func Test_ZCNBridge(t *testing.T) { ethereumClient := getEthereumClient(t) - prepareGeneralMockCalls(ðereumClient.Mock) + prepareEthereumClientGeneralMockCalls(ðereumClient.Mock) bridgeClient := getBridgeClient(ethereumClient) + // Create transaction entity mock + t.Run("should update authorizer config.", func(t *testing.T) { source := &authorizerNodeSource{ ID: "12345678", @@ -216,12 +239,10 @@ func Test_ZCNBridge(t *testing.T) { }) t.Run("should check signature and other data formating in MintWZCN", func(t *testing.T) { - ctx := context.Background() - - _, err := bridgeClient.MintWZCN(ctx, ðereum.MintPayload{ + _, err := bridgeClient.MintWZCN(context.Background(), ðereum.MintPayload{ ZCNTxnID: ZCNTxnID, Amount: Amount, - To: To, + To: ETHEREUM_ADDRESS, Nonce: Nonce, Signatures: Signatures, }) @@ -232,25 +253,81 @@ func Test_ZCNBridge(t *testing.T) { sigs = append(sigs, signature.Signature) } - ethereumClient.AssertCalled( - t, - "prepareBridge", - ctx, - To, - "mint", - common.HexToAddress(To), + to := common.HexToAddress(BRIDGE_ADDRESS) + fromAddress := common.HexToAddress(ETHEREUM_ADDRESS) + + abi, err := binding.BridgeMetaData.GetAbi() + require.NoError(t, err) + + pack, err := abi.Pack("mint", common.HexToAddress(ETHEREUM_ADDRESS), big.NewInt(Amount), DefaultClientIDEncoder(ZCNTxnID), big.NewInt(Nonce), sigs) + require.NoError(t, err) + + require.True(t, ethereumClient.AssertCalled( + t, + "EstimateGas", + context.Background(), + eth.CallMsg{ + To: &to, + From: fromAddress, + Data: pack, + }, + )) }) t.Run("should check data formating in BurnWZCN", func(t *testing.T) { + _, err := bridgeClient.BurnWZCN(context.Background(), Amount) + require.NoError(t, err) + + to := common.HexToAddress(BRIDGE_ADDRESS) + fromAddress := common.HexToAddress(ETHEREUM_ADDRESS) + + abi, err := binding.BridgeMetaData.GetAbi() + require.NoError(t, err) + pack, err := abi.Pack("burn", big.NewInt(Amount), DefaultClientIDEncoder(zcncore.GetClientWalletID())) + require.NoError(t, err) + + require.True(t, ethereumClient.AssertCalled( + t, + "EstimateGas", + context.Background(), + eth.CallMsg{ + To: &to, + From: fromAddress, + Data: pack, + }, + )) }) t.Run("should check data used by BurnZCN", func(t *testing.T) { + ethereumClient.Mock.On("createTransactionEntity") + _, err := bridgeClient.BurnZCN(context.Background(), Amount, TxnFee) + require.NoError(t, err) + + // to := common.HexToAddress(BRIDGE_ADDRESS) + // fromAddress := common.HexToAddress(ETHEREUM_ADDRESS) + + // abi, err := binding.BridgeMetaData.GetAbi() + // require.NoError(t, err) + + // pack, err := abi.Pack("burn", big.NewInt(Amount), DefaultClientIDEncoder(zcncore.GetClientWalletID())) + // require.NoError(t, err) + + // require.True(t, ethereumClient.AssertCalled( + // t, + // "EstimateGas", + // context.Background(), + // eth.CallMsg{ + // To: &to, + // From: fromAddress, + // Data: pack, + // }, + // )) }) t.Run("should check data used by IncreaseBurnerAllowance", func(t *testing.T) { @@ -258,6 +335,14 @@ func Test_ZCNBridge(t *testing.T) { }) t.Run("should check data used by CreateSignedTransactionFromKeyStore", func(t *testing.T) { + bridgeClient.CreateSignedTransactionFromKeyStore(ethereumClient, 400000) + + require.True(t, ethereumClient.AssertCalled( + t, + "PendingNonceAt", + context.Background(), + common.HexToAddress(ETHEREUM_ADDRESS))) + // TODO: check somehow used Password }) } diff --git a/zcnbridge/transaction/functions.go b/zcnbridge/transaction/functions.go index 062b115fd..fdf57c378 100644 --- a/zcnbridge/transaction/functions.go +++ b/zcnbridge/transaction/functions.go @@ -8,19 +8,23 @@ import ( "github.com/0chain/gosdk/zcncore" ) -func AddAuthorizer(ctx context.Context, input *zcncore.AddAuthorizerPayload) (*Transaction, error) { +func AddAuthorizer(ctx context.Context, input *zcncore.AddAuthorizerPayload) (Transaction, error) { t, err := NewTransactionEntity(0) if err != nil { return nil, err } - err = t.scheme.ZCNSCAddAuthorizer(input) + scheme := t.GetScheme() + + err = scheme.ZCNSCAddAuthorizer(input) if err != nil { return t, err } - err = t.callBack.waitCompleteCall(ctx) - t.Hash = t.scheme.Hash() + callBack := t.GetCallback() + + err = callBack.waitCompleteCall(ctx) + t.SetHash(scheme.Hash()) if err != nil { return t, err } @@ -28,19 +32,23 @@ func AddAuthorizer(ctx context.Context, input *zcncore.AddAuthorizerPayload) (*T return t, nil } -func AuthorizerHealthCheck(ctx context.Context, input *zcncore.AuthorizerHealthCheckPayload) (*Transaction, error) { +func AuthorizerHealthCheck(ctx context.Context, input *zcncore.AuthorizerHealthCheckPayload) (Transaction, error) { t, err := NewTransactionEntity(0) if err != nil { return nil, err } - err = t.scheme.ZCNSCAuthorizerHealthCheck(input) + scheme := t.GetScheme() + + err = scheme.ZCNSCAuthorizerHealthCheck(input) if err != nil { return t, err } - err = t.callBack.waitCompleteCall(ctx) - t.Hash = t.scheme.Hash() + callBack := t.GetCallback() + + err = callBack.waitCompleteCall(ctx) + t.SetHash(scheme.Hash()) if err != nil { return t, err } diff --git a/zcnbridge/transaction/txn.go b/zcnbridge/transaction/txn.go index eb4b8d25c..24707cd06 100644 --- a/zcnbridge/transaction/txn.go +++ b/zcnbridge/transaction/txn.go @@ -18,11 +18,22 @@ var ( ) type ( - // Transaction entity that encapsulates the transaction related data and metadata. - Transaction struct { - Hash string `json:"hash,omitempty"` - Version string `json:"version,omitempty"` - TransactionOutput string `json:"transaction_output,omitempty"` + // Transaction interface describes transaction entity. + Transaction interface { + ExecuteSmartContract(ctx context.Context, address, funcName string, input interface{}, val uint64) (string, error) + Verify(ctx context.Context) error + GetScheme() zcncore.TransactionScheme + GetCallback() *callback + GetTransactionOutput() string + GetHash() string + SetHash(string) + } + + // TransactionEntity entity that encapsulates the transaction related data and metadata. + TransactionEntity struct { + hash string `json:"hash,omitempty"` + version string `json:"version,omitempty"` + transactionOutput string `json:"transaction_output,omitempty"` scheme zcncore.TransactionScheme callBack *callback } @@ -39,7 +50,7 @@ type ( Hash string `json:"hash"` BlockHash string `json:"block_hash"` PreviousBlockHash string `json:"previous_block_hash"` - Transaction *Transaction `json:"txn,omitempty"` + Transaction Transaction `json:"txn,omitempty"` CreationDate ctime.Timestamp `json:"creation_date"` MinerID string `json:"miner_id"` Round int64 `json:"round"` @@ -54,8 +65,8 @@ type ( // NewTransactionEntity creates Transaction with initialized fields. // Sets version, client ID, creation date, public key and creates internal zcncore.TransactionScheme. -func NewTransactionEntity(txnFee uint64) (*Transaction, error) { - txn := &Transaction{ +func NewTransactionEntity(txnFee uint64) (Transaction, error) { + txn := &TransactionEntity{ callBack: NewStatus().(*callback), } zcntxn, err := zcncore.NewTransaction(txn.callBack, txnFee, 0) @@ -71,12 +82,12 @@ func NewTransactionEntity(txnFee uint64) (*Transaction, error) { // ExecuteSmartContract executes function of smart contract with provided address. // // Returns hash of executed transaction. -func (t *Transaction) ExecuteSmartContract(ctx context.Context, address, funcName string, input interface{}, +func (t *TransactionEntity) ExecuteSmartContract(ctx context.Context, address, funcName string, input interface{}, val uint64) (string, error) { const errCode = "transaction_send" tran, err := t.scheme.ExecuteSmartContract(address, funcName, input, val) - t.Hash = tran.Hash + t.hash = tran.Hash if err != nil { msg := fmt.Sprintf("error while sending txn: %v", err) @@ -95,7 +106,7 @@ func (t *Transaction) ExecuteSmartContract(ctx context.Context, address, funcNam return t.scheme.Hash(), nil } -func (t *Transaction) Verify(ctx context.Context) error { +func (t *TransactionEntity) Verify(ctx context.Context) error { const errCode = "transaction_verify" err := t.scheme.Verify() @@ -126,8 +137,8 @@ func (t *Transaction) Verify(ctx context.Context) error { } if vo.Confirmation.Transaction != nil { - t.Hash = vo.Confirmation.Transaction.Hash - t.TransactionOutput = vo.Confirmation.Transaction.TransactionOutput + t.hash = vo.Confirmation.Transaction.GetHash() + t.transactionOutput = vo.Confirmation.Transaction.GetTransactionOutput() } else { return errors.New(errCode, "got invalid confirmation (missing transaction)") } @@ -135,14 +146,45 @@ func (t *Transaction) Verify(ctx context.Context) error { return nil } +// GetSheme returns transaction scheme +func (t *TransactionEntity) GetScheme() zcncore.TransactionScheme { + return t.scheme +} + +// GetHash returns transaction hash +func (t *TransactionEntity) GetHash() string { + return t.hash +} + +// SetHash sets transaction hash +func (t *TransactionEntity) SetHash(hash string) { + t.hash = hash +} + +// GetTransactionOutput returns transaction output +func (t *TransactionEntity) GetTransactionOutput() string { + return t.transactionOutput +} + +func (t *TransactionEntity) GetCallback() *callback { + return t.callBack +} + +// GetVersion returns transaction version +func (t *TransactionEntity) GetVersion() string { + return t.version +} + // Verify checks including of transaction in the blockchain. -func Verify(ctx context.Context, hash string) (*Transaction, error) { +func Verify(ctx context.Context, hash string) (Transaction, error) { t, err := NewTransactionEntity(0) if err != nil { return nil, err } - if err := t.scheme.SetTransactionHash(hash); err != nil { + scheme := t.GetScheme() + + if err := scheme.SetTransactionHash(hash); err != nil { return nil, err } From 07efc9fd7492eec3b04e540824e56a958b9fe060 Mon Sep 17 00:00:00 2001 From: YarikRevich Date: Fri, 25 Aug 2023 20:49:00 +0200 Subject: [PATCH 003/134] fix: fixed bugs --- zcnbridge/bridge.go | 11 +--- zcnbridge/bridge_test.go | 100 ++++++++++++++++++++++------- zcnbridge/config.go | 29 +++++---- zcnbridge/transaction/callback.go | 14 +++- zcnbridge/transaction/functions.go | 4 +- zcnbridge/transaction/txn.go | 64 +++++++++++------- 6 files changed, 148 insertions(+), 74 deletions(-) diff --git a/zcnbridge/bridge.go b/zcnbridge/bridge.go index 73895c186..9d3ff976a 100644 --- a/zcnbridge/bridge.go +++ b/zcnbridge/bridge.go @@ -59,11 +59,6 @@ var ( } ) -// createTransactionEntity HOC for 0chain transaction entity creation. -func (b *BridgeClient) createTransactionEntity(txnfee uint64) (transaction.Transaction, error) { - return transaction.NewTransactionEntity(txnfee) -} - // getKeyStore reutrns key storage located in the given path. func (b *BridgeClient) getKeyStore(path string) *keystore.KeyStore { return keystore.NewKeyStore(path, keystore.StandardScryptN, keystore.StandardScryptP) @@ -372,8 +367,6 @@ func (b *BridgeClient) MintWZCN(ctx context.Context, payload *ethereum.MintPaylo toAddress := common.HexToAddress(payload.To) - fmt.Println(ctx, payload.To, "mint", toAddress, amount, zcnTxd, nonce, sigs) - bridgeInstance, transactOpts, err := b.prepareBridge(ctx, payload.To, "mint", toAddress, amount, zcnTxd, nonce, sigs) if err != nil { return nil, errors.Wrap(err, "failed to prepare bridge") @@ -447,7 +440,7 @@ func (b *BridgeClient) BurnWZCN(ctx context.Context, amountTokens uint64) (*type // MintZCN mints ZCN tokens after receiving proof-of-burn of WZCN tokens func (b *BridgeClient) MintZCN(ctx context.Context, payload *zcnsc.MintPayload) (string, error) { - trx, err := transaction.NewTransactionEntity(0) + trx, err := b.TransactionProvider.NewTransactionEntity(0) if err != nil { log.Logger.Fatal("failed to create new transaction", zap.Error(err)) } @@ -483,7 +476,7 @@ func (b *BridgeClient) BurnZCN(ctx context.Context, amount, txnfee uint64) (tran EthereumAddress: b.EthereumAddress, } - trx, err := b.createTransactionEntity(txnfee) + trx, err := b.TransactionProvider.NewTransactionEntity(txnfee) if err != nil { log.Logger.Fatal("failed to create new transaction", zap.Error(err)) } diff --git a/zcnbridge/bridge_test.go b/zcnbridge/bridge_test.go index 019138ee8..ab1c9acb6 100644 --- a/zcnbridge/bridge_test.go +++ b/zcnbridge/bridge_test.go @@ -12,8 +12,11 @@ import ( sdkcommon "github.com/0chain/gosdk/core/common" "github.com/0chain/gosdk/zcnbridge/ethereum" binding "github.com/0chain/gosdk/zcnbridge/ethereum/bridge" + "github.com/0chain/gosdk/zcnbridge/ethereum/erc20" bridgemocks "github.com/0chain/gosdk/zcnbridge/mocks" + "github.com/0chain/gosdk/zcnbridge/transaction" transactionmocks "github.com/0chain/gosdk/zcnbridge/transaction/mocks" + "github.com/0chain/gosdk/zcnbridge/zcnsc" "github.com/0chain/gosdk/zcncore" eth "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" @@ -55,11 +58,11 @@ func (ecm *ethereumClientMock) Cleanup(callback func()) { callback() } -type transactionEntityMock struct { +type transactionProviderMock struct { mock.TestingT } -func (tem *transactionEntityMock) Cleanup(callback func()) { +func (tem *transactionProviderMock) Cleanup(callback func()) { callback() } @@ -168,7 +171,7 @@ func getEthereumClient(t mock.TestingT) *bridgemocks.EthereumClient { return bridgemocks.NewEthereumClient(ðereumClientMock{t}) } -func getBridgeClient(ethereumClient EthereumClient) *BridgeClient { +func getBridgeClient(ethereumClient EthereumClient, transactionProvider transaction.TransactionProvider) *BridgeClient { cfg := viper.New() tempConfigFile, err := os.CreateTemp(".", "config.yaml") @@ -188,34 +191,34 @@ func getBridgeClient(ethereumClient EthereumClient) *BridgeClient { cfg.SetDefault("bridge.gas_limit", 0) cfg.SetDefault("bridge.consensus_threshold", 0) - return CreateBridgeClient(cfg, ethereumClient) + return createBridgeClient(cfg, ethereumClient, transactionProvider) } -func prepareEthereumClientGeneralMockCalls(m *mock.Mock) { - m.On("EstimateGas", mock.Anything, mock.Anything).Return(uint64(400000), nil) - m.On("ChainID", mock.Anything).Return(big.NewInt(400000), nil) - m.On("PendingNonceAt", mock.Anything, mock.Anything).Return(uint64(Nonce), nil) - m.On("SuggestGasPrice", mock.Anything).Return(big.NewInt(400000), nil) - m.On("SendTransaction", mock.Anything, mock.Anything).Return(nil) +func prepareEthereumClientGeneralMockCalls(ethereumClient *mock.Mock) { + ethereumClient.On("EstimateGas", mock.Anything, mock.Anything).Return(uint64(400000), nil) + ethereumClient.On("ChainID", mock.Anything).Return(big.NewInt(400000), nil) + ethereumClient.On("PendingNonceAt", mock.Anything, mock.Anything).Return(uint64(Nonce), nil) + ethereumClient.On("SuggestGasPrice", mock.Anything).Return(big.NewInt(400000), nil) + ethereumClient.On("SendTransaction", mock.Anything, mock.Anything).Return(nil) } -func getTransactionEntity(t mock.TestingT) *transactionmocks.Transaction { - return transactionmocks.NewTransaction(&transactionEntityMock{t}) +func getTransactionProvider(t mock.TestingT) *transactionmocks.TransactionProvider { + return transactionmocks.NewTransactionProvider(&transactionProviderMock{t}) } -func prepareTransactionEntityGeneralMockCalls(m *mock.Mock) { - m.On("ExecuteSmartContract", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(ZCNTxnID, nil) - m.On("Verify").Return(nil) +func prepareTransactionEntityGeneralMockCalls(transactionProvider *mock.Mock) { + transactionProvider.On("ExecuteSmartContract", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(ZCNTxnID, nil) + transactionProvider.On("Verify").Return(nil) } func Test_ZCNBridge(t *testing.T) { ethereumClient := getEthereumClient(t) - prepareEthereumClientGeneralMockCalls(ðereumClient.Mock) - bridgeClient := getBridgeClient(ethereumClient) + transactionProvider := getTransactionProvider(t) + prepareTransactionEntityGeneralMockCalls(&transactionProvider.Mock) - // Create transaction entity mock + bridgeClient := getBridgeClient(ethereumClient, transactionProvider) t.Run("should update authorizer config.", func(t *testing.T) { source := &authorizerNodeSource{ @@ -238,7 +241,7 @@ func Test_ZCNBridge(t *testing.T) { require.Equal(t, sdkcommon.Balance(999), target.Config.Fee) }) - t.Run("should check signature and other data formating in MintWZCN", func(t *testing.T) { + t.Run("should check configuration formating in MintWZCN", func(t *testing.T) { _, err := bridgeClient.MintWZCN(context.Background(), ðereum.MintPayload{ ZCNTxnID: ZCNTxnID, Amount: Amount, @@ -276,9 +279,10 @@ func Test_ZCNBridge(t *testing.T) { Data: pack, }, )) + }) - t.Run("should check data formating in BurnWZCN", func(t *testing.T) { + t.Run("should check configuration formating in BurnWZCN", func(t *testing.T) { _, err := bridgeClient.BurnWZCN(context.Background(), Amount) require.NoError(t, err) @@ -303,9 +307,34 @@ func Test_ZCNBridge(t *testing.T) { )) }) - t.Run("should check data used by BurnZCN", func(t *testing.T) { - ethereumClient.Mock.On("createTransactionEntity") + t.Run("should check configuration used by MintZCN", func(t *testing.T) { + // ethereumClient.Mock.On("createTransactionEntity") + + _, err := bridgeClient.MintZCN(context.Background(), &zcnsc.MintPayload{}) + require.NoError(t, err) + + // to := common.HexToAddress(BRIDGE_ADDRESS) + // fromAddress := common.HexToAddress(ETHEREUM_ADDRESS) + + // abi, err := binding.BridgeMetaData.GetAbi() + // require.NoError(t, err) + + // pack, err := abi.Pack("burn", big.NewInt(Amount), DefaultClientIDEncoder(zcncore.GetClientWalletID())) + // require.NoError(t, err) + // require.True(t, ethereumClient.AssertCalled( + // t, + // "EstimateGas", + // context.Background(), + // eth.CallMsg{ + // To: &to, + // From: fromAddress, + // Data: pack, + // }, + // )) + }) + + t.Run("should check configuration used by BurnZCN", func(t *testing.T) { _, err := bridgeClient.BurnZCN(context.Background(), Amount, TxnFee) require.NoError(t, err) @@ -330,11 +359,34 @@ func Test_ZCNBridge(t *testing.T) { // )) }) - t.Run("should check data used by IncreaseBurnerAllowance", func(t *testing.T) { + t.Run("should check configuration used by IncreaseBurnerAllowance", func(t *testing.T) { + _, err := bridgeClient.IncreaseBurnerAllowance(context.Background(), Amount) + require.NoError(t, err) + + spenderAddress := common.HexToAddress(BRIDGE_ADDRESS) + + to := common.HexToAddress(TOKEN_ADDRESS) + fromAddress := common.HexToAddress(ETHEREUM_ADDRESS) + + abi, err := erc20.ERC20MetaData.GetAbi() + require.NoError(t, err) + + pack, err := abi.Pack("increaseAllowance", spenderAddress, big.NewInt(Amount)) + require.NoError(t, err) + require.True(t, ethereumClient.AssertCalled( + t, + "EstimateGas", + context.Background(), + eth.CallMsg{ + To: &to, + From: fromAddress, + Data: pack, + }, + )) }) - t.Run("should check data used by CreateSignedTransactionFromKeyStore", func(t *testing.T) { + t.Run("should check configuration used by CreateSignedTransactionFromKeyStore", func(t *testing.T) { bridgeClient.CreateSignedTransactionFromKeyStore(ethereumClient, 400000) require.True(t, ethereumClient.AssertCalled( diff --git a/zcnbridge/config.go b/zcnbridge/config.go index 020882484..297576575 100644 --- a/zcnbridge/config.go +++ b/zcnbridge/config.go @@ -7,6 +7,7 @@ import ( "path" "github.com/0chain/gosdk/zcnbridge/log" + "github.com/0chain/gosdk/zcnbridge/transaction" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/ethclient" @@ -28,6 +29,7 @@ type BridgeSDKConfig struct { } type BridgeClient struct { + transaction.TransactionProvider EthereumClient BridgeAddress, @@ -48,24 +50,25 @@ type EthereumClient interface { ChainID(ctx context.Context) (*big.Int, error) } -// CreateBridgeClient initializes new bridge client with the help of the given +// createBridgeClient initializes new bridge client with the help of the given // Ethereum JSON-RPC client and locally-defined confiruration. -func CreateBridgeClient(cfg *viper.Viper, ethereumClient EthereumClient) *BridgeClient { +func createBridgeClient(cfg *viper.Viper, ethereumClient EthereumClient, transactionProvider transaction.TransactionProvider) *BridgeClient { homedir := path.Dir(cfg.ConfigFileUsed()) if homedir == "" { log.Logger.Fatal("homedir is required") } return &BridgeClient{ - BridgeAddress: cfg.GetString("bridge.bridge_address"), - TokenAddress: cfg.GetString("bridge.token_address"), - AuthorizersAddress: cfg.GetString("bridge.authorizers_address"), - EthereumAddress: cfg.GetString("bridge.ethereum_address"), - Password: cfg.GetString("bridge.password"), - GasLimit: cfg.GetUint64("bridge.gas_limit"), - ConsensusThreshold: cfg.GetFloat64("bridge.consensus_threshold"), - Homedir: homedir, - EthereumClient: ethereumClient, + BridgeAddress: cfg.GetString("bridge.bridge_address"), + TokenAddress: cfg.GetString("bridge.token_address"), + AuthorizersAddress: cfg.GetString("bridge.authorizers_address"), + EthereumAddress: cfg.GetString("bridge.ethereum_address"), + Password: cfg.GetString("bridge.password"), + GasLimit: cfg.GetUint64("bridge.gas_limit"), + ConsensusThreshold: cfg.GetFloat64("bridge.consensus_threshold"), + Homedir: homedir, + EthereumClient: ethereumClient, + TransactionProvider: transactionProvider, } } @@ -81,7 +84,9 @@ func SetupBridgeClientSDK(cfg *BridgeSDKConfig) *BridgeClient { Logger.Error(err) } - bridgeClient := CreateBridgeClient(chainCfg, ethereumClient) + transactionProvider := transaction.NewTransactionProvider() + + bridgeClient := createBridgeClient(chainCfg, ethereumClient, transactionProvider) return bridgeClient } diff --git a/zcnbridge/transaction/callback.go b/zcnbridge/transaction/callback.go index 8481b822a..0ce4a1e1a 100644 --- a/zcnbridge/transaction/callback.go +++ b/zcnbridge/transaction/callback.go @@ -13,6 +13,14 @@ var ( ) type ( + // TransactionCallbackAwaitable extends zcncore.TransactionCallback with synchronization methods + TransactionCallbackAwaitable interface { + zcncore.TransactionCallback + + WaitCompleteCall(ctx context.Context) error + WaitVerifyCall(ctx context.Context) error + } + // callback implements zcncore.TransactionCallback interface. callback struct { // waitCh represents channel for making callback.OnTransactionComplete, @@ -22,7 +30,7 @@ type ( } ) -func NewStatus() zcncore.TransactionCallback { +func NewStatus() TransactionCallbackAwaitable { return &callback{ waitCh: make(chan interface{}), } @@ -58,7 +66,7 @@ func (cb *callback) OnAuthComplete(_ *zcncore.Transaction, status int) { cb.sendCall() } -func (cb *callback) waitCompleteCall(ctx context.Context) error { +func (cb *callback) WaitCompleteCall(ctx context.Context) error { select { case <-ctx.Done(): return errors.New("completing_transaction", "completing transaction context deadline exceeded") @@ -67,7 +75,7 @@ func (cb *callback) waitCompleteCall(ctx context.Context) error { } } -func (cb *callback) waitVerifyCall(ctx context.Context) error { +func (cb *callback) WaitVerifyCall(ctx context.Context) error { select { case <-ctx.Done(): return errors.New("verifying_transaction", "verifying transaction context deadline exceeded") diff --git a/zcnbridge/transaction/functions.go b/zcnbridge/transaction/functions.go index fdf57c378..bf9845645 100644 --- a/zcnbridge/transaction/functions.go +++ b/zcnbridge/transaction/functions.go @@ -23,7 +23,7 @@ func AddAuthorizer(ctx context.Context, input *zcncore.AddAuthorizerPayload) (Tr callBack := t.GetCallback() - err = callBack.waitCompleteCall(ctx) + err = callBack.WaitCompleteCall(ctx) t.SetHash(scheme.Hash()) if err != nil { return t, err @@ -47,7 +47,7 @@ func AuthorizerHealthCheck(ctx context.Context, input *zcncore.AuthorizerHealthC callBack := t.GetCallback() - err = callBack.waitCompleteCall(ctx) + err = callBack.WaitCompleteCall(ctx) t.SetHash(scheme.Hash()) if err != nil { return t, err diff --git a/zcnbridge/transaction/txn.go b/zcnbridge/transaction/txn.go index 24707cd06..08f48afd7 100644 --- a/zcnbridge/transaction/txn.go +++ b/zcnbridge/transaction/txn.go @@ -18,24 +18,32 @@ var ( ) type ( + // TransactionProvider ... + TransactionProvider interface { + NewTransactionEntity(txnFee uint64) (Transaction, error) + } + + // transactionProvider ... + transactionProvider struct{} + // Transaction interface describes transaction entity. Transaction interface { ExecuteSmartContract(ctx context.Context, address, funcName string, input interface{}, val uint64) (string, error) Verify(ctx context.Context) error GetScheme() zcncore.TransactionScheme - GetCallback() *callback + GetCallback() TransactionCallbackAwaitable GetTransactionOutput() string GetHash() string SetHash(string) } // TransactionEntity entity that encapsulates the transaction related data and metadata. - TransactionEntity struct { - hash string `json:"hash,omitempty"` - version string `json:"version,omitempty"` - transactionOutput string `json:"transaction_output,omitempty"` + transactionEntity struct { + Hash string `json:"hash,omitempty"` + Version string `json:"version,omitempty"` + TransactionOutput string `json:"transaction_output,omitempty"` scheme zcncore.TransactionScheme - callBack *callback + callBack TransactionCallbackAwaitable } ) @@ -63,10 +71,18 @@ type ( } ) +func NewTransactionProvider() TransactionProvider { + return &transactionProvider{} +} + +func (t *transactionProvider) NewTransactionEntity(txnFee uint64) (Transaction, error) { + return NewTransactionEntity(txnFee) +} + // NewTransactionEntity creates Transaction with initialized fields. // Sets version, client ID, creation date, public key and creates internal zcncore.TransactionScheme. func NewTransactionEntity(txnFee uint64) (Transaction, error) { - txn := &TransactionEntity{ + txn := &transactionEntity{ callBack: NewStatus().(*callback), } zcntxn, err := zcncore.NewTransaction(txn.callBack, txnFee, 0) @@ -82,19 +98,19 @@ func NewTransactionEntity(txnFee uint64) (Transaction, error) { // ExecuteSmartContract executes function of smart contract with provided address. // // Returns hash of executed transaction. -func (t *TransactionEntity) ExecuteSmartContract(ctx context.Context, address, funcName string, input interface{}, +func (t *transactionEntity) ExecuteSmartContract(ctx context.Context, address, funcName string, input interface{}, val uint64) (string, error) { const errCode = "transaction_send" tran, err := t.scheme.ExecuteSmartContract(address, funcName, input, val) - t.hash = tran.Hash + t.Hash = tran.Hash if err != nil { msg := fmt.Sprintf("error while sending txn: %v", err) return "", errors.New(errCode, msg) } - if err := t.callBack.waitCompleteCall(ctx); err != nil { + if err := t.callBack.WaitCompleteCall(ctx); err != nil { msg := fmt.Sprintf("error while sending txn: %v", err) return "", errors.New(errCode, msg) } @@ -106,7 +122,7 @@ func (t *TransactionEntity) ExecuteSmartContract(ctx context.Context, address, f return t.scheme.Hash(), nil } -func (t *TransactionEntity) Verify(ctx context.Context) error { +func (t *transactionEntity) Verify(ctx context.Context) error { const errCode = "transaction_verify" err := t.scheme.Verify() @@ -115,7 +131,7 @@ func (t *TransactionEntity) Verify(ctx context.Context) error { return errors.New(errCode, msg) } - if err := t.callBack.waitVerifyCall(ctx); err != nil { + if err := t.callBack.WaitVerifyCall(ctx); err != nil { msg := fmt.Sprintf("error while verifying txn: %v; txn hash: %s", err, t.scheme.GetTransactionHash()) return errors.New(errCode, msg) } @@ -137,8 +153,8 @@ func (t *TransactionEntity) Verify(ctx context.Context) error { } if vo.Confirmation.Transaction != nil { - t.hash = vo.Confirmation.Transaction.GetHash() - t.transactionOutput = vo.Confirmation.Transaction.GetTransactionOutput() + t.Hash = vo.Confirmation.Transaction.GetHash() + t.TransactionOutput = vo.Confirmation.Transaction.GetTransactionOutput() } else { return errors.New(errCode, "got invalid confirmation (missing transaction)") } @@ -147,32 +163,32 @@ func (t *TransactionEntity) Verify(ctx context.Context) error { } // GetSheme returns transaction scheme -func (t *TransactionEntity) GetScheme() zcncore.TransactionScheme { +func (t *transactionEntity) GetScheme() zcncore.TransactionScheme { return t.scheme } // GetHash returns transaction hash -func (t *TransactionEntity) GetHash() string { - return t.hash +func (t *transactionEntity) GetHash() string { + return t.Hash } // SetHash sets transaction hash -func (t *TransactionEntity) SetHash(hash string) { - t.hash = hash +func (t *transactionEntity) SetHash(hash string) { + t.Hash = hash } // GetTransactionOutput returns transaction output -func (t *TransactionEntity) GetTransactionOutput() string { - return t.transactionOutput +func (t *transactionEntity) GetTransactionOutput() string { + return t.TransactionOutput } -func (t *TransactionEntity) GetCallback() *callback { +func (t *transactionEntity) GetCallback() TransactionCallbackAwaitable { return t.callBack } // GetVersion returns transaction version -func (t *TransactionEntity) GetVersion() string { - return t.version +func (t *transactionEntity) GetVersion() string { + return t.Version } // Verify checks including of transaction in the blockchain. From 8a82e5c7cb9e90a662b732de67ae08e7ef37ae8f Mon Sep 17 00:00:00 2001 From: YarikRevich Date: Fri, 25 Aug 2023 21:15:19 +0200 Subject: [PATCH 004/134] fix: fixed bugs --- zcnbridge/bridge_test.go | 187 +++++++++++++++++++++------------------ 1 file changed, 103 insertions(+), 84 deletions(-) diff --git a/zcnbridge/bridge_test.go b/zcnbridge/bridge_test.go index ab1c9acb6..5716f964f 100644 --- a/zcnbridge/bridge_test.go +++ b/zcnbridge/bridge_test.go @@ -16,6 +16,7 @@ import ( bridgemocks "github.com/0chain/gosdk/zcnbridge/mocks" "github.com/0chain/gosdk/zcnbridge/transaction" transactionmocks "github.com/0chain/gosdk/zcnbridge/transaction/mocks" + "github.com/0chain/gosdk/zcnbridge/wallet" "github.com/0chain/gosdk/zcnbridge/zcnsc" "github.com/0chain/gosdk/zcncore" eth "github.com/ethereum/go-ethereum" @@ -26,28 +27,39 @@ import ( ) const ( - ETHEREUM_MNEMONIC = "symbol alley celery diesel donate moral almost opinion achieve since diamond page" + ethereumMnemonic = "symbol alley celery diesel donate moral almost opinion achieve since diamond page" - ETHEREUM_ADDRESS = "0xD8c9156e782C68EE671C09b6b92de76C97948432" - PASSWORD = "\"02289b9\"" + ethereumAddress = "0xD8c9156e782C68EE671C09b6b92de76C97948432" + password = "\"02289b9\"" - BRIDGE_ADDRESS = "0x7bbbEa24ac1751317D7669f05558632c4A9113D7" - TOKEN_ADDRESS = "0x2ec8F26ccC678c9faF0Df20208aEE3AF776160CD" - AUTHORIZER_ADDRESS = "0xEAe8229c0E457efBA1A1769e7F8c20110fF68E61" + bridgeAddress = "0x7bbbEa24ac1751317D7669f05558632c4A9113D7" + tokenAddress = "0x2ec8F26ccC678c9faF0Df20208aEE3AF776160CD" + authorizerAddress = "0xEAe8229c0E457efBA1A1769e7F8c20110fF68E61" - ZCNTxnID = "b26abeb31fcee5d2e75b26717722938a06fa5ce4a5b5e68ddad68357432caace" - Amount = 1e10 - TxnFee = 1 - Nonce = 1 + zcnTxnID = "b26abeb31fcee5d2e75b26717722938a06fa5ce4a5b5e68ddad68357432caace" + amount = 1e10 + txnFee = 1 + nonce = 1 + + ethereumTxnID = "0x3b59971c2aa294739cd73912f0c5a7996aafb796238cf44408b0eb4af0fbac82" + + clientId = "d6e9b3222434faa043c683d1a939d6a0fa2818c4d56e794974d64a32005330d3" ) var ( - Signatures = []*ethereum.AuthorizerSignature{ + ethereumSignatures = []*ethereum.AuthorizerSignature{ { ID: "0x2ec8F26ccC678c9faF0Df20208aEE3AF776160CD", Signature: []byte("0xEAe8229c0E457efBA1A1769e7F8c20110fF68E61"), }, } + + zcnScSignatures = []*zcnsc.AuthorizerSignature{ + { + ID: "0x2ec8F26ccC678c9faF0Df20208aEE3AF776160CD", + Signature: "0xEAe8229c0E457efBA1A1769e7F8c20110fF68E61", + }, + } ) type ethereumClientMock struct { @@ -58,6 +70,14 @@ func (ecm *ethereumClientMock) Cleanup(callback func()) { callback() } +type transactionMock struct { + mock.TestingT +} + +func (tem *transactionMock) Cleanup(callback func()) { + callback() +} + type transactionProviderMock struct { mock.TestingT } @@ -183,11 +203,11 @@ func getBridgeClient(ethereumClient EthereumClient, transactionProvider transact cfg.SetConfigFile(tempConfigFile.Name()) - cfg.SetDefault("bridge.bridge_address", BRIDGE_ADDRESS) - cfg.SetDefault("bridge.token_address", TOKEN_ADDRESS) - cfg.SetDefault("bridge.authorizers_address", AUTHORIZER_ADDRESS) - cfg.SetDefault("bridge.ethereum_address", ETHEREUM_ADDRESS) - cfg.SetDefault("bridge.password", PASSWORD) + cfg.SetDefault("bridge.bridge_address", bridgeAddress) + cfg.SetDefault("bridge.token_address", tokenAddress) + cfg.SetDefault("bridge.authorizers_address", authorizerAddress) + cfg.SetDefault("bridge.ethereum_address", ethereumAddress) + cfg.SetDefault("bridge.password", password) cfg.SetDefault("bridge.gas_limit", 0) cfg.SetDefault("bridge.consensus_threshold", 0) @@ -197,26 +217,37 @@ func getBridgeClient(ethereumClient EthereumClient, transactionProvider transact func prepareEthereumClientGeneralMockCalls(ethereumClient *mock.Mock) { ethereumClient.On("EstimateGas", mock.Anything, mock.Anything).Return(uint64(400000), nil) ethereumClient.On("ChainID", mock.Anything).Return(big.NewInt(400000), nil) - ethereumClient.On("PendingNonceAt", mock.Anything, mock.Anything).Return(uint64(Nonce), nil) + ethereumClient.On("PendingNonceAt", mock.Anything, mock.Anything).Return(uint64(nonce), nil) ethereumClient.On("SuggestGasPrice", mock.Anything).Return(big.NewInt(400000), nil) ethereumClient.On("SendTransaction", mock.Anything, mock.Anything).Return(nil) } +func getTransaction(t mock.TestingT) *transactionmocks.Transaction { + return transactionmocks.NewTransaction(&transactionMock{t}) +} + +func prepareTransactionGeneralMockCalls(transaction *mock.Mock) { + transaction.On("ExecuteSmartContract", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(zcnTxnID, nil) + transaction.On("Verify").Return(nil) +} + func getTransactionProvider(t mock.TestingT) *transactionmocks.TransactionProvider { return transactionmocks.NewTransactionProvider(&transactionProviderMock{t}) } -func prepareTransactionEntityGeneralMockCalls(transactionProvider *mock.Mock) { - transactionProvider.On("ExecuteSmartContract", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(ZCNTxnID, nil) - transactionProvider.On("Verify").Return(nil) +func prepareTransactionProviderGeneralMockCalls(transactionProvider, transaction *mock.Mock) { + transactionProvider.On("NewTransactionEntity", mock.Anything).Return(transaction) } func Test_ZCNBridge(t *testing.T) { ethereumClient := getEthereumClient(t) prepareEthereumClientGeneralMockCalls(ðereumClient.Mock) + transaction := getTransaction(t) + prepareTransactionGeneralMockCalls(&transaction.Mock) + transactionProvider := getTransactionProvider(t) - prepareTransactionEntityGeneralMockCalls(&transactionProvider.Mock) + prepareTransactionProviderGeneralMockCalls(&transactionProvider.Mock, &transaction.Mock) bridgeClient := getBridgeClient(ethereumClient, transactionProvider) @@ -243,29 +274,29 @@ func Test_ZCNBridge(t *testing.T) { t.Run("should check configuration formating in MintWZCN", func(t *testing.T) { _, err := bridgeClient.MintWZCN(context.Background(), ðereum.MintPayload{ - ZCNTxnID: ZCNTxnID, - Amount: Amount, - To: ETHEREUM_ADDRESS, - Nonce: Nonce, - Signatures: Signatures, + ZCNTxnID: zcnTxnID, + Amount: amount, + To: ethereumAddress, + Nonce: nonce, + Signatures: ethereumSignatures, }) require.NoError(t, err) var sigs [][]byte - for _, signature := range Signatures { + for _, signature := range ethereumSignatures { sigs = append(sigs, signature.Signature) } - to := common.HexToAddress(BRIDGE_ADDRESS) - fromAddress := common.HexToAddress(ETHEREUM_ADDRESS) + to := common.HexToAddress(bridgeAddress) + fromAddress := common.HexToAddress(ethereumAddress) abi, err := binding.BridgeMetaData.GetAbi() require.NoError(t, err) - pack, err := abi.Pack("mint", common.HexToAddress(ETHEREUM_ADDRESS), - big.NewInt(Amount), - DefaultClientIDEncoder(ZCNTxnID), - big.NewInt(Nonce), + pack, err := abi.Pack("mint", common.HexToAddress(ethereumAddress), + big.NewInt(amount), + DefaultClientIDEncoder(zcnTxnID), + big.NewInt(nonce), sigs) require.NoError(t, err) @@ -283,16 +314,16 @@ func Test_ZCNBridge(t *testing.T) { }) t.Run("should check configuration formating in BurnWZCN", func(t *testing.T) { - _, err := bridgeClient.BurnWZCN(context.Background(), Amount) + _, err := bridgeClient.BurnWZCN(context.Background(), amount) require.NoError(t, err) - to := common.HexToAddress(BRIDGE_ADDRESS) - fromAddress := common.HexToAddress(ETHEREUM_ADDRESS) + to := common.HexToAddress(bridgeAddress) + fromAddress := common.HexToAddress(ethereumAddress) abi, err := binding.BridgeMetaData.GetAbi() require.NoError(t, err) - pack, err := abi.Pack("burn", big.NewInt(Amount), DefaultClientIDEncoder(zcncore.GetClientWalletID())) + pack, err := abi.Pack("burn", big.NewInt(amount), DefaultClientIDEncoder(zcncore.GetClientWalletID())) require.NoError(t, err) require.True(t, ethereumClient.AssertCalled( @@ -308,70 +339,58 @@ func Test_ZCNBridge(t *testing.T) { }) t.Run("should check configuration used by MintZCN", func(t *testing.T) { - // ethereumClient.Mock.On("createTransactionEntity") + payload := &zcnsc.MintPayload{ + EthereumTxnID: ethereumTxnID, + Amount: sdkcommon.Balance(amount), + Nonce: nonce, + Signatures: zcnScSignatures, + ReceivingClientID: clientId, + } - _, err := bridgeClient.MintZCN(context.Background(), &zcnsc.MintPayload{}) + _, err := bridgeClient.MintZCN(context.Background(), payload) require.NoError(t, err) - // to := common.HexToAddress(BRIDGE_ADDRESS) - // fromAddress := common.HexToAddress(ETHEREUM_ADDRESS) - - // abi, err := binding.BridgeMetaData.GetAbi() - // require.NoError(t, err) - - // pack, err := abi.Pack("burn", big.NewInt(Amount), DefaultClientIDEncoder(zcncore.GetClientWalletID())) - // require.NoError(t, err) - - // require.True(t, ethereumClient.AssertCalled( - // t, - // "EstimateGas", - // context.Background(), - // eth.CallMsg{ - // To: &to, - // From: fromAddress, - // Data: pack, - // }, - // )) + require.True(t, transactionProvider.AssertCalled( + t, + "ExecuteSmartContract", + context.Background(), + wallet.ZCNSCSmartContractAddress, + wallet.MintFunc, + payload, + 0, + )) }) t.Run("should check configuration used by BurnZCN", func(t *testing.T) { - _, err := bridgeClient.BurnZCN(context.Background(), Amount, TxnFee) + _, err := bridgeClient.BurnZCN(context.Background(), amount, txnFee) require.NoError(t, err) - // to := common.HexToAddress(BRIDGE_ADDRESS) - // fromAddress := common.HexToAddress(ETHEREUM_ADDRESS) - - // abi, err := binding.BridgeMetaData.GetAbi() - // require.NoError(t, err) - - // pack, err := abi.Pack("burn", big.NewInt(Amount), DefaultClientIDEncoder(zcncore.GetClientWalletID())) - // require.NoError(t, err) - - // require.True(t, ethereumClient.AssertCalled( - // t, - // "EstimateGas", - // context.Background(), - // eth.CallMsg{ - // To: &to, - // From: fromAddress, - // Data: pack, - // }, - // )) + require.True(t, transactionProvider.AssertCalled( + t, + "ExecuteSmartContract", + context.Background(), + wallet.ZCNSCSmartContractAddress, + wallet.BurnFunc, + zcnsc.BurnPayload{ + EthereumAddress: ethereumAddress, + }, + amount, + )) }) t.Run("should check configuration used by IncreaseBurnerAllowance", func(t *testing.T) { - _, err := bridgeClient.IncreaseBurnerAllowance(context.Background(), Amount) + _, err := bridgeClient.IncreaseBurnerAllowance(context.Background(), amount) require.NoError(t, err) - spenderAddress := common.HexToAddress(BRIDGE_ADDRESS) + spenderAddress := common.HexToAddress(bridgeAddress) - to := common.HexToAddress(TOKEN_ADDRESS) - fromAddress := common.HexToAddress(ETHEREUM_ADDRESS) + to := common.HexToAddress(tokenAddress) + fromAddress := common.HexToAddress(ethereumAddress) abi, err := erc20.ERC20MetaData.GetAbi() require.NoError(t, err) - pack, err := abi.Pack("increaseAllowance", spenderAddress, big.NewInt(Amount)) + pack, err := abi.Pack("increaseAllowance", spenderAddress, big.NewInt(amount)) require.NoError(t, err) require.True(t, ethereumClient.AssertCalled( @@ -393,7 +412,7 @@ func Test_ZCNBridge(t *testing.T) { t, "PendingNonceAt", context.Background(), - common.HexToAddress(ETHEREUM_ADDRESS))) + common.HexToAddress(ethereumAddress))) // TODO: check somehow used Password }) From 84787ffd47cbe0ba828ea6828b4ecba713d05887 Mon Sep 17 00:00:00 2001 From: YarikRevich Date: Fri, 25 Aug 2023 21:15:40 +0200 Subject: [PATCH 005/134] fix: fixed bugs --- wasmsdk/bridge.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wasmsdk/bridge.go b/wasmsdk/bridge.go index 2c5599547..27a625769 100644 --- a/wasmsdk/bridge.go +++ b/wasmsdk/bridge.go @@ -60,7 +60,7 @@ func burnZCN(amount, txnfee uint64) string { //nolint return errors.Wrap("burnZCN", "failed to burn ZCN tokens", err).Error() } - return tx.Hash + return tx.GetHash() } // Mints ZCN tokens and returns a hash of the mint transaction From 14e845c796b3b9a5452b73d3f93dc7edc35fa415 Mon Sep 17 00:00:00 2001 From: YarikRevich Date: Sat, 26 Aug 2023 01:12:37 +0200 Subject: [PATCH 006/134] feature: added more test cases --- zcnbridge/bridge.go | 21 ++++-------- zcnbridge/bridge_test.go | 70 ++++++++++++++++++++++++++++++++-------- zcnbridge/config.go | 22 +++++++------ zcnbridge/keystore.go | 40 +++++++++++++++++++++++ 4 files changed, 114 insertions(+), 39 deletions(-) diff --git a/zcnbridge/bridge.go b/zcnbridge/bridge.go index 9d3ff976a..232ac930b 100644 --- a/zcnbridge/bridge.go +++ b/zcnbridge/bridge.go @@ -6,7 +6,6 @@ import ( "fmt" "math/big" "os" - "path" "time" "github.com/0chain/gosdk/core/logger" @@ -23,7 +22,6 @@ import ( eth "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/accounts/keystore" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" @@ -59,22 +57,17 @@ var ( } ) -// getKeyStore reutrns key storage located in the given path. -func (b *BridgeClient) getKeyStore(path string) *keystore.KeyStore { - return keystore.NewKeyStore(path, keystore.StandardScryptN, keystore.StandardScryptP) -} - func (b *BridgeClient) CreateSignedTransactionFromKeyStore(client EthereumClient, gasLimitUnits uint64) *bind.TransactOpts { var ( signerAddress = common.HexToAddress(b.EthereumAddress) password = b.Password ) - ks := b.getKeyStore(path.Join(b.Homedir, EthereumWalletStorageDir)) + // ks := b.getKeyStore(path.Join(b.Homedir, EthereumWalletStorageDir)) signer := accounts.Account{ Address: signerAddress, } - signerAcc, err := ks.Find(signer) + signerAcc, err := b.KeyStore.Find(signer) if err != nil { Logger.Fatal(errors.Wrapf(err, "signer: %s", signerAddress.Hex())) } @@ -94,12 +87,12 @@ func (b *BridgeClient) CreateSignedTransactionFromKeyStore(client EthereumClient Logger.Fatal(err) } - err = ks.TimedUnlock(signer, password, time.Second*2) + err = b.KeyStore.TimedUnlock(signer, password, time.Second*2) if err != nil { Logger.Fatal(err) } - opts, err := bind.NewKeyStoreTransactorWithChainID(ks, signerAcc, chainID) + opts, err := bind.NewKeyStoreTransactorWithChainID(b.KeyStore.GetEthereumKeyStore(), signerAcc, chainID) if err != nil { Logger.Fatal(err) } @@ -294,18 +287,16 @@ func (b *BridgeClient) VerifyZCNTransaction(ctx context.Context, hash string) (t func (b *BridgeClient) SignWithEthereumChain(message string) ([]byte, error) { hash := crypto.Keccak256Hash([]byte(message)) - keyDir := path.Join(b.Homedir, EthereumWalletStorageDir) - ks := keystore.NewKeyStore(keyDir, keystore.StandardScryptN, keystore.StandardScryptP) signer := accounts.Account{ Address: common.HexToAddress(b.EthereumAddress), } - signerAcc, err := ks.Find(signer) + signerAcc, err := b.KeyStore.Find(signer) if err != nil { Logger.Fatal(err) } - signature, err := ks.SignHash(signerAcc, hash.Bytes()) + signature, err := b.KeyStore.SignHash(signerAcc, hash.Bytes()) if err != nil { return nil, err } diff --git a/zcnbridge/bridge_test.go b/zcnbridge/bridge_test.go index 5716f964f..45499ed8f 100644 --- a/zcnbridge/bridge_test.go +++ b/zcnbridge/bridge_test.go @@ -8,6 +8,7 @@ import ( "os" "strconv" "testing" + "time" sdkcommon "github.com/0chain/gosdk/core/common" "github.com/0chain/gosdk/zcnbridge/ethereum" @@ -20,6 +21,8 @@ import ( "github.com/0chain/gosdk/zcnbridge/zcnsc" "github.com/0chain/gosdk/zcncore" eth "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts" + "github.com/ethereum/go-ethereum/accounts/keystore" "github.com/ethereum/go-ethereum/common" "github.com/spf13/viper" "github.com/stretchr/testify/mock" @@ -86,6 +89,14 @@ func (tem *transactionProviderMock) Cleanup(callback func()) { callback() } +type keyStoreMock struct { + mock.TestingT +} + +func (ksm *keyStoreMock) Cleanup(callback func()) { + callback() +} + type authorizerConfigTarget struct { Fee sdkcommon.Balance `json:"fee"` } @@ -191,7 +202,7 @@ func getEthereumClient(t mock.TestingT) *bridgemocks.EthereumClient { return bridgemocks.NewEthereumClient(ðereumClientMock{t}) } -func getBridgeClient(ethereumClient EthereumClient, transactionProvider transaction.TransactionProvider) *BridgeClient { +func getBridgeClient(ethereumClient EthereumClient, transactionProvider transaction.TransactionProvider, keyStore KeyStore) *BridgeClient { cfg := viper.New() tempConfigFile, err := os.CreateTemp(".", "config.yaml") @@ -211,7 +222,7 @@ func getBridgeClient(ethereumClient EthereumClient, transactionProvider transact cfg.SetDefault("bridge.gas_limit", 0) cfg.SetDefault("bridge.consensus_threshold", 0) - return createBridgeClient(cfg, ethereumClient, transactionProvider) + return createBridgeClient(cfg, ethereumClient, transactionProvider, keyStore) } func prepareEthereumClientGeneralMockCalls(ethereumClient *mock.Mock) { @@ -227,16 +238,37 @@ func getTransaction(t mock.TestingT) *transactionmocks.Transaction { } func prepareTransactionGeneralMockCalls(transaction *mock.Mock) { - transaction.On("ExecuteSmartContract", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(zcnTxnID, nil) - transaction.On("Verify").Return(nil) + transaction.On("ExecuteSmartContract", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(zcnTxnID, nil) + transaction.On("Verify", mock.Anything).Return(nil) } func getTransactionProvider(t mock.TestingT) *transactionmocks.TransactionProvider { return transactionmocks.NewTransactionProvider(&transactionProviderMock{t}) } -func prepareTransactionProviderGeneralMockCalls(transactionProvider, transaction *mock.Mock) { - transactionProvider.On("NewTransactionEntity", mock.Anything).Return(transaction) +func prepareTransactionProviderGeneralMockCalls(transactionProvider *mock.Mock, transaction *transactionmocks.Transaction) { + transactionProvider.On("NewTransactionEntity", mock.Anything).Return(transaction, nil) +} + +func getKeyStore(t mock.TestingT) *bridgemocks.KeyStore { + return bridgemocks.NewKeyStore(&keyStoreMock{t}) +} + +func prepareKeyStoreGeneralMockCalls(keyStore *bridgemocks.KeyStore) { + keyStore.On("Find", mock.Anything).Return(accounts.Account{ + Address: common.HexToAddress(ethereumAddress), + }, nil) + keyStore.On("TimedUnlock", mock.Anything, mock.Anything, mock.Anything).Return(nil) + keyStore.On("SignHash", mock.Anything, mock.Anything).Return([]byte(ethereumAddress), nil) + + keyStoreDir, err := os.MkdirTemp(".", "keyStore") + if err != nil { + log.Fatalln(err) + } + + defer os.Remove(keyStoreDir) + + keyStore.On("GetEthereumKeyStore").Return(keystore.NewKeyStore(keyStoreDir, keystore.StandardScryptN, keystore.StandardScryptP)) } func Test_ZCNBridge(t *testing.T) { @@ -247,9 +279,12 @@ func Test_ZCNBridge(t *testing.T) { prepareTransactionGeneralMockCalls(&transaction.Mock) transactionProvider := getTransactionProvider(t) - prepareTransactionProviderGeneralMockCalls(&transactionProvider.Mock, &transaction.Mock) + prepareTransactionProviderGeneralMockCalls(&transactionProvider.Mock, transaction) - bridgeClient := getBridgeClient(ethereumClient, transactionProvider) + keyStore := getKeyStore(t) + prepareKeyStoreGeneralMockCalls(keyStore) + + bridgeClient := getBridgeClient(ethereumClient, transactionProvider, keyStore) t.Run("should update authorizer config.", func(t *testing.T) { source := &authorizerNodeSource{ @@ -310,7 +345,6 @@ func Test_ZCNBridge(t *testing.T) { Data: pack, }, )) - }) t.Run("should check configuration formating in BurnWZCN", func(t *testing.T) { @@ -350,14 +384,14 @@ func Test_ZCNBridge(t *testing.T) { _, err := bridgeClient.MintZCN(context.Background(), payload) require.NoError(t, err) - require.True(t, transactionProvider.AssertCalled( + require.True(t, transaction.AssertCalled( t, "ExecuteSmartContract", context.Background(), wallet.ZCNSCSmartContractAddress, wallet.MintFunc, payload, - 0, + uint64(0), )) }) @@ -365,7 +399,7 @@ func Test_ZCNBridge(t *testing.T) { _, err := bridgeClient.BurnZCN(context.Background(), amount, txnFee) require.NoError(t, err) - require.True(t, transactionProvider.AssertCalled( + require.True(t, transaction.AssertCalled( t, "ExecuteSmartContract", context.Background(), @@ -374,7 +408,7 @@ func Test_ZCNBridge(t *testing.T) { zcnsc.BurnPayload{ EthereumAddress: ethereumAddress, }, - amount, + uint64(amount), )) }) @@ -414,6 +448,14 @@ func Test_ZCNBridge(t *testing.T) { context.Background(), common.HexToAddress(ethereumAddress))) - // TODO: check somehow used Password + require.True(t, keyStore.AssertCalled( + t, + "TimedUnlock", + accounts.Account{ + Address: common.HexToAddress(ethereumAddress), + }, + password, + time.Second*2, + )) }) } diff --git a/zcnbridge/config.go b/zcnbridge/config.go index 297576575..7b9ce8252 100644 --- a/zcnbridge/config.go +++ b/zcnbridge/config.go @@ -29,6 +29,7 @@ type BridgeSDKConfig struct { } type BridgeClient struct { + KeyStore transaction.TransactionProvider EthereumClient @@ -36,8 +37,7 @@ type BridgeClient struct { TokenAddress, AuthorizersAddress, EthereumAddress, - Password, - Homedir string + Password string ConsensusThreshold float64 GasLimit uint64 @@ -52,12 +52,7 @@ type EthereumClient interface { // createBridgeClient initializes new bridge client with the help of the given // Ethereum JSON-RPC client and locally-defined confiruration. -func createBridgeClient(cfg *viper.Viper, ethereumClient EthereumClient, transactionProvider transaction.TransactionProvider) *BridgeClient { - homedir := path.Dir(cfg.ConfigFileUsed()) - if homedir == "" { - log.Logger.Fatal("homedir is required") - } - +func createBridgeClient(cfg *viper.Viper, ethereumClient EthereumClient, transactionProvider transaction.TransactionProvider, keyStore KeyStore) *BridgeClient { return &BridgeClient{ BridgeAddress: cfg.GetString("bridge.bridge_address"), TokenAddress: cfg.GetString("bridge.token_address"), @@ -66,9 +61,9 @@ func createBridgeClient(cfg *viper.Viper, ethereumClient EthereumClient, transac Password: cfg.GetString("bridge.password"), GasLimit: cfg.GetUint64("bridge.gas_limit"), ConsensusThreshold: cfg.GetFloat64("bridge.consensus_threshold"), - Homedir: homedir, EthereumClient: ethereumClient, TransactionProvider: transactionProvider, + KeyStore: keyStore, } } @@ -86,7 +81,14 @@ func SetupBridgeClientSDK(cfg *BridgeSDKConfig) *BridgeClient { transactionProvider := transaction.NewTransactionProvider() - bridgeClient := createBridgeClient(chainCfg, ethereumClient, transactionProvider) + homedir := path.Dir(chainCfg.ConfigFileUsed()) + if homedir == "" { + log.Logger.Fatal("err happened during home directory retrieval") + } + + ks := NewKeyStore(path.Join(homedir, EthereumWalletStorageDir)) + + bridgeClient := createBridgeClient(chainCfg, ethereumClient, transactionProvider, ks) return bridgeClient } diff --git a/zcnbridge/keystore.go b/zcnbridge/keystore.go index 6fffbc821..0beaf30dc 100644 --- a/zcnbridge/keystore.go +++ b/zcnbridge/keystore.go @@ -3,6 +3,7 @@ package zcnbridge import ( "fmt" "path" + "time" hdw "github.com/0chain/gosdk/zcncore/ethhdwallet" "github.com/ethereum/go-ethereum/accounts" @@ -11,6 +12,45 @@ import ( "github.com/pkg/errors" ) +// KeyStore is a wrapper, which exposes Ethereum KeyStore methods used by DEX bridge. +type KeyStore interface { + Find(accounts.Account) (accounts.Account, error) + TimedUnlock(accounts.Account, string, time.Duration) error + SignHash(account accounts.Account, hash []byte) ([]byte, error) + GetEthereumKeyStore() *keystore.KeyStore +} + +type keyStore struct { + ks *keystore.KeyStore +} + +// Creates new KeyStore wrapper instance +func NewKeyStore(path string) KeyStore { + return &keyStore{ + ks: keystore.NewKeyStore(path, keystore.StandardScryptN, keystore.StandardScryptP), + } +} + +// TimedUnlock forwards request to Ethereum KeyStore TimedUnlock method +func (k *keyStore) TimedUnlock(account accounts.Account, passPhrase string, timeout time.Duration) error { + return k.ks.TimedUnlock(account, passPhrase, timeout) +} + +// Find forwards request to Ethereum KeyStore Find method +func (k *keyStore) Find(account accounts.Account) (accounts.Account, error) { + return k.ks.Find(account) +} + +// SignHash forwards request to Ethereum KeyStore SignHash method +func (k *keyStore) SignHash(account accounts.Account, hash []byte) ([]byte, error) { + return k.ks.SignHash(account, hash) +} + +// GetEthereumKeyStore returns Ethereum KeyStore instance +func (k *keyStore) GetEthereumKeyStore() *keystore.KeyStore { + return k.ks +} + // ListStorageAccounts List available accounts func ListStorageAccounts(homedir string) []common.Address { keyDir := path.Join(homedir, EthereumWalletStorageDir) From 8f71d486cfc9d9d1f58e323f229e208887db2151 Mon Sep 17 00:00:00 2001 From: YarikRevich Date: Sat, 26 Aug 2023 12:17:05 +0200 Subject: [PATCH 007/134] feature: added more test cases --- zcnbridge/bridge.go | 8 +++--- zcnbridge/bridge_test.go | 62 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 65 insertions(+), 5 deletions(-) diff --git a/zcnbridge/bridge.go b/zcnbridge/bridge.go index 232ac930b..e62b6ab37 100644 --- a/zcnbridge/bridge.go +++ b/zcnbridge/bridge.go @@ -298,11 +298,11 @@ func (b *BridgeClient) SignWithEthereumChain(message string) ([]byte, error) { signature, err := b.KeyStore.SignHash(signerAcc, hash.Bytes()) if err != nil { - return nil, err - } - if err != nil { - return []byte{}, errors.Wrap(err, "failed to sign the message") + // return nil, err } + // if err != nil { + // return []byte{}, errors.Wrap(err, "failed to sign the message") + // } return signature, nil } diff --git a/zcnbridge/bridge_test.go b/zcnbridge/bridge_test.go index 45499ed8f..6ed720c7f 100644 --- a/zcnbridge/bridge_test.go +++ b/zcnbridge/bridge_test.go @@ -12,6 +12,7 @@ import ( sdkcommon "github.com/0chain/gosdk/core/common" "github.com/0chain/gosdk/zcnbridge/ethereum" + "github.com/0chain/gosdk/zcnbridge/ethereum/authorizers" binding "github.com/0chain/gosdk/zcnbridge/ethereum/bridge" "github.com/0chain/gosdk/zcnbridge/ethereum/erc20" bridgemocks "github.com/0chain/gosdk/zcnbridge/mocks" @@ -35,6 +36,8 @@ const ( ethereumAddress = "0xD8c9156e782C68EE671C09b6b92de76C97948432" password = "\"02289b9\"" + authorizerDelegatedAddress = "0xa149B58b7e1390D152383BB03dBc79B390F648e2" + bridgeAddress = "0x7bbbEa24ac1751317D7669f05558632c4A9113D7" tokenAddress = "0x2ec8F26ccC678c9faF0Df20208aEE3AF776160CD" authorizerAddress = "0xEAe8229c0E457efBA1A1769e7F8c20110fF68E61" @@ -268,7 +271,14 @@ func prepareKeyStoreGeneralMockCalls(keyStore *bridgemocks.KeyStore) { defer os.Remove(keyStoreDir) - keyStore.On("GetEthereumKeyStore").Return(keystore.NewKeyStore(keyStoreDir, keystore.StandardScryptN, keystore.StandardScryptP)) + ks := keystore.NewKeyStore(keyStoreDir, keystore.StandardScryptN, keystore.StandardScryptP) + + // _, err = ImportAccount(keyStoreDir, ethereumMnemonic, password) + // if err != nil { + // log.Fatalln(err) + // } + + keyStore.On("GetEthereumKeyStore").Return(ks) } func Test_ZCNBridge(t *testing.T) { @@ -412,6 +422,56 @@ func Test_ZCNBridge(t *testing.T) { )) }) + t.Run("should check configuration used by AddEthereumAuthorizer", func(t *testing.T) { + _, err := bridgeClient.AddEthereumAuthorizer(context.Background(), common.HexToAddress(authorizerDelegatedAddress)) + require.NoError(t, err) + + to := common.HexToAddress(bridgeAddress) + fromAddress := common.HexToAddress(ethereumAddress) + + abi, err := authorizers.AuthorizersMetaData.GetAbi() + require.NoError(t, err) + + pack, err := abi.Pack("addAuthorizers", common.HexToAddress(authorizerDelegatedAddress)) + require.NoError(t, err) + + require.True(t, ethereumClient.AssertCalled( + t, + "EstimateGas", + context.Background(), + eth.CallMsg{ + To: &to, + From: fromAddress, + Data: pack, + }, + )) + }) + + t.Run("should check configuration used by RemoveAuthorizer", func(t *testing.T) { + _, err := bridgeClient.RemoveEthereumAuthorizer(context.Background(), common.HexToAddress(authorizerDelegatedAddress)) + require.NoError(t, err) + + to := common.HexToAddress(bridgeAddress) + fromAddress := common.HexToAddress(ethereumAddress) + + abi, err := authorizers.AuthorizersMetaData.GetAbi() + require.NoError(t, err) + + pack, err := abi.Pack("removeAuthorizers", common.HexToAddress(authorizerDelegatedAddress)) + require.NoError(t, err) + + require.True(t, ethereumClient.AssertCalled( + t, + "EstimateGas", + context.Background(), + eth.CallMsg{ + To: &to, + From: fromAddress, + Data: pack, + }, + )) + }) + t.Run("should check configuration used by IncreaseBurnerAllowance", func(t *testing.T) { _, err := bridgeClient.IncreaseBurnerAllowance(context.Background(), amount) require.NoError(t, err) From 10c024db3ebac876348f437663038acf6b9c7f89 Mon Sep 17 00:00:00 2001 From: YarikRevich Date: Sat, 26 Aug 2023 12:17:58 +0200 Subject: [PATCH 008/134] fix: fixed bugs --- wasmsdk/bridge.go | 1 - 1 file changed, 1 deletion(-) diff --git a/wasmsdk/bridge.go b/wasmsdk/bridge.go index 27a625769..d0d00178a 100644 --- a/wasmsdk/bridge.go +++ b/wasmsdk/bridge.go @@ -40,7 +40,6 @@ func initBridge( AuthorizersAddress: authorizersAddress, TokenAddress: tokenAddress, Password: "", - Homedir: ".", GasLimit: gasLimit, ConsensusThreshold: consensusThreshold, EthereumClient: ethereumClient, From 0c5b2c879de70acf721c1b7bc46a15d2492c612d Mon Sep 17 00:00:00 2001 From: YarikRevich Date: Sat, 26 Aug 2023 13:41:15 +0200 Subject: [PATCH 009/134] fix: fixed bugs --- zcnbridge/bridge.go | 9 +++---- zcnbridge/bridge_test.go | 51 +++++++++++++++++++++++----------------- 2 files changed, 35 insertions(+), 25 deletions(-) diff --git a/zcnbridge/bridge.go b/zcnbridge/bridge.go index e62b6ab37..a69d3c250 100644 --- a/zcnbridge/bridge.go +++ b/zcnbridge/bridge.go @@ -298,11 +298,12 @@ func (b *BridgeClient) SignWithEthereumChain(message string) ([]byte, error) { signature, err := b.KeyStore.SignHash(signerAcc, hash.Bytes()) if err != nil { - // return nil, err + return nil, err + } + + if err != nil { + return []byte{}, errors.Wrap(err, "failed to sign the message") } - // if err != nil { - // return []byte{}, errors.Wrap(err, "failed to sign the message") - // } return signature, nil } diff --git a/zcnbridge/bridge_test.go b/zcnbridge/bridge_test.go index 6ed720c7f..22a9e6229 100644 --- a/zcnbridge/bridge_test.go +++ b/zcnbridge/bridge_test.go @@ -6,6 +6,7 @@ import ( "log" "math/big" "os" + "path" "strconv" "testing" "time" @@ -34,13 +35,13 @@ const ( ethereumMnemonic = "symbol alley celery diesel donate moral almost opinion achieve since diamond page" ethereumAddress = "0xD8c9156e782C68EE671C09b6b92de76C97948432" - password = "\"02289b9\"" + password = "02289b9" authorizerDelegatedAddress = "0xa149B58b7e1390D152383BB03dBc79B390F648e2" - bridgeAddress = "0x7bbbEa24ac1751317D7669f05558632c4A9113D7" - tokenAddress = "0x2ec8F26ccC678c9faF0Df20208aEE3AF776160CD" - authorizerAddress = "0xEAe8229c0E457efBA1A1769e7F8c20110fF68E61" + bridgeAddress = "0x7bbbEa24ac1751317D7669f05558632c4A9113D7" + tokenAddress = "0x2ec8F26ccC678c9faF0Df20208aEE3AF776160CD" + authorizersAddress = "0xEAe8229c0E457efBA1A1769e7F8c20110fF68E61" zcnTxnID = "b26abeb31fcee5d2e75b26717722938a06fa5ce4a5b5e68ddad68357432caace" amount = 1e10 @@ -52,6 +53,10 @@ const ( clientId = "d6e9b3222434faa043c683d1a939d6a0fa2818c4d56e794974d64a32005330d3" ) +var ( + testKeyStoreLocation = path.Join(".", EthereumWalletStorageDir) +) + var ( ethereumSignatures = []*ethereum.AuthorizerSignature{ { @@ -219,7 +224,7 @@ func getBridgeClient(ethereumClient EthereumClient, transactionProvider transact cfg.SetDefault("bridge.bridge_address", bridgeAddress) cfg.SetDefault("bridge.token_address", tokenAddress) - cfg.SetDefault("bridge.authorizers_address", authorizerAddress) + cfg.SetDefault("bridge.authorizers_address", authorizersAddress) cfg.SetDefault("bridge.ethereum_address", ethereumAddress) cfg.SetDefault("bridge.password", password) cfg.SetDefault("bridge.gas_limit", 0) @@ -258,25 +263,23 @@ func getKeyStore(t mock.TestingT) *bridgemocks.KeyStore { } func prepareKeyStoreGeneralMockCalls(keyStore *bridgemocks.KeyStore) { - keyStore.On("Find", mock.Anything).Return(accounts.Account{ - Address: common.HexToAddress(ethereumAddress), - }, nil) - keyStore.On("TimedUnlock", mock.Anything, mock.Anything, mock.Anything).Return(nil) - keyStore.On("SignHash", mock.Anything, mock.Anything).Return([]byte(ethereumAddress), nil) + ks := keystore.NewKeyStore(testKeyStoreLocation, keystore.StandardScryptN, keystore.StandardScryptP) - keyStoreDir, err := os.MkdirTemp(".", "keyStore") + _, err := ImportAccount(".", ethereumMnemonic, password) if err != nil { log.Fatalln(err) } - defer os.Remove(keyStoreDir) - - ks := keystore.NewKeyStore(keyStoreDir, keystore.StandardScryptN, keystore.StandardScryptP) - - // _, err = ImportAccount(keyStoreDir, ethereumMnemonic, password) - // if err != nil { - // log.Fatalln(err) - // } + keyStore.On("Find", mock.Anything).Return(accounts.Account{Address: common.HexToAddress(ethereumAddress)}, nil) + keyStore.On("TimedUnlock", mock.Anything, mock.Anything, mock.Anything).Run( + func(args mock.Arguments) { + err = ks.TimedUnlock(args.Get(0).(accounts.Account), args.Get(1).(string), args.Get(2).(time.Duration)) + if err != nil { + log.Fatalln(err) + } + }, + ).Return(nil) + keyStore.On("SignHash", mock.Anything, mock.Anything).Return([]byte(ethereumAddress), nil) keyStore.On("GetEthereumKeyStore").Return(ks) } @@ -296,6 +299,12 @@ func Test_ZCNBridge(t *testing.T) { bridgeClient := getBridgeClient(ethereumClient, transactionProvider, keyStore) + t.Cleanup(func() { + if err := os.Remove(testKeyStoreLocation); err != nil { + log.Fatalln(err) + } + }) + t.Run("should update authorizer config.", func(t *testing.T) { source := &authorizerNodeSource{ ID: "12345678", @@ -426,7 +435,7 @@ func Test_ZCNBridge(t *testing.T) { _, err := bridgeClient.AddEthereumAuthorizer(context.Background(), common.HexToAddress(authorizerDelegatedAddress)) require.NoError(t, err) - to := common.HexToAddress(bridgeAddress) + to := common.HexToAddress(authorizersAddress) fromAddress := common.HexToAddress(ethereumAddress) abi, err := authorizers.AuthorizersMetaData.GetAbi() @@ -451,7 +460,7 @@ func Test_ZCNBridge(t *testing.T) { _, err := bridgeClient.RemoveEthereumAuthorizer(context.Background(), common.HexToAddress(authorizerDelegatedAddress)) require.NoError(t, err) - to := common.HexToAddress(bridgeAddress) + to := common.HexToAddress(authorizersAddress) fromAddress := common.HexToAddress(ethereumAddress) abi, err := authorizers.AuthorizersMetaData.GetAbi() From e3c3b5b6ed0f4dfbebf4a2d19ffac7bf74abe65c Mon Sep 17 00:00:00 2001 From: YarikRevich Date: Sat, 26 Aug 2023 13:46:08 +0200 Subject: [PATCH 010/134] fix: fixed bugs --- zcnbridge/bridge_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zcnbridge/bridge_test.go b/zcnbridge/bridge_test.go index 22a9e6229..2bc31878a 100644 --- a/zcnbridge/bridge_test.go +++ b/zcnbridge/bridge_test.go @@ -300,7 +300,7 @@ func Test_ZCNBridge(t *testing.T) { bridgeClient := getBridgeClient(ethereumClient, transactionProvider, keyStore) t.Cleanup(func() { - if err := os.Remove(testKeyStoreLocation); err != nil { + if err := os.RemoveAll(testKeyStoreLocation); err != nil { log.Fatalln(err) } }) From 5abf1a49c2aafc0ad8680f13dc225c609b60df53 Mon Sep 17 00:00:00 2001 From: YarikRevich Date: Sat, 26 Aug 2023 14:15:57 +0200 Subject: [PATCH 011/134] feature: added mocks --- zcnbridge/mocks/EthereumClient.go | 332 ++++++++++++++++++ zcnbridge/mocks/JobResult.go | 74 ++++ zcnbridge/mocks/KeyStore.go | 112 ++++++ zcnbridge/mocks/Transaction.go | 135 +++++++ .../mocks/TransactionCallbackAwaitable.go | 74 ++++ zcnbridge/mocks/TransactionProvider.go | 54 +++ zcnbridge/transaction/mocks/Transaction.go | 135 +++++++ .../mocks/TransactionCallbackAwaitable.go | 74 ++++ .../transaction/mocks/TransactionProvider.go | 54 +++ 9 files changed, 1044 insertions(+) create mode 100644 zcnbridge/mocks/EthereumClient.go create mode 100644 zcnbridge/mocks/JobResult.go create mode 100644 zcnbridge/mocks/KeyStore.go create mode 100644 zcnbridge/mocks/Transaction.go create mode 100644 zcnbridge/mocks/TransactionCallbackAwaitable.go create mode 100644 zcnbridge/mocks/TransactionProvider.go create mode 100644 zcnbridge/transaction/mocks/Transaction.go create mode 100644 zcnbridge/transaction/mocks/TransactionCallbackAwaitable.go create mode 100644 zcnbridge/transaction/mocks/TransactionProvider.go diff --git a/zcnbridge/mocks/EthereumClient.go b/zcnbridge/mocks/EthereumClient.go new file mode 100644 index 000000000..1169cfa92 --- /dev/null +++ b/zcnbridge/mocks/EthereumClient.go @@ -0,0 +1,332 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import ( + context "context" + big "math/big" + + common "github.com/ethereum/go-ethereum/common" + + ethereum "github.com/ethereum/go-ethereum" + + mock "github.com/stretchr/testify/mock" + + types "github.com/ethereum/go-ethereum/core/types" +) + +// EthereumClient is an autogenerated mock type for the EthereumClient type +type EthereumClient struct { + mock.Mock +} + +// CallContract provides a mock function with given fields: ctx, call, blockNumber +func (_m *EthereumClient) CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) { + ret := _m.Called(ctx, call, blockNumber) + + var r0 []byte + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, ethereum.CallMsg, *big.Int) ([]byte, error)); ok { + return rf(ctx, call, blockNumber) + } + if rf, ok := ret.Get(0).(func(context.Context, ethereum.CallMsg, *big.Int) []byte); ok { + r0 = rf(ctx, call, blockNumber) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]byte) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, ethereum.CallMsg, *big.Int) error); ok { + r1 = rf(ctx, call, blockNumber) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// ChainID provides a mock function with given fields: ctx +func (_m *EthereumClient) ChainID(ctx context.Context) (*big.Int, error) { + ret := _m.Called(ctx) + + var r0 *big.Int + var r1 error + if rf, ok := ret.Get(0).(func(context.Context) (*big.Int, error)); ok { + return rf(ctx) + } + if rf, ok := ret.Get(0).(func(context.Context) *big.Int); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*big.Int) + } + } + + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(ctx) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// CodeAt provides a mock function with given fields: ctx, contract, blockNumber +func (_m *EthereumClient) CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error) { + ret := _m.Called(ctx, contract, blockNumber) + + var r0 []byte + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, common.Address, *big.Int) ([]byte, error)); ok { + return rf(ctx, contract, blockNumber) + } + if rf, ok := ret.Get(0).(func(context.Context, common.Address, *big.Int) []byte); ok { + r0 = rf(ctx, contract, blockNumber) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]byte) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, common.Address, *big.Int) error); ok { + r1 = rf(ctx, contract, blockNumber) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// EstimateGas provides a mock function with given fields: ctx, call +func (_m *EthereumClient) EstimateGas(ctx context.Context, call ethereum.CallMsg) (uint64, error) { + ret := _m.Called(ctx, call) + + var r0 uint64 + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, ethereum.CallMsg) (uint64, error)); ok { + return rf(ctx, call) + } + if rf, ok := ret.Get(0).(func(context.Context, ethereum.CallMsg) uint64); ok { + r0 = rf(ctx, call) + } else { + r0 = ret.Get(0).(uint64) + } + + if rf, ok := ret.Get(1).(func(context.Context, ethereum.CallMsg) error); ok { + r1 = rf(ctx, call) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// FilterLogs provides a mock function with given fields: ctx, query +func (_m *EthereumClient) FilterLogs(ctx context.Context, query ethereum.FilterQuery) ([]types.Log, error) { + ret := _m.Called(ctx, query) + + var r0 []types.Log + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, ethereum.FilterQuery) ([]types.Log, error)); ok { + return rf(ctx, query) + } + if rf, ok := ret.Get(0).(func(context.Context, ethereum.FilterQuery) []types.Log); ok { + r0 = rf(ctx, query) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]types.Log) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, ethereum.FilterQuery) error); ok { + r1 = rf(ctx, query) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// HeaderByNumber provides a mock function with given fields: ctx, number +func (_m *EthereumClient) HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) { + ret := _m.Called(ctx, number) + + var r0 *types.Header + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *big.Int) (*types.Header, error)); ok { + return rf(ctx, number) + } + if rf, ok := ret.Get(0).(func(context.Context, *big.Int) *types.Header); ok { + r0 = rf(ctx, number) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.Header) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *big.Int) error); ok { + r1 = rf(ctx, number) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// PendingCodeAt provides a mock function with given fields: ctx, account +func (_m *EthereumClient) PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error) { + ret := _m.Called(ctx, account) + + var r0 []byte + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, common.Address) ([]byte, error)); ok { + return rf(ctx, account) + } + if rf, ok := ret.Get(0).(func(context.Context, common.Address) []byte); ok { + r0 = rf(ctx, account) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]byte) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, common.Address) error); ok { + r1 = rf(ctx, account) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// PendingNonceAt provides a mock function with given fields: ctx, account +func (_m *EthereumClient) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) { + ret := _m.Called(ctx, account) + + var r0 uint64 + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, common.Address) (uint64, error)); ok { + return rf(ctx, account) + } + if rf, ok := ret.Get(0).(func(context.Context, common.Address) uint64); ok { + r0 = rf(ctx, account) + } else { + r0 = ret.Get(0).(uint64) + } + + if rf, ok := ret.Get(1).(func(context.Context, common.Address) error); ok { + r1 = rf(ctx, account) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// SendTransaction provides a mock function with given fields: ctx, tx +func (_m *EthereumClient) SendTransaction(ctx context.Context, tx *types.Transaction) error { + ret := _m.Called(ctx, tx) + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context, *types.Transaction) error); ok { + r0 = rf(ctx, tx) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// SubscribeFilterLogs provides a mock function with given fields: ctx, query, ch +func (_m *EthereumClient) SubscribeFilterLogs(ctx context.Context, query ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) { + ret := _m.Called(ctx, query, ch) + + var r0 ethereum.Subscription + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, ethereum.FilterQuery, chan<- types.Log) (ethereum.Subscription, error)); ok { + return rf(ctx, query, ch) + } + if rf, ok := ret.Get(0).(func(context.Context, ethereum.FilterQuery, chan<- types.Log) ethereum.Subscription); ok { + r0 = rf(ctx, query, ch) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(ethereum.Subscription) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, ethereum.FilterQuery, chan<- types.Log) error); ok { + r1 = rf(ctx, query, ch) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// SuggestGasPrice provides a mock function with given fields: ctx +func (_m *EthereumClient) SuggestGasPrice(ctx context.Context) (*big.Int, error) { + ret := _m.Called(ctx) + + var r0 *big.Int + var r1 error + if rf, ok := ret.Get(0).(func(context.Context) (*big.Int, error)); ok { + return rf(ctx) + } + if rf, ok := ret.Get(0).(func(context.Context) *big.Int); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*big.Int) + } + } + + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(ctx) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// SuggestGasTipCap provides a mock function with given fields: ctx +func (_m *EthereumClient) SuggestGasTipCap(ctx context.Context) (*big.Int, error) { + ret := _m.Called(ctx) + + var r0 *big.Int + var r1 error + if rf, ok := ret.Get(0).(func(context.Context) (*big.Int, error)); ok { + return rf(ctx) + } + if rf, ok := ret.Get(0).(func(context.Context) *big.Int); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*big.Int) + } + } + + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(ctx) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +type mockConstructorTestingTNewEthereumClient interface { + mock.TestingT + Cleanup(func()) +} + +// NewEthereumClient creates a new instance of EthereumClient. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewEthereumClient(t mockConstructorTestingTNewEthereumClient) *EthereumClient { + mock := &EthereumClient{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zcnbridge/mocks/JobResult.go b/zcnbridge/mocks/JobResult.go new file mode 100644 index 000000000..78487e1e3 --- /dev/null +++ b/zcnbridge/mocks/JobResult.go @@ -0,0 +1,74 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import mock "github.com/stretchr/testify/mock" + +// JobResult is an autogenerated mock type for the JobResult type +type JobResult struct { + mock.Mock +} + +// Data provides a mock function with given fields: +func (_m *JobResult) Data() interface{} { + ret := _m.Called() + + var r0 interface{} + if rf, ok := ret.Get(0).(func() interface{}); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(interface{}) + } + } + + return r0 +} + +// Error provides a mock function with given fields: +func (_m *JobResult) Error() error { + ret := _m.Called() + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// GetAuthorizerID provides a mock function with given fields: +func (_m *JobResult) GetAuthorizerID() string { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// SetAuthorizerID provides a mock function with given fields: ID +func (_m *JobResult) SetAuthorizerID(ID string) { + _m.Called(ID) +} + +type mockConstructorTestingTNewJobResult interface { + mock.TestingT + Cleanup(func()) +} + +// NewJobResult creates a new instance of JobResult. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewJobResult(t mockConstructorTestingTNewJobResult) *JobResult { + mock := &JobResult{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zcnbridge/mocks/KeyStore.go b/zcnbridge/mocks/KeyStore.go new file mode 100644 index 000000000..be25a121c --- /dev/null +++ b/zcnbridge/mocks/KeyStore.go @@ -0,0 +1,112 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import ( + accounts "github.com/ethereum/go-ethereum/accounts" + keystore "github.com/ethereum/go-ethereum/accounts/keystore" + + mock "github.com/stretchr/testify/mock" + + time "time" +) + +// KeyStore is an autogenerated mock type for the KeyStore type +type KeyStore struct { + mock.Mock +} + +// Find provides a mock function with given fields: _a0 +func (_m *KeyStore) Find(_a0 accounts.Account) (accounts.Account, error) { + ret := _m.Called(_a0) + + var r0 accounts.Account + var r1 error + if rf, ok := ret.Get(0).(func(accounts.Account) (accounts.Account, error)); ok { + return rf(_a0) + } + if rf, ok := ret.Get(0).(func(accounts.Account) accounts.Account); ok { + r0 = rf(_a0) + } else { + r0 = ret.Get(0).(accounts.Account) + } + + if rf, ok := ret.Get(1).(func(accounts.Account) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetEthereumKeyStore provides a mock function with given fields: +func (_m *KeyStore) GetEthereumKeyStore() *keystore.KeyStore { + ret := _m.Called() + + var r0 *keystore.KeyStore + if rf, ok := ret.Get(0).(func() *keystore.KeyStore); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*keystore.KeyStore) + } + } + + return r0 +} + +// SignHash provides a mock function with given fields: account, hash +func (_m *KeyStore) SignHash(account accounts.Account, hash []byte) ([]byte, error) { + ret := _m.Called(account, hash) + + var r0 []byte + var r1 error + if rf, ok := ret.Get(0).(func(accounts.Account, []byte) ([]byte, error)); ok { + return rf(account, hash) + } + if rf, ok := ret.Get(0).(func(accounts.Account, []byte) []byte); ok { + r0 = rf(account, hash) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]byte) + } + } + + if rf, ok := ret.Get(1).(func(accounts.Account, []byte) error); ok { + r1 = rf(account, hash) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// TimedUnlock provides a mock function with given fields: _a0, _a1, _a2 +func (_m *KeyStore) TimedUnlock(_a0 accounts.Account, _a1 string, _a2 time.Duration) error { + ret := _m.Called(_a0, _a1, _a2) + + var r0 error + if rf, ok := ret.Get(0).(func(accounts.Account, string, time.Duration) error); ok { + r0 = rf(_a0, _a1, _a2) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +type mockConstructorTestingTNewKeyStore interface { + mock.TestingT + Cleanup(func()) +} + +// NewKeyStore creates a new instance of KeyStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewKeyStore(t mockConstructorTestingTNewKeyStore) *KeyStore { + mock := &KeyStore{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zcnbridge/mocks/Transaction.go b/zcnbridge/mocks/Transaction.go new file mode 100644 index 000000000..b9a833470 --- /dev/null +++ b/zcnbridge/mocks/Transaction.go @@ -0,0 +1,135 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import ( + context "context" + + transaction "github.com/0chain/gosdk/zcnbridge/transaction" + mock "github.com/stretchr/testify/mock" + + zcncore "github.com/0chain/gosdk/zcncore" +) + +// Transaction is an autogenerated mock type for the Transaction type +type Transaction struct { + mock.Mock +} + +// ExecuteSmartContract provides a mock function with given fields: ctx, address, funcName, input, val +func (_m *Transaction) ExecuteSmartContract(ctx context.Context, address string, funcName string, input interface{}, val uint64) (string, error) { + ret := _m.Called(ctx, address, funcName, input, val) + + var r0 string + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, string, string, interface{}, uint64) (string, error)); ok { + return rf(ctx, address, funcName, input, val) + } + if rf, ok := ret.Get(0).(func(context.Context, string, string, interface{}, uint64) string); ok { + r0 = rf(ctx, address, funcName, input, val) + } else { + r0 = ret.Get(0).(string) + } + + if rf, ok := ret.Get(1).(func(context.Context, string, string, interface{}, uint64) error); ok { + r1 = rf(ctx, address, funcName, input, val) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetCallback provides a mock function with given fields: +func (_m *Transaction) GetCallback() transaction.TransactionCallbackAwaitable { + ret := _m.Called() + + var r0 transaction.TransactionCallbackAwaitable + if rf, ok := ret.Get(0).(func() transaction.TransactionCallbackAwaitable); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(transaction.TransactionCallbackAwaitable) + } + } + + return r0 +} + +// GetHash provides a mock function with given fields: +func (_m *Transaction) GetHash() string { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// GetScheme provides a mock function with given fields: +func (_m *Transaction) GetScheme() zcncore.TransactionScheme { + ret := _m.Called() + + var r0 zcncore.TransactionScheme + if rf, ok := ret.Get(0).(func() zcncore.TransactionScheme); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(zcncore.TransactionScheme) + } + } + + return r0 +} + +// GetTransactionOutput provides a mock function with given fields: +func (_m *Transaction) GetTransactionOutput() string { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// SetHash provides a mock function with given fields: _a0 +func (_m *Transaction) SetHash(_a0 string) { + _m.Called(_a0) +} + +// Verify provides a mock function with given fields: ctx +func (_m *Transaction) Verify(ctx context.Context) error { + ret := _m.Called(ctx) + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context) error); ok { + r0 = rf(ctx) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +type mockConstructorTestingTNewTransaction interface { + mock.TestingT + Cleanup(func()) +} + +// NewTransaction creates a new instance of Transaction. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewTransaction(t mockConstructorTestingTNewTransaction) *Transaction { + mock := &Transaction{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zcnbridge/mocks/TransactionCallbackAwaitable.go b/zcnbridge/mocks/TransactionCallbackAwaitable.go new file mode 100644 index 000000000..299573252 --- /dev/null +++ b/zcnbridge/mocks/TransactionCallbackAwaitable.go @@ -0,0 +1,74 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import ( + context "context" + + mock "github.com/stretchr/testify/mock" + + zcncore "github.com/0chain/gosdk/zcncore" +) + +// TransactionCallbackAwaitable is an autogenerated mock type for the TransactionCallbackAwaitable type +type TransactionCallbackAwaitable struct { + mock.Mock +} + +// OnAuthComplete provides a mock function with given fields: t, status +func (_m *TransactionCallbackAwaitable) OnAuthComplete(t *zcncore.Transaction, status int) { + _m.Called(t, status) +} + +// OnTransactionComplete provides a mock function with given fields: t, status +func (_m *TransactionCallbackAwaitable) OnTransactionComplete(t *zcncore.Transaction, status int) { + _m.Called(t, status) +} + +// OnVerifyComplete provides a mock function with given fields: t, status +func (_m *TransactionCallbackAwaitable) OnVerifyComplete(t *zcncore.Transaction, status int) { + _m.Called(t, status) +} + +// WaitCompleteCall provides a mock function with given fields: ctx +func (_m *TransactionCallbackAwaitable) WaitCompleteCall(ctx context.Context) error { + ret := _m.Called(ctx) + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context) error); ok { + r0 = rf(ctx) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// WaitVerifyCall provides a mock function with given fields: ctx +func (_m *TransactionCallbackAwaitable) WaitVerifyCall(ctx context.Context) error { + ret := _m.Called(ctx) + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context) error); ok { + r0 = rf(ctx) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +type mockConstructorTestingTNewTransactionCallbackAwaitable interface { + mock.TestingT + Cleanup(func()) +} + +// NewTransactionCallbackAwaitable creates a new instance of TransactionCallbackAwaitable. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewTransactionCallbackAwaitable(t mockConstructorTestingTNewTransactionCallbackAwaitable) *TransactionCallbackAwaitable { + mock := &TransactionCallbackAwaitable{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zcnbridge/mocks/TransactionProvider.go b/zcnbridge/mocks/TransactionProvider.go new file mode 100644 index 000000000..25617eb25 --- /dev/null +++ b/zcnbridge/mocks/TransactionProvider.go @@ -0,0 +1,54 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import ( + transaction "github.com/0chain/gosdk/zcnbridge/transaction" + mock "github.com/stretchr/testify/mock" +) + +// TransactionProvider is an autogenerated mock type for the TransactionProvider type +type TransactionProvider struct { + mock.Mock +} + +// NewTransactionEntity provides a mock function with given fields: txnFee +func (_m *TransactionProvider) NewTransactionEntity(txnFee uint64) (transaction.Transaction, error) { + ret := _m.Called(txnFee) + + var r0 transaction.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(uint64) (transaction.Transaction, error)); ok { + return rf(txnFee) + } + if rf, ok := ret.Get(0).(func(uint64) transaction.Transaction); ok { + r0 = rf(txnFee) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(transaction.Transaction) + } + } + + if rf, ok := ret.Get(1).(func(uint64) error); ok { + r1 = rf(txnFee) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +type mockConstructorTestingTNewTransactionProvider interface { + mock.TestingT + Cleanup(func()) +} + +// NewTransactionProvider creates a new instance of TransactionProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewTransactionProvider(t mockConstructorTestingTNewTransactionProvider) *TransactionProvider { + mock := &TransactionProvider{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zcnbridge/transaction/mocks/Transaction.go b/zcnbridge/transaction/mocks/Transaction.go new file mode 100644 index 000000000..b9a833470 --- /dev/null +++ b/zcnbridge/transaction/mocks/Transaction.go @@ -0,0 +1,135 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import ( + context "context" + + transaction "github.com/0chain/gosdk/zcnbridge/transaction" + mock "github.com/stretchr/testify/mock" + + zcncore "github.com/0chain/gosdk/zcncore" +) + +// Transaction is an autogenerated mock type for the Transaction type +type Transaction struct { + mock.Mock +} + +// ExecuteSmartContract provides a mock function with given fields: ctx, address, funcName, input, val +func (_m *Transaction) ExecuteSmartContract(ctx context.Context, address string, funcName string, input interface{}, val uint64) (string, error) { + ret := _m.Called(ctx, address, funcName, input, val) + + var r0 string + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, string, string, interface{}, uint64) (string, error)); ok { + return rf(ctx, address, funcName, input, val) + } + if rf, ok := ret.Get(0).(func(context.Context, string, string, interface{}, uint64) string); ok { + r0 = rf(ctx, address, funcName, input, val) + } else { + r0 = ret.Get(0).(string) + } + + if rf, ok := ret.Get(1).(func(context.Context, string, string, interface{}, uint64) error); ok { + r1 = rf(ctx, address, funcName, input, val) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetCallback provides a mock function with given fields: +func (_m *Transaction) GetCallback() transaction.TransactionCallbackAwaitable { + ret := _m.Called() + + var r0 transaction.TransactionCallbackAwaitable + if rf, ok := ret.Get(0).(func() transaction.TransactionCallbackAwaitable); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(transaction.TransactionCallbackAwaitable) + } + } + + return r0 +} + +// GetHash provides a mock function with given fields: +func (_m *Transaction) GetHash() string { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// GetScheme provides a mock function with given fields: +func (_m *Transaction) GetScheme() zcncore.TransactionScheme { + ret := _m.Called() + + var r0 zcncore.TransactionScheme + if rf, ok := ret.Get(0).(func() zcncore.TransactionScheme); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(zcncore.TransactionScheme) + } + } + + return r0 +} + +// GetTransactionOutput provides a mock function with given fields: +func (_m *Transaction) GetTransactionOutput() string { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// SetHash provides a mock function with given fields: _a0 +func (_m *Transaction) SetHash(_a0 string) { + _m.Called(_a0) +} + +// Verify provides a mock function with given fields: ctx +func (_m *Transaction) Verify(ctx context.Context) error { + ret := _m.Called(ctx) + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context) error); ok { + r0 = rf(ctx) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +type mockConstructorTestingTNewTransaction interface { + mock.TestingT + Cleanup(func()) +} + +// NewTransaction creates a new instance of Transaction. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewTransaction(t mockConstructorTestingTNewTransaction) *Transaction { + mock := &Transaction{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zcnbridge/transaction/mocks/TransactionCallbackAwaitable.go b/zcnbridge/transaction/mocks/TransactionCallbackAwaitable.go new file mode 100644 index 000000000..299573252 --- /dev/null +++ b/zcnbridge/transaction/mocks/TransactionCallbackAwaitable.go @@ -0,0 +1,74 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import ( + context "context" + + mock "github.com/stretchr/testify/mock" + + zcncore "github.com/0chain/gosdk/zcncore" +) + +// TransactionCallbackAwaitable is an autogenerated mock type for the TransactionCallbackAwaitable type +type TransactionCallbackAwaitable struct { + mock.Mock +} + +// OnAuthComplete provides a mock function with given fields: t, status +func (_m *TransactionCallbackAwaitable) OnAuthComplete(t *zcncore.Transaction, status int) { + _m.Called(t, status) +} + +// OnTransactionComplete provides a mock function with given fields: t, status +func (_m *TransactionCallbackAwaitable) OnTransactionComplete(t *zcncore.Transaction, status int) { + _m.Called(t, status) +} + +// OnVerifyComplete provides a mock function with given fields: t, status +func (_m *TransactionCallbackAwaitable) OnVerifyComplete(t *zcncore.Transaction, status int) { + _m.Called(t, status) +} + +// WaitCompleteCall provides a mock function with given fields: ctx +func (_m *TransactionCallbackAwaitable) WaitCompleteCall(ctx context.Context) error { + ret := _m.Called(ctx) + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context) error); ok { + r0 = rf(ctx) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// WaitVerifyCall provides a mock function with given fields: ctx +func (_m *TransactionCallbackAwaitable) WaitVerifyCall(ctx context.Context) error { + ret := _m.Called(ctx) + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context) error); ok { + r0 = rf(ctx) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +type mockConstructorTestingTNewTransactionCallbackAwaitable interface { + mock.TestingT + Cleanup(func()) +} + +// NewTransactionCallbackAwaitable creates a new instance of TransactionCallbackAwaitable. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewTransactionCallbackAwaitable(t mockConstructorTestingTNewTransactionCallbackAwaitable) *TransactionCallbackAwaitable { + mock := &TransactionCallbackAwaitable{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zcnbridge/transaction/mocks/TransactionProvider.go b/zcnbridge/transaction/mocks/TransactionProvider.go new file mode 100644 index 000000000..25617eb25 --- /dev/null +++ b/zcnbridge/transaction/mocks/TransactionProvider.go @@ -0,0 +1,54 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import ( + transaction "github.com/0chain/gosdk/zcnbridge/transaction" + mock "github.com/stretchr/testify/mock" +) + +// TransactionProvider is an autogenerated mock type for the TransactionProvider type +type TransactionProvider struct { + mock.Mock +} + +// NewTransactionEntity provides a mock function with given fields: txnFee +func (_m *TransactionProvider) NewTransactionEntity(txnFee uint64) (transaction.Transaction, error) { + ret := _m.Called(txnFee) + + var r0 transaction.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(uint64) (transaction.Transaction, error)); ok { + return rf(txnFee) + } + if rf, ok := ret.Get(0).(func(uint64) transaction.Transaction); ok { + r0 = rf(txnFee) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(transaction.Transaction) + } + } + + if rf, ok := ret.Get(1).(func(uint64) error); ok { + r1 = rf(txnFee) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +type mockConstructorTestingTNewTransactionProvider interface { + mock.TestingT + Cleanup(func()) +} + +// NewTransactionProvider creates a new instance of TransactionProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewTransactionProvider(t mockConstructorTestingTNewTransactionProvider) *TransactionProvider { + mock := &TransactionProvider{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} From dc1a603b2ee3778d640279429bc60715d26bf4e5 Mon Sep 17 00:00:00 2001 From: YarikRevich Date: Sat, 26 Aug 2023 14:23:20 +0200 Subject: [PATCH 012/134] fix: fixed bugs --- go.mod | 25 +++----- go.sum | 184 ++++++--------------------------------------------------- 2 files changed, 26 insertions(+), 183 deletions(-) diff --git a/go.mod b/go.mod index 2d198cbf2..578f0e474 100644 --- a/go.mod +++ b/go.mod @@ -9,7 +9,7 @@ require ( github.com/btcsuite/btcd v0.23.4 github.com/dgraph-io/badger/v3 v3.2103.5 github.com/didip/tollbooth v4.0.2+incompatible - github.com/ethereum/go-ethereum v1.12.0 + github.com/ethereum/go-ethereum v1.10.26 github.com/google/uuid v1.3.0 github.com/gorilla/handlers v1.5.1 github.com/gorilla/mux v1.8.0 @@ -46,31 +46,25 @@ require ( require github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d require ( - github.com/DataDog/zstd v1.5.2 // indirect github.com/VictoriaMetrics/fastcache v1.6.0 // indirect - github.com/beorn7/perks v1.0.1 // indirect github.com/btcsuite/btcd/btcec/v2 v2.3.2 // indirect github.com/btcsuite/btcd/chaincfg/chainhash v1.0.2 // indirect github.com/cespare/xxhash v1.1.0 // indirect github.com/cespare/xxhash/v2 v2.2.0 // indirect - github.com/cockroachdb/errors v1.9.1 // indirect - github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect - github.com/cockroachdb/pebble v0.0.0-20230209160836-829675f94811 // indirect - github.com/cockroachdb/redact v1.1.3 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/deckarep/golang-set/v2 v2.1.0 // indirect + github.com/deckarep/golang-set v1.8.0 // indirect github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 // indirect github.com/dgraph-io/ristretto v0.1.1 // indirect github.com/dustin/go-humanize v1.0.1 // indirect + github.com/edsrzf/mmap-go v1.0.0 // indirect github.com/felixge/httpsnoop v1.0.3 // indirect github.com/fjl/memsize v0.0.0-20190710130421-bcb5799ab5e5 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff // indirect - github.com/getsentry/sentry-go v0.18.0 // indirect + github.com/go-logfmt/logfmt v0.5.1 // indirect github.com/go-ole/go-ole v1.2.6 // indirect github.com/go-stack/stack v1.8.1 // indirect - github.com/gofrs/flock v0.8.1 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang-jwt/jwt/v4 v4.3.0 // indirect github.com/golang/glog v1.0.0 // indirect @@ -87,26 +81,21 @@ require ( github.com/huin/goupnp v1.0.3 // indirect github.com/jackpal/go-nat-pmp v1.0.2 // indirect github.com/kr/pretty v0.3.1 // indirect - github.com/kr/text v0.2.0 // indirect github.com/labstack/gommon v0.4.0 // indirect github.com/magiconair/properties v1.8.7 // indirect github.com/matryer/is v1.4.1 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.17 // indirect github.com/mattn/go-runewidth v0.0.14 // indirect - github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect github.com/mitchellh/pointerstructure v1.2.0 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/patrickmn/go-cache v2.1.0+incompatible // indirect github.com/pelletier/go-toml/v2 v2.0.6 // indirect github.com/philhofer/fwd v1.1.2-0.20210722190033-5c56ac6d0bb9 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/prometheus/client_golang v1.14.0 // indirect - github.com/prometheus/client_model v0.3.0 // indirect - github.com/prometheus/common v0.39.0 // indirect - github.com/prometheus/procfs v0.9.0 // indirect + github.com/prometheus/tsdb v0.7.1 // indirect github.com/rivo/uniseg v0.4.3 // indirect - github.com/rogpeppe/go-internal v1.9.0 // indirect + github.com/rjeczalik/notify v0.9.1 // indirect github.com/rs/cors v1.7.0 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/shirou/gopsutil v3.21.11+incompatible // indirect @@ -127,10 +116,10 @@ require ( github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect go.dedis.ch/fixbuf v1.0.3 // indirect go.opencensus.io v0.24.0 // indirect - golang.org/x/exp v0.0.0-20230206171751-46f607a40771 // indirect golang.org/x/sys v0.7.0 // indirect golang.org/x/text v0.8.0 // indirect google.golang.org/protobuf v1.28.1 // indirect + gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce // indirect ) diff --git a/go.sum b/go.sum index c20718b07..d20bca247 100644 --- a/go.sum +++ b/go.sum @@ -44,24 +44,16 @@ github.com/0chain/common v0.0.6-0.20230127095721-8df4d1d72565 h1:z+DtCR8mBsjPnEs github.com/0chain/common v0.0.6-0.20230127095721-8df4d1d72565/go.mod h1:UyDC8Qyl5z9lGkCnf9RHJPMektnFX8XtCJZHXCCVj8E= github.com/0chain/errors v1.0.3 h1:QQZPFxTfnMcRdt32DXbzRQIfGWmBsKoEdszKQDb0rRM= github.com/0chain/errors v1.0.3/go.mod h1:xymD6nVgrbgttWwkpSCfLLEJbFO6iHGQwk/yeSuYkIc= -github.com/AndreasBriese/bbloom v0.0.0-20190306092124-e2d15f34fcf9/go.mod h1:bOvUY6CB00SOBii9/FifXqc0awNKxLFCL/+pkDPuyl8= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= -github.com/CloudyKit/fastprinter v0.0.0-20200109182630-33d98a066a53/go.mod h1:+3IMCy2vIlbG1XG/0ggNQv0SvxCAIpPM5b1nCz56Xno= -github.com/CloudyKit/jet/v3 v3.0.0/go.mod h1:HKQPgSJmdK8hdoAbKUUWajkHyHo4RaU5rMdUywE7VMo= github.com/DATA-DOG/go-sqlmock v1.3.3/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= -github.com/DataDog/zstd v1.5.2 h1:vUG4lAyuPCXO0TLbXvPv7EB7cNK1QV/luu55UHLrrn8= -github.com/DataDog/zstd v1.5.2/go.mod h1:g4AWEaM3yOg3HYfnJ3YIawPnVdXJh9QME85blwSAmyw= -github.com/Joker/hpp v1.0.0/go.mod h1:8x5n+M1Hp5hC0g8okX3sR3vFQwynaX/UgSOM9MeBKzY= github.com/Luzifer/go-openssl/v3 v3.1.0 h1:QqKqo6kYXGGUsvtUoCpRZm8lHw+jDfhbzr36gVj+/gw= github.com/Luzifer/go-openssl/v3 v3.1.0/go.mod h1:liy3FXuuS8hfDlYh1T+l78AwQ/NjZflJz0NDvjKhwDs= github.com/OneOfOne/xxhash v1.2.2 h1:KMrpdQIwFcEqXDklaen+P1axHaj9BSKzvpUUfnHldSE= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= -github.com/Shopify/goreferrer v0.0.0-20181106222321-ec9c9a553398/go.mod h1:a1uqRtAwp2Xwc6WNPJEufxJ7fx3npB4UV/JOLmbu5I0= github.com/VictoriaMetrics/fastcache v1.6.0 h1:C/3Oi3EiBCqufydp1neRZkqcwmEiuRT9c3fqvvgKm5o= github.com/VictoriaMetrics/fastcache v1.6.0/go.mod h1:0qHz5QP0GMX4pfmMA/zt5RgfNuXJrTP0zS7DqpHGGTw= github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII= -github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY= github.com/ajstarks/svgo v0.0.0-20180226025133-644b8db467af/go.mod h1:K08gAheRH3/J6wwsYMMT4xOr94bZjxIelGM0+d/wbFw= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= @@ -70,13 +62,10 @@ github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8= github.com/apache/arrow/go/arrow v0.0.0-20191024131854-af6fa24be0db/go.mod h1:VTxUBvSJ3s3eHAg65PNgrsn5BtqCRPdmyXh6rAfdxN0= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= -github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8= github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= -github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= -github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bmizerany/pat v0.0.0-20170815010413-6226ea591a40/go.mod h1:8rLXio+WjiTceGBHIoTvn60HIbs7Hm7bcHjyrSqYB9c= github.com/boltdb/bolt v1.3.1/go.mod h1:clJnj/oiGkjum5o1McbSZDSLxVThjynRyGBgiAx27Ps= github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ= @@ -120,18 +109,6 @@ github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDk github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= -github.com/cockroachdb/datadriven v1.0.2 h1:H9MtNqVoVhvd9nCBwOyDjUEdZCREqbIdCJD93PBm/jA= -github.com/cockroachdb/datadriven v1.0.2/go.mod h1:a9RdTaap04u637JoCzcUoIcDmvwSUtcUFtT/C3kJlTU= -github.com/cockroachdb/errors v1.9.1 h1:yFVvsI0VxmRShfawbt/laCIDy/mtTqqnvoNgiy5bEV8= -github.com/cockroachdb/errors v1.9.1/go.mod h1:2sxOtL2WIc096WSZqZ5h8fa17rdDq9HZOZLBCor4mBk= -github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= -github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= -github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= -github.com/cockroachdb/pebble v0.0.0-20230209160836-829675f94811 h1:ytcWPaNPhNoGMWEhDvS3zToKcDpRsLuRolQJBVGdozk= -github.com/cockroachdb/pebble v0.0.0-20230209160836-829675f94811/go.mod h1:Nb5lgvnQ2+oGlE/EyZy4+2/CxRh9KfvCXnag1vtpxVM= -github.com/cockroachdb/redact v1.1.3 h1:AKZds10rFSIj7qADf0g46UixK8NNLwWTNdCIGS5wfSQ= -github.com/cockroachdb/redact v1.1.3/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= -github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0/go.mod h1:4Zcjuz89kmFXt9morQgcfYZAYZ5n8WHjt81YYWIwtTM= github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= @@ -144,15 +121,14 @@ github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2 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/deckarep/golang-set/v2 v2.1.0 h1:g47V4Or+DUdzbs8FxCCmgb6VYd+ptPAngjM6dtGktsI= -github.com/deckarep/golang-set/v2 v2.1.0/go.mod h1:VAky9rY/yGXJOLEDv3OMci+7wtDpOF4IN+y82NBOac4= +github.com/deckarep/golang-set v1.8.0 h1:sk9/l/KqpunDwP7pSjUg0keiOOLEnOBHzykLrsPppp4= +github.com/deckarep/golang-set v1.8.0/go.mod h1:5nI87KwE7wgsBU1F4GKAw2Qod7p5kyS383rP6+o6qqo= github.com/decred/dcrd/crypto/blake256 v1.0.0 h1:/8DMNYp9SGi5f0w7uCm6d6M4OU2rGFK09Y2A4Xv7EE0= github.com/decred/dcrd/crypto/blake256 v1.0.0/go.mod h1:sQl2p6Y26YV+ZOcSTP6thNdn47hh8kt6rqSlvmrXFAc= github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1/go.mod h1:hyedUtir6IdtD/7lIxGeCxkaw7y45JueMRL4DIyJDKs= github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 h1:HbphB4TFFXpv7MNrT52FGrrgVXF1owhMVTHFZIlnvd4= github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0/go.mod h1:DZGJHZMqrU4JJqFAWUS2UO1+lbSKsdiOoYi9Zzey7Fc= github.com/decred/dcrd/lru v1.0.0/go.mod h1:mxKOwFd7lFjN2GZYsiz/ecgqR6kkYAl+0pz0tEMk218= -github.com/dgraph-io/badger v1.6.0/go.mod h1:zwt7syl517jmP8s94KqSxTlM6IMsdhYy6psNgSztDR4= github.com/dgraph-io/badger/v3 v3.2103.5 h1:ylPa6qzbjYRQMU6jokoj4wzcaweHylt//CH0AKt0akg= github.com/dgraph-io/badger/v3 v3.2103.5/go.mod h1:4MPiseMeDQ3FNCYwRbbcBOGJLf5jsE0PPFzRiKjtcdw= github.com/dgraph-io/ristretto v0.1.1 h1:6CWw5tJNgpegArSHpNHJKldNeq03FQCwYvfMVWajOK8= @@ -161,26 +137,24 @@ github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZm github.com/dgryski/go-bitstream v0.0.0-20180413035011-3522498ce2c8/go.mod h1:VMaSuZ+SZcx/wljOQKvp5srsbCiKDEb6K2wC4+PiBmQ= github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2 h1:tdlZCpZ/P9DhczCTSixgIKmwPv6+wP5DGjqLYw5SUiA= github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= +github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= github.com/didip/tollbooth v4.0.2+incompatible h1:fVSa33JzSz0hoh2NxpwZtksAzAgd7zjmGO20HCZtF4M= github.com/didip/tollbooth v4.0.2+incompatible/go.mod h1:A9b0665CE6l1KmzpDws2++elm/CsuWBMa5Jv4WY0PEY= github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/eclipse/paho.mqtt.golang v1.2.0/go.mod h1:H9keYFcgq3Qr5OUJm/JZI/i6U7joQ8SYLhZwfeOo6Ts= -github.com/eknkc/amber v0.0.0-20171010120322-cdade1c07385/go.mod h1:0vRUJqYpeSZifjYj7uP3BG/gKcuzL9xWVV/Y+cK33KM= +github.com/edsrzf/mmap-go v1.0.0 h1:CEBF7HpRnUCSJgGUb5h1Gm7e3VkmVDrR8lvWVLtrOFw= +github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5ynNVH9qI8YYLbd1fK2po= github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= -github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/etcd-io/bbolt v1.3.3/go.mod h1:ZF2nL25h33cCyBtcyWeZ2/I3HQOfTP+0PIEvHjkjCrw= -github.com/ethereum/go-ethereum v1.12.0 h1:bdnhLPtqETd4m3mS8BGMNvBTf36bO5bx/hxE2zljOa0= -github.com/ethereum/go-ethereum v1.12.0/go.mod h1:/oo2X/dZLJjf2mJ6YT9wcWxa4nNJDBKDBU6sFIpx1Gs= -github.com/fasthttp-contrib/websocket v0.0.0-20160511215533-1f3b11f56072/go.mod h1:duJ4Jxv5lDcvg4QuQr0oowTf7dz4/CR8NtyCooz9HL8= +github.com/ethereum/go-ethereum v1.10.26 h1:i/7d9RBBwiXCEuyduBQzJw/mKmnvzsN14jqBmytw72s= +github.com/ethereum/go-ethereum v1.10.26/go.mod h1:EYFyF19u3ezGLD4RqOkLq+ZCXzYbLoNDdZlMt7kyKFg= github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w= -github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= github.com/felixge/httpsnoop v1.0.1/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/felixge/httpsnoop v1.0.3 h1:s/nj+GCswXYzN5v2DpNMuMQYe+0DDwt5WVCU6CWBdXk= github.com/felixge/httpsnoop v1.0.3/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= @@ -192,47 +166,30 @@ github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMo github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= -github.com/gavv/httpexpect v2.0.0+incompatible/go.mod h1:x+9tiU1YnrOvnB725RkpoLv1M62hOWzwo5OXotisrKc= github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff h1:tY80oXqGNY4FhTFhk+o9oFHGINQ/+vhlm8HFzi6znCI= github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff/go.mod h1:x7DCsMOv1taUwEWCzT4cmDeAkigA5/QCwUodaVOe8Ww= -github.com/getsentry/sentry-go v0.12.0/go.mod h1:NSap0JBYWzHND8oMbyi0+XZhUalc1TBdRL1M71JZW2c= -github.com/getsentry/sentry-go v0.18.0 h1:MtBW5H9QgdcJabtZcuJG80BMOwaBpkRDZkxRkNC1sN0= -github.com/getsentry/sentry-go v0.18.0/go.mod h1:Kgon4Mby+FJ7ZWHFUAZgVaIa8sxHtnRJRLTXZr51aKQ= -github.com/gin-contrib/sse v0.0.0-20190301062529-5545eab6dad3/go.mod h1:VJ0WA2NBN22VlZ2dKZQPAPnyWw5XTlK1KymzLKsr59s= -github.com/gin-gonic/gin v1.4.0/go.mod h1:OW2EZn3DO8Ln9oIKOvM++LBO+5UPHJJDH72/q/3rZdM= github.com/glycerine/go-unsnap-stream v0.0.0-20180323001048-9f0cb55181dd/go.mod h1:/20jfyN9Y5QPEAprSgKAUr+glWDY39ZiUEAYOEv5dsE= github.com/glycerine/goconvey v0.0.0-20190410193231-58a59202ab31/go.mod h1:Ogl1Tioa0aV7gstGFO7KhffUsb9M4ydbEbbxpcEDc24= -github.com/go-check/check v0.0.0-20180628173108-788fd7840127/go.mod h1:9ES+weclKsC9YodN5RgxqK/VD9HM9JsCSh7rNhMZE98= -github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q= -github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-kit/kit v0.8.0 h1:Wz+5lgoB0kkuqLEc6NVmwRknTKP6dTGbSqvhZtBI/j0= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= -github.com/go-martini/martini v0.0.0-20170121215854-22fa46961aab/go.mod h1:/P9AEU963A2AYjv4d1V5eVL1CQbEJq6aCNHDDjibzu8= +github.com/go-logfmt/logfmt v0.5.1 h1:otpy5pqBCBZ1ng9RQ0dPu4PN7ba75Y/aA+UpowDyNVA= +github.com/go-logfmt/logfmt v0.5.1/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY= github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/go-stack/stack v1.8.1 h1:ntEHSVwIt7PNXNpgPmVfMrNhLtgjlmnZha2kOpuRiDw= github.com/go-stack/stack v1.8.1/go.mod h1:dcoOX6HbPZSZptuspn9bctJ+N/CnF5gGygcUP3XYfe4= -github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee/go.mod h1:L0fX3K22YWvt/FAX9NnzrNzcI4wNYi9Yku4O0LKYflo= -github.com/gobwas/pool v0.2.0/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= -github.com/gobwas/ws v1.0.2/go.mod h1:szmBTxLgaFppYjEmNtny/v3w89xOydFnnZMcgRRu/EM= -github.com/gofrs/flock v0.8.1 h1:+gYjHKf32LDeiEEFhQaotPbLuUXjY5ZqxKgXy7n59aw= -github.com/gofrs/flock v0.8.1/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU= github.com/gofrs/uuid v3.3.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= -github.com/gogo/googleapis v0.0.0-20180223154316-0cd9801be74a/go.mod h1:gf4bu3Q80BeJ6H1S1vYPm8/ELATdvryBaNFGgqEef3s= -github.com/gogo/googleapis v1.4.1/go.mod h1:2lpHqI5OcWCtVElxXnPt+s8oJvMpySlOyM6xDCrzib4= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= -github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= -github.com/gogo/status v1.1.0/go.mod h1:BFv9nrluPLmrS0EmGVvLaPNmRosr9KapBYd5/hpY1WM= -github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= github.com/golang-jwt/jwt/v4 v4.3.0 h1:kHL1vqdqWNfATmA0FNMdmZNMyZI1U6O31X4rlIPoBog= github.com/golang-jwt/jwt/v4 v4.3.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg= github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= @@ -274,7 +231,6 @@ github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEW github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb h1:PBC98N2aIaM3XXiurYmW7fx4GZkL8feAMVq7nEjURHk= github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= -github.com/gomodule/redigo v1.7.1-0.20190724094224-574c33c3df38/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/flatbuffers v1.11.0/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8= @@ -293,8 +249,6 @@ github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= -github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= -github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= @@ -321,7 +275,6 @@ github.com/gorilla/handlers v1.5.1 h1:9lRY6j8DEeeBT10CvO9hGW0gmky0BprnvDI5vfhUHH github.com/gorilla/handlers v1.5.1/go.mod h1:t8XrUpc4KVXb7HGyJ4/cEnwQiaxrX/hz1Zv/4g96P1Q= github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= -github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/h2non/filetype v1.1.3 h1:FKkx9QbD7HR/zjK1Ia5XiBsq9zdLi5Kf3zGyFTAFkGg= @@ -334,7 +287,6 @@ github.com/hashicorp/go-hclog v0.9.2/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrj github.com/hashicorp/go-hclog v1.2.0 h1:La19f8d7WIlm4ogzNHB0JGqs5AUDAZ2UfCY4sJXcJdM= github.com/hashicorp/go-retryablehttp v0.7.2 h1:AcYqCvkpalPnPF2pn0KamgwamS42TqUDDYFRKq/RAd0= github.com/hashicorp/go-retryablehttp v0.7.2/go.mod h1:Jy/gPYAdjqffZ/yFGCFV2doI5wjtH1ewM9u8iYVjtX8= -github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d h1:dg1dEPuWpEqDnvIw251EVy4zlP8gWbsGj4BsUKCRpYs= @@ -353,10 +305,8 @@ github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpO github.com/huin/goupnp v1.0.3 h1:N8No57ls+MnjlB+JPiCVSOyy/ot7MJTqlo7rn+NYSqQ= github.com/huin/goupnp v1.0.3/go.mod h1:ZxNlw5WqJj6wSsRK5+YfflQGXYfccj5VgQsMNixHM7Y= github.com/huin/goutil v0.0.0-20170803182201-1ca381bf3150/go.mod h1:PpLOETDnJ0o3iZrZfqZzyLl6l7F3c6L1oWn7OICBi6o= -github.com/hydrogen18/memlistener v0.0.0-20200120041712-dcc25e7acd91/go.mod h1:qEIFzExnS6016fRpRfxrExeVn2gbClQA99gQhnIcdhE= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= -github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/CoI+jC3w2iA= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/influxdata/flux v0.65.1/go.mod h1:J754/zds0vvpfwuq7Gc2wRdVwEodfpCFM7mYlOw2LqY= github.com/influxdata/influxdb v1.8.3 h1:WEypI1BQFTT4teLM+1qkEcvUi0dAvopAI/ir0vAiBg8= @@ -367,18 +317,12 @@ github.com/influxdata/promql/v2 v2.12.0/go.mod h1:fxOPu+DY0bqCTCECchSRtWfc+0X19y github.com/influxdata/roaring v0.4.13-0.20180809181101-fc520f41fab6/go.mod h1:bSgUQ7q5ZLSO+bKBGqJiCBGAl+9DxyW63zLTujjUlOE= github.com/influxdata/tdigest v0.0.0-20181121200506-bf2b5ad3c0a9/go.mod h1:Js0mqiSBE6Ffsg94weZZ2c+v/ciT8QRHFOap7EKDrR0= github.com/influxdata/usage-client v0.0.0-20160829180054-6d3895376368/go.mod h1:Wbbw6tYNvwa5dlB6304Sd+82Z3f7PmVZHVKU637d4po= -github.com/iris-contrib/blackfriday v2.0.0+incompatible/go.mod h1:UzZ2bDEoaSGPbkg6SAB4att1aAwTmVIx/5gCVqeyUdI= -github.com/iris-contrib/go.uuid v2.0.0+incompatible/go.mod h1:iz2lgM/1UnEf1kP0L/+fafWORmlnuysV2EMP8MW+qe0= -github.com/iris-contrib/jade v1.1.3/go.mod h1:H/geBymxJhShH5kecoiOCSssPX7QWYH7UaeZTSWddIk= -github.com/iris-contrib/pongo2 v0.0.1/go.mod h1:Ssh+00+3GAZqSQb30AvBRNxBx7rf0GqwkjqxNd0u65g= -github.com/iris-contrib/schema v0.0.1/go.mod h1:urYA3uvUNG1TIIjOSCzHr9/LmbQo8LrOcOqfqxa4hXw= github.com/jackpal/go-nat-pmp v1.0.2 h1:KzKSgb7qkJvOUTqYl9/Hg/me3pWgBmERKrTGD7BdWus= github.com/jackpal/go-nat-pmp v1.0.2/go.mod h1:QPH045xvCAeXUZOxsnwmrtiCoxIr9eob+4orBN1SBKc= github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/jrick/logrotate v1.0.0/go.mod h1:LNinyqDIJnpAur+b8yyulnQw/wDuN1+BYKlTRt3OuAQ= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= -github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= github.com/jsternberg/zap-logfmt v1.0.0/go.mod h1:uvPs/4X51zdkcm5jXl5SYoN+4RK21K8mysFmDaM/h+o= @@ -386,24 +330,15 @@ github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfV github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= github.com/jung-kurt/gofpdf v1.0.3-0.20190309125859-24315acbbda5/go.mod h1:7Id9E/uU8ce6rXgefFLlgrJj/GYY22cpxn+r32jIOes= github.com/jwilder/encoding v0.0.0-20170811194829-b4e1701a28ef/go.mod h1:Ct9fl0F6iIOGgxJ5npU/IUOhOhqlVrGjyIZc8/MagT0= -github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88/go.mod h1:3w7q1U84EfirKl04SVQ/s7nPm1ZPhiXd34z40TNz36k= -github.com/kataras/golog v0.0.10/go.mod h1:yJ8YKCmyL+nWjERB90Qwn+bdyBZsaQwU3bTVFgkFIp8= -github.com/kataras/iris/v12 v12.1.8/go.mod h1:LMYy4VlP67TQ3Zgriz8RE2h2kMZV2SgMYbq3UhfoFmE= -github.com/kataras/neffos v0.0.14/go.mod h1:8lqADm8PnbeFfL7CLXh1WHw53dG27MC3pgi2R1rmoTE= -github.com/kataras/pio v0.0.2/go.mod h1:hAoW0t9UmXi4R5Oyq5Z4irTbaTsOemSrDGUtaTl7Dro= -github.com/kataras/sitemap v0.0.5/go.mod h1:KY2eugMKiPwsJgx7+U103YZehfvNGOXURubcGyk0Bz8= github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4= github.com/klauspost/compress v1.4.0/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= -github.com/klauspost/compress v1.8.2/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= -github.com/klauspost/compress v1.9.7/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= github.com/klauspost/compress v1.12.3/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= github.com/klauspost/compress v1.16.0 h1:iULayQNOReoYUe+1qtKOqw9CwJv3aNQu8ivo7lw1HU4= github.com/klauspost/compress v1.16.0/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/cpuid v0.0.0-20170728055534-ae7887de9fa5/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= -github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk= github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= github.com/klauspost/crc32 v0.0.0-20161016154125-cb6bfca970f6/go.mod h1:+ZoRqAPRLkC4NPOvfYeR5KNOrY6TD+/sAC3HXPZgDYg= @@ -414,18 +349,15 @@ github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxv github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= 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/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/labstack/echo v3.3.10+incompatible h1:pGRcYk231ExFAyoAjAfD85kQzRJCRI8bbnE7CX5OEgg= github.com/labstack/echo v3.3.10+incompatible/go.mod h1:0INS7j/VjnFxD4E2wkz67b8cVwCLbBmJyDaka6Cmk1s= -github.com/labstack/echo/v4 v4.5.0/go.mod h1:czIriw4a0C1dFun+ObrXp7ok03xON0N1awStJ6ArI7Y= -github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k= github.com/labstack/gommon v0.4.0 h1:y7cvthEAEbU0yHOf4axH8ZG2NH8knB9iNSoTO8dyIk8= github.com/labstack/gommon v0.4.0/go.mod h1:uW6kP17uPlLJsD3ijUYn3/M5bAxtlZhMI6m3MFxTMTM= github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= @@ -441,16 +373,10 @@ github.com/magma/augmented-networks/accounting/protos v0.1.1/go.mod h1:Hpfg8aAxl github.com/matryer/is v1.4.1 h1:55ehd8zaGABKLXQUe2awZ99BD/PTc2ls+KV/dXphgEQ= github.com/matryer/is v1.4.1/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= -github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= -github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= -github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ= -github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng= @@ -461,12 +387,7 @@ github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWV github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/go-sqlite3 v1.11.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= github.com/mattn/go-tty v0.0.0-20180907095812-13ff1204f104/go.mod h1:XPvLUNfbS4fJH25nqRHfWLMa1ONC8Amw+mIA639KxkE= -github.com/mattn/goveralls v0.0.2/go.mod h1:8d1ZMHsd7fW6IRPKQh46F2WRpyib5/X4FOpevwGNQEw= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= -github.com/matttproud/golang_protobuf_extensions v1.0.4 h1:mmDVorXM7PCGKw94cs5zkfA9PSy5pEvNWRP0ET0TIVo= -github.com/matttproud/golang_protobuf_extensions v1.0.4/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4= -github.com/mediocregopher/radix/v3 v3.4.2/go.mod h1:8FL3F6UQRXHXIBSPUs5h0RybMF8i4n7wVopoX3x7Bv8= -github.com/microcosm-cc/bluemonday v1.0.2/go.mod h1:iVP4YcDBq+n/5fb23BhYFvIMq/leAFZyRl6bYmGDlGc= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= @@ -475,24 +396,17 @@ github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyua github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/mitchellh/pointerstructure v1.2.0 h1:O+i9nHnXS3l/9Wu7r4NrEdwA2VFTicjUEN1uBnDo34A= github.com/mitchellh/pointerstructure v1.2.0/go.mod h1:BRAsLI5zgXmw97Lf6s25bs8ohIXc3tViBH44KcwB2g4= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/moul/http2curl v1.0.0/go.mod h1:8UbvGypXm98wA/IqH45anm5Y2Z6ep6O31QGOAZ3H0fQ= github.com/mschoch/smat v0.0.0-20160514031455-90eadee771ae/go.mod h1:qAyveg+e4CE+eKJXWVjKXM4ck2QobLqTDytGJbLLhJg= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/nats-io/jwt v0.3.0/go.mod h1:fRYCDE99xlTsqUzISS1Bi75UBJ6ljOJQOAAu5VglpSg= -github.com/nats-io/nats.go v1.9.1/go.mod h1:ZjDU1L/7fJ09jvUSRVBR2e7+RnLiiIQyqyzEE/Zbp4w= -github.com/nats-io/nkeys v0.1.0/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w= -github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= github.com/nxadm/tail v1.4.4 h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= +github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.10.3/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= github.com/onsi/ginkgo v1.14.0 h1:2mOpI4JVVPBN+WQRa0WKH2eXR+Ey+uK4n7Zj0aYpIQA= github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= @@ -515,8 +429,6 @@ github.com/philhofer/fwd v1.1.1/go.mod h1:gk3iGcWd9+svBvR0sR+KPcfE+RNWozjowpeBVG github.com/philhofer/fwd v1.1.2-0.20210722190033-5c56ac6d0bb9 h1:6ob53CVz+ja2i7easAStApZJlh7sxyq3Cm7g1Di6iqA= github.com/philhofer/fwd v1.1.2-0.20210722190033-5c56ac6d0bb9/go.mod h1:gk3iGcWd9+svBvR0sR+KPcfE+RNWozjowpeBVG3ZVNU= github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= -github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= -github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= @@ -528,28 +440,23 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= -github.com/prometheus/client_golang v1.14.0 h1:nJdhIvne2eSX/XRAFV9PcvFFRbrjbcTUj0VP62TMhnw= -github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/client_model v0.3.0 h1:UBgGFHqYdG/TPFD1B1ogZywDqEkwp3fBMvqdiQ7Xew4= -github.com/prometheus/client_model v0.3.0/go.mod h1:LDGWKZIo7rky3hgvBe+caln+Dr3dPggB5dvjtD7w9+w= +github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.6.0/go.mod h1:eBmuwkDJBwy6iBfxCBob6t6dR6ENT/y+J+Zk0j9GMYc= -github.com/prometheus/common v0.39.0 h1:oOyhkDq05hPZKItWVBkJ6g6AtGxi+fy7F4JvUV8uhsI= -github.com/prometheus/common v0.39.0/go.mod h1:6XBZ7lYdLCbkAVhwRsWTZn+IN5AB9F/NXd5w0BbEX0Y= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= -github.com/prometheus/procfs v0.9.0 h1:wzCHvIvM5SxWqYvwgVL7yJY8Lz3PKn49KQtpgMYJfhI= -github.com/prometheus/procfs v0.9.0/go.mod h1:+pB4zwohETzFnmlpe6yd2lSc+0/46IYZRB/chUwxUZY= +github.com/prometheus/tsdb v0.7.1 h1:YZcsG11NqnK4czYLrWd9mpEuAJIHVQLwdrleYfszMAA= +github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= github.com/retailnext/hllpp v1.0.1-0.20180308014038-101a6d2f8b52/go.mod h1:RDpi1RftBQPUCDRw6SmxeaREsAaRKnOclghuzp/WRzc= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.4.3 h1:utMvzDsuh3suAEnhH0RdHmoPbU648o6CvXxTx4SBMOw= github.com/rivo/uniseg v0.4.3/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/rjeczalik/notify v0.9.1 h1:CLCKso/QK1snAlnhNR/CNvNiFU2saUtjV0bx3EwNeCE= +github.com/rjeczalik/notify v0.9.1/go.mod h1:rKwnCoCGeuQnwBtTSPL9Dad03Vh2n40ePRrjvIXnJho= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= -github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= -github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/rs/cors v1.7.0 h1:+88SsELBHx5r+hZ8TCkggzSstaWNbDvThkVK8H6f9ik= @@ -557,8 +464,6 @@ github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= -github.com/schollz/closestmatch v2.1.0+incompatible/go.mod h1:RtP1ddjLong6gTkbtmuhtR2uUrrJOpYzYRvbcPAid+g= github.com/segmentio/kafka-go v0.1.0/go.mod h1:X6itGqS9L4jDletMsxZ7Dz+JFWxM6JHfPOCvTvk+EJo= github.com/segmentio/kafka-go v0.2.0/go.mod h1:X6itGqS9L4jDletMsxZ7Dz+JFWxM6JHfPOCvTvk+EJo= github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= @@ -566,7 +471,6 @@ github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKl github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= github.com/shopspring/decimal v1.3.1 h1:2Usl1nmF/WZucqkFZhnfFYxxxu8LG21F6nPQBE5gKV8= github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= -github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= @@ -620,40 +524,25 @@ github.com/tklauser/numcpus v0.6.0 h1:kebhY2Qt+3U6RNK7UqpYNA+tJ23IBEGKkB7JQBfDYm github.com/tklauser/numcpus v0.6.0/go.mod h1:FEZLMke0lhOUG6w2JadTzp0a+Nl8PF/GFkQ5UVIcaL4= github.com/tyler-smith/go-bip39 v1.1.0 h1:5eUemwrMargf3BSLRRCalXT93Ns6pQJIjYQN2nyfOP8= github.com/tyler-smith/go-bip39 v1.1.0/go.mod h1:gUYDtqQw1JS3ZJ8UWVcGTGqqr6YIN3CWg+kkNaLt55U= -github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= -github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= -github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= github.com/uptrace/bunrouter v1.0.20 h1:jNvYNcJxF+lSYBQAaQjnE6I11Zs0m+3M5Ek7fq/Tp4c= github.com/uptrace/bunrouter v1.0.20/go.mod h1:TwT7Bc0ztF2Z2q/ZzMuSVkcb/Ig/d3MQeP2cxn3e1hI= github.com/urfave/cli/v2 v2.17.2-0.20221006022127-8f469abc00aa h1:5SqCsI/2Qya2bCzK15ozrqo2sZxkh0FHynJZOTVoV6Q= github.com/urfave/cli/v2 v2.17.2-0.20221006022127-8f469abc00aa/go.mod h1:1CNUng3PtjQMtRzJO4FMXBQvkGtuYRxxiR9xMa7jMwI= -github.com/urfave/negroni v1.0.0/go.mod h1:Meg73S6kFm/4PpbYdq35yYWoCZ9mS/YSx+lKnmiohz4= github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= -github.com/valyala/fasthttp v1.6.0/go.mod h1:FstJa9V+Pj9vQ7OJie2qMHdwemEDaDiSdBnvPM1Su9w= -github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8= github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo= github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= -github.com/valyala/tcplisten v0.0.0-20161114210144-ceec8f93295a/go.mod h1:v3UYOV9WzVtRmSR+PDvWpU/qWl4Wa5LApYYX4ZtKbio= github.com/willf/bitset v1.1.3/go.mod h1:RjeCKbqT1RxIR/KWY6phxZiaY1IyutSBfGjNPySAYV4= -github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= -github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= -github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= github.com/xlab/treeprint v0.0.0-20180616005107-d6fb6747feb6/go.mod h1:ce1O1j6UtZfjr22oyGxGLbauSBp2YVXpARAosm7dHBg= github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU= github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8= -github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0/go.mod h1:/LWChgwKmvncFJFHJ7Gvn9wZArjbV5/FppcK2fKk/tI= -github.com/yudai/gojsondiff v1.0.0/go.mod h1:AY32+k2cwILAkW1fbgxQ5mUmMiZFgLIV+FBNExI05xg= -github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82/go.mod h1:lgjkn3NuSvDfVJdfcVVdX+jpBxNmX4rDAzaS45IcYoM= -github.com/yudai/pp v2.0.1+incompatible/go.mod h1:PuxR/8QJ7cyCkFp/aUDS+JY727OFEZkTdatxwunjIkc= github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yusufpapurcu/wmi v1.2.2 h1:KBNDSne4vP5mbSWnJbO+51IMOXJB67QiYCSBrubbPRg= github.com/yusufpapurcu/wmi v1.2.2/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= @@ -695,11 +584,8 @@ golang.org/x/crypto v0.0.0-20190123085648-057139ce5d2b/go.mod h1:6SG95UA2DQfeDnf golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20191227163750-53104e6ec876/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= @@ -718,8 +604,6 @@ golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u0 golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= -golang.org/x/exp v0.0.0-20230206171751-46f607a40771 h1:xP7rWLUr1e1n2xkK5YB4LI0hPEy3LJC6Wk+D4pGlOJg= -golang.org/x/exp v0.0.0-20230206171751-46f607a40771/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc= golang.org/x/image v0.0.0-20180708004352-c73c2afc3b81/go.mod h1:ux5Hcp/YLpHSI86hEcLt0YII63i6oz57MZXIpbrjZUs= golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= @@ -736,7 +620,6 @@ golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRu golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= @@ -747,18 +630,15 @@ golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190327091125-710a502c58a2/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= @@ -767,7 +647,6 @@ golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLL golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -790,8 +669,6 @@ golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwY golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= -golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= @@ -821,20 +698,18 @@ golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190124100055-b90733256f2e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -844,7 +719,6 @@ golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200107162124-548cf772de50/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -867,17 +741,11 @@ golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210225134936-a50acf3fe073/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210324051608-47abb6519492/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211103235746-7861aae1554b/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -895,8 +763,6 @@ golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3 golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68= @@ -904,20 +770,17 @@ golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180525024113-a5b4c53f6e8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20181221001348-537d06c36207/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190206041539-40960b6deb8e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190327201419-c70d86f8b7cf/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= @@ -965,7 +828,6 @@ golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4f golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210108195828-e2f9c7f1fc8e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= -golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -1004,7 +866,6 @@ google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/genproto v0.0.0-20180518175338-11a468237815/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= @@ -1043,10 +904,8 @@ google.golang.org/genproto v0.0.0-20201210142538-e3217bee35cc/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210108203827-ffc7fda8c3d7/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210226172003-ab064af71705/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24= google.golang.org/genproto v0.0.0-20230216225411-c8e22ba71e44 h1:EfLuoKW5WfkgVdDy7dTK8qSbH37AX5mj/MFh+bGPz14= google.golang.org/genproto v0.0.0-20230216225411-c8e22ba71e44/go.mod h1:8B0gmkoRebU8ukX6HP+4wrVQUY1+6PkQ44BSyIlflHA= -google.golang.org/grpc v1.12.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= @@ -1063,7 +922,6 @@ google.golang.org/grpc v1.31.1/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA51WJ8= google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= google.golang.org/grpc v1.53.0 h1:LAv2ds7cmFV/XTS3XG1NneeENYrXGmorPxsBbptIjNc= google.golang.org/grpc v1.53.0/go.mod h1:OnIrk0ipVdj4N5d9IUoFUx72/VlD7+jUsHwZgwSMQpw= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= @@ -1085,16 +943,13 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8 gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/cheggaaa/pb.v1 v1.0.28 h1:n1tBJnnK2r7g9OW2btFH91V92STTUevLXYFb8gy9EMk= gopkg.in/cheggaaa/pb.v1 v1.0.28/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= -gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8bDuhia5mkpMnE= -gopkg.in/go-playground/validator.v8 v8.18.2/go.mod h1:RX2a/7Ha8BgOhfk7j780h4/u/RRjR0eouCJSH80/M2Y= -gopkg.in/ini.v1 v1.51.1/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= -gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce h1:+JknDZhAj8YMt7GC73Ei8pv4MzjDUNPHgQWJdtMAaDU= @@ -1108,7 +963,6 @@ gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= -gopkg.in/yaml.v3 v3.0.0-20191120175047-4206685974f2/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= From e9c908492e28f7ec73c7799184b835f8a67040b4 Mon Sep 17 00:00:00 2001 From: YarikRevich Date: Sat, 26 Aug 2023 15:04:46 +0200 Subject: [PATCH 013/134] fix: fixed mocks --- zboxcore/mocks/AllocationChange.go | 2 +- zboxcore/mocks/ChunkedUploadChunkReader.go | 80 +++ zboxcore/mocks/ChunkedUploadFormBuilder.go | 63 ++ zboxcore/mocks/ChunkedUploadOption.go | 33 + zboxcore/mocks/ChunkedUploadProgressStorer.go | 63 ++ zboxcore/mocks/DownloadOption.go | 33 + zboxcore/mocks/Downloader.go | 72 +++ zboxcore/mocks/EncryptionScheme.go | 42 +- zboxcore/mocks/FileNameBuilder.go | 95 +++ zboxcore/mocks/Hasher.go | 153 +++++ zboxcore/mocks/HttpClient.go | 7 +- zboxcore/mocks/LiveUploadOption.go | 33 + zboxcore/mocks/LiveUploadReader.go | 91 +++ zboxcore/mocks/M3u8Writer.go | 101 ++++ zboxcore/mocks/Operationer.go | 109 ++++ zboxcore/mocks/RefEntity.go | 2 +- zboxcore/mocks/SCRestAPIHandler.go | 2 +- zboxcore/mocks/SignFunc.go | 49 ++ zboxcore/mocks/StatusCallback.go | 2 +- zboxcore/mocks/Suite.go | 2 +- zcncore/mocks/AuthCallback.go | 2 +- zcncore/mocks/FeeOption.go | 30 + zcncore/mocks/GetBalanceCallback.go | 2 +- zcncore/mocks/GetInfoCallback.go | 2 +- zcncore/mocks/GetNonceCallback.go | 30 + zcncore/mocks/MSVoteCallback.go | 2 +- zcncore/mocks/QueryResultHandle.go | 42 ++ zcncore/mocks/TransactionCallback.go | 2 +- zcncore/mocks/TransactionCommon.go | 567 ++++++++++++++++++ zcncore/mocks/TransactionScheme.go | 7 +- zcncore/mocks/WalletCallback.go | 2 +- 31 files changed, 1698 insertions(+), 24 deletions(-) create mode 100644 zboxcore/mocks/ChunkedUploadChunkReader.go create mode 100644 zboxcore/mocks/ChunkedUploadFormBuilder.go create mode 100644 zboxcore/mocks/ChunkedUploadOption.go create mode 100644 zboxcore/mocks/ChunkedUploadProgressStorer.go create mode 100644 zboxcore/mocks/DownloadOption.go create mode 100644 zboxcore/mocks/Downloader.go create mode 100644 zboxcore/mocks/FileNameBuilder.go create mode 100644 zboxcore/mocks/Hasher.go create mode 100644 zboxcore/mocks/LiveUploadOption.go create mode 100644 zboxcore/mocks/LiveUploadReader.go create mode 100644 zboxcore/mocks/M3u8Writer.go create mode 100644 zboxcore/mocks/Operationer.go create mode 100644 zboxcore/mocks/SignFunc.go create mode 100644 zcncore/mocks/FeeOption.go create mode 100644 zcncore/mocks/GetNonceCallback.go create mode 100644 zcncore/mocks/QueryResultHandle.go create mode 100644 zcncore/mocks/TransactionCommon.go diff --git a/zboxcore/mocks/AllocationChange.go b/zboxcore/mocks/AllocationChange.go index ea012fc55..d5205842a 100644 --- a/zboxcore/mocks/AllocationChange.go +++ b/zboxcore/mocks/AllocationChange.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.22.1. DO NOT EDIT. package mocks diff --git a/zboxcore/mocks/ChunkedUploadChunkReader.go b/zboxcore/mocks/ChunkedUploadChunkReader.go new file mode 100644 index 000000000..f8bd909a8 --- /dev/null +++ b/zboxcore/mocks/ChunkedUploadChunkReader.go @@ -0,0 +1,80 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import ( + sdk "github.com/0chain/gosdk/zboxcore/sdk" + mock "github.com/stretchr/testify/mock" +) + +// ChunkedUploadChunkReader is an autogenerated mock type for the ChunkedUploadChunkReader type +type ChunkedUploadChunkReader struct { + mock.Mock +} + +// Next provides a mock function with given fields: +func (_m *ChunkedUploadChunkReader) Next() (*sdk.ChunkData, error) { + ret := _m.Called() + + var r0 *sdk.ChunkData + var r1 error + if rf, ok := ret.Get(0).(func() (*sdk.ChunkData, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() *sdk.ChunkData); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*sdk.ChunkData) + } + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Read provides a mock function with given fields: buf +func (_m *ChunkedUploadChunkReader) Read(buf []byte) ([][]byte, error) { + ret := _m.Called(buf) + + var r0 [][]byte + var r1 error + if rf, ok := ret.Get(0).(func([]byte) ([][]byte, error)); ok { + return rf(buf) + } + if rf, ok := ret.Get(0).(func([]byte) [][]byte); ok { + r0 = rf(buf) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([][]byte) + } + } + + if rf, ok := ret.Get(1).(func([]byte) error); ok { + r1 = rf(buf) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +type mockConstructorTestingTNewChunkedUploadChunkReader interface { + mock.TestingT + Cleanup(func()) +} + +// NewChunkedUploadChunkReader creates a new instance of ChunkedUploadChunkReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewChunkedUploadChunkReader(t mockConstructorTestingTNewChunkedUploadChunkReader) *ChunkedUploadChunkReader { + mock := &ChunkedUploadChunkReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zboxcore/mocks/ChunkedUploadFormBuilder.go b/zboxcore/mocks/ChunkedUploadFormBuilder.go new file mode 100644 index 000000000..cc8e3d6b8 --- /dev/null +++ b/zboxcore/mocks/ChunkedUploadFormBuilder.go @@ -0,0 +1,63 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import ( + bytes "bytes" + + sdk "github.com/0chain/gosdk/zboxcore/sdk" + mock "github.com/stretchr/testify/mock" +) + +// ChunkedUploadFormBuilder is an autogenerated mock type for the ChunkedUploadFormBuilder type +type ChunkedUploadFormBuilder struct { + mock.Mock +} + +// Build provides a mock function with given fields: fileMeta, hasher, connectionID, chunkSize, chunkStartIndex, chunkEndIndex, isFinal, encryptedKey, fileChunksData, thumbnailChunkData +func (_m *ChunkedUploadFormBuilder) Build(fileMeta *sdk.FileMeta, hasher sdk.Hasher, connectionID string, chunkSize int64, chunkStartIndex int, chunkEndIndex int, isFinal bool, encryptedKey string, fileChunksData [][]byte, thumbnailChunkData []byte) (*bytes.Buffer, sdk.ChunkedUploadFormMetadata, error) { + ret := _m.Called(fileMeta, hasher, connectionID, chunkSize, chunkStartIndex, chunkEndIndex, isFinal, encryptedKey, fileChunksData, thumbnailChunkData) + + var r0 *bytes.Buffer + var r1 sdk.ChunkedUploadFormMetadata + var r2 error + if rf, ok := ret.Get(0).(func(*sdk.FileMeta, sdk.Hasher, string, int64, int, int, bool, string, [][]byte, []byte) (*bytes.Buffer, sdk.ChunkedUploadFormMetadata, error)); ok { + return rf(fileMeta, hasher, connectionID, chunkSize, chunkStartIndex, chunkEndIndex, isFinal, encryptedKey, fileChunksData, thumbnailChunkData) + } + if rf, ok := ret.Get(0).(func(*sdk.FileMeta, sdk.Hasher, string, int64, int, int, bool, string, [][]byte, []byte) *bytes.Buffer); ok { + r0 = rf(fileMeta, hasher, connectionID, chunkSize, chunkStartIndex, chunkEndIndex, isFinal, encryptedKey, fileChunksData, thumbnailChunkData) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*bytes.Buffer) + } + } + + if rf, ok := ret.Get(1).(func(*sdk.FileMeta, sdk.Hasher, string, int64, int, int, bool, string, [][]byte, []byte) sdk.ChunkedUploadFormMetadata); ok { + r1 = rf(fileMeta, hasher, connectionID, chunkSize, chunkStartIndex, chunkEndIndex, isFinal, encryptedKey, fileChunksData, thumbnailChunkData) + } else { + r1 = ret.Get(1).(sdk.ChunkedUploadFormMetadata) + } + + if rf, ok := ret.Get(2).(func(*sdk.FileMeta, sdk.Hasher, string, int64, int, int, bool, string, [][]byte, []byte) error); ok { + r2 = rf(fileMeta, hasher, connectionID, chunkSize, chunkStartIndex, chunkEndIndex, isFinal, encryptedKey, fileChunksData, thumbnailChunkData) + } else { + r2 = ret.Error(2) + } + + return r0, r1, r2 +} + +type mockConstructorTestingTNewChunkedUploadFormBuilder interface { + mock.TestingT + Cleanup(func()) +} + +// NewChunkedUploadFormBuilder creates a new instance of ChunkedUploadFormBuilder. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewChunkedUploadFormBuilder(t mockConstructorTestingTNewChunkedUploadFormBuilder) *ChunkedUploadFormBuilder { + mock := &ChunkedUploadFormBuilder{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zboxcore/mocks/ChunkedUploadOption.go b/zboxcore/mocks/ChunkedUploadOption.go new file mode 100644 index 000000000..9d088e60a --- /dev/null +++ b/zboxcore/mocks/ChunkedUploadOption.go @@ -0,0 +1,33 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import ( + sdk "github.com/0chain/gosdk/zboxcore/sdk" + mock "github.com/stretchr/testify/mock" +) + +// ChunkedUploadOption is an autogenerated mock type for the ChunkedUploadOption type +type ChunkedUploadOption struct { + mock.Mock +} + +// Execute provides a mock function with given fields: su +func (_m *ChunkedUploadOption) Execute(su *sdk.ChunkedUpload) { + _m.Called(su) +} + +type mockConstructorTestingTNewChunkedUploadOption interface { + mock.TestingT + Cleanup(func()) +} + +// NewChunkedUploadOption creates a new instance of ChunkedUploadOption. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewChunkedUploadOption(t mockConstructorTestingTNewChunkedUploadOption) *ChunkedUploadOption { + mock := &ChunkedUploadOption{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zboxcore/mocks/ChunkedUploadProgressStorer.go b/zboxcore/mocks/ChunkedUploadProgressStorer.go new file mode 100644 index 000000000..ee958bd21 --- /dev/null +++ b/zboxcore/mocks/ChunkedUploadProgressStorer.go @@ -0,0 +1,63 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import ( + sdk "github.com/0chain/gosdk/zboxcore/sdk" + mock "github.com/stretchr/testify/mock" +) + +// ChunkedUploadProgressStorer is an autogenerated mock type for the ChunkedUploadProgressStorer type +type ChunkedUploadProgressStorer struct { + mock.Mock +} + +// Load provides a mock function with given fields: id +func (_m *ChunkedUploadProgressStorer) Load(id string) *sdk.UploadProgress { + ret := _m.Called(id) + + var r0 *sdk.UploadProgress + if rf, ok := ret.Get(0).(func(string) *sdk.UploadProgress); ok { + r0 = rf(id) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*sdk.UploadProgress) + } + } + + return r0 +} + +// Remove provides a mock function with given fields: id +func (_m *ChunkedUploadProgressStorer) Remove(id string) error { + ret := _m.Called(id) + + var r0 error + if rf, ok := ret.Get(0).(func(string) error); ok { + r0 = rf(id) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// Save provides a mock function with given fields: up +func (_m *ChunkedUploadProgressStorer) Save(up sdk.UploadProgress) { + _m.Called(up) +} + +type mockConstructorTestingTNewChunkedUploadProgressStorer interface { + mock.TestingT + Cleanup(func()) +} + +// NewChunkedUploadProgressStorer creates a new instance of ChunkedUploadProgressStorer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewChunkedUploadProgressStorer(t mockConstructorTestingTNewChunkedUploadProgressStorer) *ChunkedUploadProgressStorer { + mock := &ChunkedUploadProgressStorer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zboxcore/mocks/DownloadOption.go b/zboxcore/mocks/DownloadOption.go new file mode 100644 index 000000000..d5130e4e4 --- /dev/null +++ b/zboxcore/mocks/DownloadOption.go @@ -0,0 +1,33 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import ( + sdk "github.com/0chain/gosdk/zboxcore/sdk" + mock "github.com/stretchr/testify/mock" +) + +// DownloadOption is an autogenerated mock type for the DownloadOption type +type DownloadOption struct { + mock.Mock +} + +// Execute provides a mock function with given fields: do +func (_m *DownloadOption) Execute(do *sdk.DownloadOptions) { + _m.Called(do) +} + +type mockConstructorTestingTNewDownloadOption interface { + mock.TestingT + Cleanup(func()) +} + +// NewDownloadOption creates a new instance of DownloadOption. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewDownloadOption(t mockConstructorTestingTNewDownloadOption) *DownloadOption { + mock := &DownloadOption{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zboxcore/mocks/Downloader.go b/zboxcore/mocks/Downloader.go new file mode 100644 index 000000000..d1b2af1f0 --- /dev/null +++ b/zboxcore/mocks/Downloader.go @@ -0,0 +1,72 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import ( + sdk "github.com/0chain/gosdk/zboxcore/sdk" + mock "github.com/stretchr/testify/mock" +) + +// Downloader is an autogenerated mock type for the Downloader type +type Downloader struct { + mock.Mock +} + +// GetAllocation provides a mock function with given fields: +func (_m *Downloader) GetAllocation() *sdk.Allocation { + ret := _m.Called() + + var r0 *sdk.Allocation + if rf, ok := ret.Get(0).(func() *sdk.Allocation); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*sdk.Allocation) + } + } + + return r0 +} + +// GetFileName provides a mock function with given fields: +func (_m *Downloader) GetFileName() string { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// Start provides a mock function with given fields: status, isFinal +func (_m *Downloader) Start(status sdk.StatusCallback, isFinal bool) error { + ret := _m.Called(status, isFinal) + + var r0 error + if rf, ok := ret.Get(0).(func(sdk.StatusCallback, bool) error); ok { + r0 = rf(status, isFinal) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +type mockConstructorTestingTNewDownloader interface { + mock.TestingT + Cleanup(func()) +} + +// NewDownloader creates a new instance of Downloader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewDownloader(t mockConstructorTestingTNewDownloader) *Downloader { + mock := &Downloader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zboxcore/mocks/EncryptionScheme.go b/zboxcore/mocks/EncryptionScheme.go index 834fab862..55711d55d 100644 --- a/zboxcore/mocks/EncryptionScheme.go +++ b/zboxcore/mocks/EncryptionScheme.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.22.1. DO NOT EDIT. package mocks @@ -17,6 +17,10 @@ func (_m *EncryptionScheme) Decrypt(_a0 *encryption.EncryptedMessage) ([]byte, e ret := _m.Called(_a0) var r0 []byte + var r1 error + if rf, ok := ret.Get(0).(func(*encryption.EncryptedMessage) ([]byte, error)); ok { + return rf(_a0) + } if rf, ok := ret.Get(0).(func(*encryption.EncryptedMessage) []byte); ok { r0 = rf(_a0) } else { @@ -25,7 +29,6 @@ func (_m *EncryptionScheme) Decrypt(_a0 *encryption.EncryptedMessage) ([]byte, e } } - var r1 error if rf, ok := ret.Get(1).(func(*encryption.EncryptedMessage) error); ok { r1 = rf(_a0) } else { @@ -40,6 +43,10 @@ func (_m *EncryptionScheme) Encrypt(data []byte) (*encryption.EncryptedMessage, ret := _m.Called(data) var r0 *encryption.EncryptedMessage + var r1 error + if rf, ok := ret.Get(0).(func([]byte) (*encryption.EncryptedMessage, error)); ok { + return rf(data) + } if rf, ok := ret.Get(0).(func([]byte) *encryption.EncryptedMessage); ok { r0 = rf(data) } else { @@ -48,7 +55,6 @@ func (_m *EncryptionScheme) Encrypt(data []byte) (*encryption.EncryptedMessage, } } - var r1 error if rf, ok := ret.Get(1).(func([]byte) error); ok { r1 = rf(data) } else { @@ -77,13 +83,16 @@ func (_m *EncryptionScheme) GetPrivateKey() (string, error) { ret := _m.Called() var r0 string + var r1 error + if rf, ok := ret.Get(0).(func() (string, error)); ok { + return rf() + } if rf, ok := ret.Get(0).(func() string); ok { r0 = rf() } else { r0 = ret.Get(0).(string) } - var r1 error if rf, ok := ret.Get(1).(func() error); ok { r1 = rf() } else { @@ -98,13 +107,16 @@ func (_m *EncryptionScheme) GetPublicKey() (string, error) { ret := _m.Called() var r0 string + var r1 error + if rf, ok := ret.Get(0).(func() (string, error)); ok { + return rf() + } if rf, ok := ret.Get(0).(func() string); ok { r0 = rf() } else { r0 = ret.Get(0).(string) } - var r1 error if rf, ok := ret.Get(1).(func() error); ok { r1 = rf() } else { @@ -119,13 +131,16 @@ func (_m *EncryptionScheme) GetReGenKey(encPublicKey string, tag string) (string ret := _m.Called(encPublicKey, tag) var r0 string + var r1 error + if rf, ok := ret.Get(0).(func(string, string) (string, error)); ok { + return rf(encPublicKey, tag) + } if rf, ok := ret.Get(0).(func(string, string) string); ok { r0 = rf(encPublicKey, tag) } else { r0 = ret.Get(0).(string) } - var r1 error if rf, ok := ret.Get(1).(func(string, string) error); ok { r1 = rf(encPublicKey, tag) } else { @@ -159,6 +174,10 @@ func (_m *EncryptionScheme) Initialize(mnemonic string) ([]byte, error) { ret := _m.Called(mnemonic) var r0 []byte + var r1 error + if rf, ok := ret.Get(0).(func(string) ([]byte, error)); ok { + return rf(mnemonic) + } if rf, ok := ret.Get(0).(func(string) []byte); ok { r0 = rf(mnemonic) } else { @@ -167,7 +186,6 @@ func (_m *EncryptionScheme) Initialize(mnemonic string) ([]byte, error) { } } - var r1 error if rf, ok := ret.Get(1).(func(string) error); ok { r1 = rf(mnemonic) } else { @@ -196,6 +214,10 @@ func (_m *EncryptionScheme) ReDecrypt(D *encryption.ReEncryptedMessage) ([]byte, ret := _m.Called(D) var r0 []byte + var r1 error + if rf, ok := ret.Get(0).(func(*encryption.ReEncryptedMessage) ([]byte, error)); ok { + return rf(D) + } if rf, ok := ret.Get(0).(func(*encryption.ReEncryptedMessage) []byte); ok { r0 = rf(D) } else { @@ -204,7 +226,6 @@ func (_m *EncryptionScheme) ReDecrypt(D *encryption.ReEncryptedMessage) ([]byte, } } - var r1 error if rf, ok := ret.Get(1).(func(*encryption.ReEncryptedMessage) error); ok { r1 = rf(D) } else { @@ -219,6 +240,10 @@ func (_m *EncryptionScheme) ReEncrypt(encMsg *encryption.EncryptedMessage, reGen ret := _m.Called(encMsg, reGenKey, clientPublicKey) var r0 *encryption.ReEncryptedMessage + var r1 error + if rf, ok := ret.Get(0).(func(*encryption.EncryptedMessage, string, string) (*encryption.ReEncryptedMessage, error)); ok { + return rf(encMsg, reGenKey, clientPublicKey) + } if rf, ok := ret.Get(0).(func(*encryption.EncryptedMessage, string, string) *encryption.ReEncryptedMessage); ok { r0 = rf(encMsg, reGenKey, clientPublicKey) } else { @@ -227,7 +252,6 @@ func (_m *EncryptionScheme) ReEncrypt(encMsg *encryption.EncryptedMessage, reGen } } - var r1 error if rf, ok := ret.Get(1).(func(*encryption.EncryptedMessage, string, string) error); ok { r1 = rf(encMsg, reGenKey, clientPublicKey) } else { diff --git a/zboxcore/mocks/FileNameBuilder.go b/zboxcore/mocks/FileNameBuilder.go new file mode 100644 index 000000000..b8df10942 --- /dev/null +++ b/zboxcore/mocks/FileNameBuilder.go @@ -0,0 +1,95 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import mock "github.com/stretchr/testify/mock" + +// FileNameBuilder is an autogenerated mock type for the FileNameBuilder type +type FileNameBuilder struct { + mock.Mock +} + +// ClipsFile provides a mock function with given fields: index +func (_m *FileNameBuilder) ClipsFile(index int) string { + ret := _m.Called(index) + + var r0 string + if rf, ok := ret.Get(0).(func(int) string); ok { + r0 = rf(index) + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// ClipsFileName provides a mock function with given fields: index +func (_m *FileNameBuilder) ClipsFileName(index int) string { + ret := _m.Called(index) + + var r0 string + if rf, ok := ret.Get(0).(func(int) string); ok { + r0 = rf(index) + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// FileExt provides a mock function with given fields: +func (_m *FileNameBuilder) FileExt() string { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// OutDir provides a mock function with given fields: +func (_m *FileNameBuilder) OutDir() string { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// OutFile provides a mock function with given fields: +func (_m *FileNameBuilder) OutFile() string { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +type mockConstructorTestingTNewFileNameBuilder interface { + mock.TestingT + Cleanup(func()) +} + +// NewFileNameBuilder creates a new instance of FileNameBuilder. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewFileNameBuilder(t mockConstructorTestingTNewFileNameBuilder) *FileNameBuilder { + mock := &FileNameBuilder{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zboxcore/mocks/Hasher.go b/zboxcore/mocks/Hasher.go new file mode 100644 index 000000000..1e20707a3 --- /dev/null +++ b/zboxcore/mocks/Hasher.go @@ -0,0 +1,153 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import mock "github.com/stretchr/testify/mock" + +// Hasher is an autogenerated mock type for the Hasher type +type Hasher struct { + mock.Mock +} + +// Finalize provides a mock function with given fields: +func (_m *Hasher) Finalize() error { + ret := _m.Called() + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// GetFileHash provides a mock function with given fields: +func (_m *Hasher) GetFileHash() (string, error) { + ret := _m.Called() + + var r0 string + var r1 error + if rf, ok := ret.Get(0).(func() (string, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetFixedMerkleRoot provides a mock function with given fields: +func (_m *Hasher) GetFixedMerkleRoot() (string, error) { + ret := _m.Called() + + var r0 string + var r1 error + if rf, ok := ret.Get(0).(func() (string, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetValidationRoot provides a mock function with given fields: +func (_m *Hasher) GetValidationRoot() (string, error) { + ret := _m.Called() + + var r0 string + var r1 error + if rf, ok := ret.Get(0).(func() (string, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// WriteToFile provides a mock function with given fields: buf +func (_m *Hasher) WriteToFile(buf []byte) error { + ret := _m.Called(buf) + + var r0 error + if rf, ok := ret.Get(0).(func([]byte) error); ok { + r0 = rf(buf) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// WriteToFixedMT provides a mock function with given fields: buf +func (_m *Hasher) WriteToFixedMT(buf []byte) error { + ret := _m.Called(buf) + + var r0 error + if rf, ok := ret.Get(0).(func([]byte) error); ok { + r0 = rf(buf) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// WriteToValidationMT provides a mock function with given fields: buf +func (_m *Hasher) WriteToValidationMT(buf []byte) error { + ret := _m.Called(buf) + + var r0 error + if rf, ok := ret.Get(0).(func([]byte) error); ok { + r0 = rf(buf) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +type mockConstructorTestingTNewHasher interface { + mock.TestingT + Cleanup(func()) +} + +// NewHasher creates a new instance of Hasher. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewHasher(t mockConstructorTestingTNewHasher) *Hasher { + mock := &Hasher{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zboxcore/mocks/HttpClient.go b/zboxcore/mocks/HttpClient.go index 0d9a50f09..e7a62e27c 100644 --- a/zboxcore/mocks/HttpClient.go +++ b/zboxcore/mocks/HttpClient.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.22.1. DO NOT EDIT. package mocks @@ -18,6 +18,10 @@ func (_m *HttpClient) Do(req *http.Request) (*http.Response, error) { ret := _m.Called(req) var r0 *http.Response + var r1 error + if rf, ok := ret.Get(0).(func(*http.Request) (*http.Response, error)); ok { + return rf(req) + } if rf, ok := ret.Get(0).(func(*http.Request) *http.Response); ok { r0 = rf(req) } else { @@ -26,7 +30,6 @@ func (_m *HttpClient) Do(req *http.Request) (*http.Response, error) { } } - var r1 error if rf, ok := ret.Get(1).(func(*http.Request) error); ok { r1 = rf(req) } else { diff --git a/zboxcore/mocks/LiveUploadOption.go b/zboxcore/mocks/LiveUploadOption.go new file mode 100644 index 000000000..88750015d --- /dev/null +++ b/zboxcore/mocks/LiveUploadOption.go @@ -0,0 +1,33 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import ( + sdk "github.com/0chain/gosdk/zboxcore/sdk" + mock "github.com/stretchr/testify/mock" +) + +// LiveUploadOption is an autogenerated mock type for the LiveUploadOption type +type LiveUploadOption struct { + mock.Mock +} + +// Execute provides a mock function with given fields: lu +func (_m *LiveUploadOption) Execute(lu *sdk.LiveUpload) { + _m.Called(lu) +} + +type mockConstructorTestingTNewLiveUploadOption interface { + mock.TestingT + Cleanup(func()) +} + +// NewLiveUploadOption creates a new instance of LiveUploadOption. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewLiveUploadOption(t mockConstructorTestingTNewLiveUploadOption) *LiveUploadOption { + mock := &LiveUploadOption{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zboxcore/mocks/LiveUploadReader.go b/zboxcore/mocks/LiveUploadReader.go new file mode 100644 index 000000000..3c470b5bf --- /dev/null +++ b/zboxcore/mocks/LiveUploadReader.go @@ -0,0 +1,91 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import mock "github.com/stretchr/testify/mock" + +// LiveUploadReader is an autogenerated mock type for the LiveUploadReader type +type LiveUploadReader struct { + mock.Mock +} + +// GetClipsFile provides a mock function with given fields: clipsIndex +func (_m *LiveUploadReader) GetClipsFile(clipsIndex int) string { + ret := _m.Called(clipsIndex) + + var r0 string + if rf, ok := ret.Get(0).(func(int) string); ok { + r0 = rf(clipsIndex) + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// GetClipsFileName provides a mock function with given fields: cliipsIndex +func (_m *LiveUploadReader) GetClipsFileName(cliipsIndex int) string { + ret := _m.Called(cliipsIndex) + + var r0 string + if rf, ok := ret.Get(0).(func(int) string); ok { + r0 = rf(cliipsIndex) + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// Read provides a mock function with given fields: p +func (_m *LiveUploadReader) Read(p []byte) (int, error) { + ret := _m.Called(p) + + var r0 int + var r1 error + if rf, ok := ret.Get(0).(func([]byte) (int, error)); ok { + return rf(p) + } + if rf, ok := ret.Get(0).(func([]byte) int); ok { + r0 = rf(p) + } else { + r0 = ret.Get(0).(int) + } + + if rf, ok := ret.Get(1).(func([]byte) error); ok { + r1 = rf(p) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Size provides a mock function with given fields: +func (_m *LiveUploadReader) Size() int64 { + ret := _m.Called() + + var r0 int64 + if rf, ok := ret.Get(0).(func() int64); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(int64) + } + + return r0 +} + +type mockConstructorTestingTNewLiveUploadReader interface { + mock.TestingT + Cleanup(func()) +} + +// NewLiveUploadReader creates a new instance of LiveUploadReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewLiveUploadReader(t mockConstructorTestingTNewLiveUploadReader) *LiveUploadReader { + mock := &LiveUploadReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zboxcore/mocks/M3u8Writer.go b/zboxcore/mocks/M3u8Writer.go new file mode 100644 index 000000000..858e00d7f --- /dev/null +++ b/zboxcore/mocks/M3u8Writer.go @@ -0,0 +1,101 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import mock "github.com/stretchr/testify/mock" + +// M3u8Writer is an autogenerated mock type for the M3u8Writer type +type M3u8Writer struct { + mock.Mock +} + +// Seek provides a mock function with given fields: offset, whence +func (_m *M3u8Writer) Seek(offset int64, whence int) (int64, error) { + ret := _m.Called(offset, whence) + + var r0 int64 + var r1 error + if rf, ok := ret.Get(0).(func(int64, int) (int64, error)); ok { + return rf(offset, whence) + } + if rf, ok := ret.Get(0).(func(int64, int) int64); ok { + r0 = rf(offset, whence) + } else { + r0 = ret.Get(0).(int64) + } + + if rf, ok := ret.Get(1).(func(int64, int) error); ok { + r1 = rf(offset, whence) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Sync provides a mock function with given fields: +func (_m *M3u8Writer) Sync() error { + ret := _m.Called() + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// Truncate provides a mock function with given fields: size +func (_m *M3u8Writer) Truncate(size int64) error { + ret := _m.Called(size) + + var r0 error + if rf, ok := ret.Get(0).(func(int64) error); ok { + r0 = rf(size) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// Write provides a mock function with given fields: p +func (_m *M3u8Writer) Write(p []byte) (int, error) { + ret := _m.Called(p) + + var r0 int + var r1 error + if rf, ok := ret.Get(0).(func([]byte) (int, error)); ok { + return rf(p) + } + if rf, ok := ret.Get(0).(func([]byte) int); ok { + r0 = rf(p) + } else { + r0 = ret.Get(0).(int) + } + + if rf, ok := ret.Get(1).(func([]byte) error); ok { + r1 = rf(p) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +type mockConstructorTestingTNewM3u8Writer interface { + mock.TestingT + Cleanup(func()) +} + +// NewM3u8Writer creates a new instance of M3u8Writer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewM3u8Writer(t mockConstructorTestingTNewM3u8Writer) *M3u8Writer { + mock := &M3u8Writer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zboxcore/mocks/Operationer.go b/zboxcore/mocks/Operationer.go new file mode 100644 index 000000000..1d5b4cfe1 --- /dev/null +++ b/zboxcore/mocks/Operationer.go @@ -0,0 +1,109 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import ( + allocationchange "github.com/0chain/gosdk/zboxcore/allocationchange" + fileref "github.com/0chain/gosdk/zboxcore/fileref" + + mock "github.com/stretchr/testify/mock" + + sdk "github.com/0chain/gosdk/zboxcore/sdk" + + uuid "github.com/google/uuid" + + zboxutil "github.com/0chain/gosdk/zboxcore/zboxutil" +) + +// Operationer is an autogenerated mock type for the Operationer type +type Operationer struct { + mock.Mock +} + +// Completed provides a mock function with given fields: allocObj +func (_m *Operationer) Completed(allocObj *sdk.Allocation) { + _m.Called(allocObj) +} + +// Error provides a mock function with given fields: allocObj, consensus, err +func (_m *Operationer) Error(allocObj *sdk.Allocation, consensus int, err error) { + _m.Called(allocObj, consensus, err) +} + +// Process provides a mock function with given fields: allocObj, connectionID +func (_m *Operationer) Process(allocObj *sdk.Allocation, connectionID string) ([]fileref.RefEntity, zboxutil.Uint128, error) { + ret := _m.Called(allocObj, connectionID) + + var r0 []fileref.RefEntity + var r1 zboxutil.Uint128 + var r2 error + if rf, ok := ret.Get(0).(func(*sdk.Allocation, string) ([]fileref.RefEntity, zboxutil.Uint128, error)); ok { + return rf(allocObj, connectionID) + } + if rf, ok := ret.Get(0).(func(*sdk.Allocation, string) []fileref.RefEntity); ok { + r0 = rf(allocObj, connectionID) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]fileref.RefEntity) + } + } + + if rf, ok := ret.Get(1).(func(*sdk.Allocation, string) zboxutil.Uint128); ok { + r1 = rf(allocObj, connectionID) + } else { + r1 = ret.Get(1).(zboxutil.Uint128) + } + + if rf, ok := ret.Get(2).(func(*sdk.Allocation, string) error); ok { + r2 = rf(allocObj, connectionID) + } else { + r2 = ret.Error(2) + } + + return r0, r1, r2 +} + +// Verify provides a mock function with given fields: allocObj +func (_m *Operationer) Verify(allocObj *sdk.Allocation) error { + ret := _m.Called(allocObj) + + var r0 error + if rf, ok := ret.Get(0).(func(*sdk.Allocation) error); ok { + r0 = rf(allocObj) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// buildChange provides a mock function with given fields: refs, uid +func (_m *Operationer) buildChange(refs []fileref.RefEntity, uid uuid.UUID) []allocationchange.AllocationChange { + ret := _m.Called(refs, uid) + + var r0 []allocationchange.AllocationChange + if rf, ok := ret.Get(0).(func([]fileref.RefEntity, uuid.UUID) []allocationchange.AllocationChange); ok { + r0 = rf(refs, uid) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]allocationchange.AllocationChange) + } + } + + return r0 +} + +type mockConstructorTestingTNewOperationer interface { + mock.TestingT + Cleanup(func()) +} + +// NewOperationer creates a new instance of Operationer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewOperationer(t mockConstructorTestingTNewOperationer) *Operationer { + mock := &Operationer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zboxcore/mocks/RefEntity.go b/zboxcore/mocks/RefEntity.go index 4e255d3c1..cd62950fc 100644 --- a/zboxcore/mocks/RefEntity.go +++ b/zboxcore/mocks/RefEntity.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.22.1. DO NOT EDIT. package mocks diff --git a/zboxcore/mocks/SCRestAPIHandler.go b/zboxcore/mocks/SCRestAPIHandler.go index f07f77d3e..ebccc15fc 100644 --- a/zboxcore/mocks/SCRestAPIHandler.go +++ b/zboxcore/mocks/SCRestAPIHandler.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.22.1. DO NOT EDIT. package mocks diff --git a/zboxcore/mocks/SignFunc.go b/zboxcore/mocks/SignFunc.go new file mode 100644 index 000000000..8b657fd3d --- /dev/null +++ b/zboxcore/mocks/SignFunc.go @@ -0,0 +1,49 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import mock "github.com/stretchr/testify/mock" + +// SignFunc is an autogenerated mock type for the SignFunc type +type SignFunc struct { + mock.Mock +} + +// Execute provides a mock function with given fields: hash +func (_m *SignFunc) Execute(hash string) (string, error) { + ret := _m.Called(hash) + + var r0 string + var r1 error + if rf, ok := ret.Get(0).(func(string) (string, error)); ok { + return rf(hash) + } + if rf, ok := ret.Get(0).(func(string) string); ok { + r0 = rf(hash) + } else { + r0 = ret.Get(0).(string) + } + + if rf, ok := ret.Get(1).(func(string) error); ok { + r1 = rf(hash) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +type mockConstructorTestingTNewSignFunc interface { + mock.TestingT + Cleanup(func()) +} + +// NewSignFunc creates a new instance of SignFunc. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewSignFunc(t mockConstructorTestingTNewSignFunc) *SignFunc { + mock := &SignFunc{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zboxcore/mocks/StatusCallback.go b/zboxcore/mocks/StatusCallback.go index 1baaef7a4..eb2584ff9 100644 --- a/zboxcore/mocks/StatusCallback.go +++ b/zboxcore/mocks/StatusCallback.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.22.1. DO NOT EDIT. package mocks diff --git a/zboxcore/mocks/Suite.go b/zboxcore/mocks/Suite.go index 9810840ae..96874b0cb 100644 --- a/zboxcore/mocks/Suite.go +++ b/zboxcore/mocks/Suite.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.22.1. DO NOT EDIT. package mocks diff --git a/zcncore/mocks/AuthCallback.go b/zcncore/mocks/AuthCallback.go index 1e7889d88..479e6475e 100644 --- a/zcncore/mocks/AuthCallback.go +++ b/zcncore/mocks/AuthCallback.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.22.1. DO NOT EDIT. package mocks diff --git a/zcncore/mocks/FeeOption.go b/zcncore/mocks/FeeOption.go new file mode 100644 index 000000000..9fbe7f4ed --- /dev/null +++ b/zcncore/mocks/FeeOption.go @@ -0,0 +1,30 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import mock "github.com/stretchr/testify/mock" + +// FeeOption is an autogenerated mock type for the FeeOption type +type FeeOption struct { + mock.Mock +} + +// Execute provides a mock function with given fields: _a0 +func (_m *FeeOption) Execute(_a0 *zcncore.txnFeeOption) { + _m.Called(_a0) +} + +type mockConstructorTestingTNewFeeOption interface { + mock.TestingT + Cleanup(func()) +} + +// NewFeeOption creates a new instance of FeeOption. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewFeeOption(t mockConstructorTestingTNewFeeOption) *FeeOption { + mock := &FeeOption{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zcncore/mocks/GetBalanceCallback.go b/zcncore/mocks/GetBalanceCallback.go index a18f52f85..2ca67ea8d 100644 --- a/zcncore/mocks/GetBalanceCallback.go +++ b/zcncore/mocks/GetBalanceCallback.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.22.1. DO NOT EDIT. package mocks diff --git a/zcncore/mocks/GetInfoCallback.go b/zcncore/mocks/GetInfoCallback.go index 631f241e8..9e28c1422 100644 --- a/zcncore/mocks/GetInfoCallback.go +++ b/zcncore/mocks/GetInfoCallback.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.22.1. DO NOT EDIT. package mocks diff --git a/zcncore/mocks/GetNonceCallback.go b/zcncore/mocks/GetNonceCallback.go new file mode 100644 index 000000000..6c0256589 --- /dev/null +++ b/zcncore/mocks/GetNonceCallback.go @@ -0,0 +1,30 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import mock "github.com/stretchr/testify/mock" + +// GetNonceCallback is an autogenerated mock type for the GetNonceCallback type +type GetNonceCallback struct { + mock.Mock +} + +// OnNonceAvailable provides a mock function with given fields: status, nonce, info +func (_m *GetNonceCallback) OnNonceAvailable(status int, nonce int64, info string) { + _m.Called(status, nonce, info) +} + +type mockConstructorTestingTNewGetNonceCallback interface { + mock.TestingT + Cleanup(func()) +} + +// NewGetNonceCallback creates a new instance of GetNonceCallback. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewGetNonceCallback(t mockConstructorTestingTNewGetNonceCallback) *GetNonceCallback { + mock := &GetNonceCallback{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zcncore/mocks/MSVoteCallback.go b/zcncore/mocks/MSVoteCallback.go index 69a09e5e5..db825fbfc 100644 --- a/zcncore/mocks/MSVoteCallback.go +++ b/zcncore/mocks/MSVoteCallback.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.22.1. DO NOT EDIT. package mocks diff --git a/zcncore/mocks/QueryResultHandle.go b/zcncore/mocks/QueryResultHandle.go new file mode 100644 index 000000000..bd43feefb --- /dev/null +++ b/zcncore/mocks/QueryResultHandle.go @@ -0,0 +1,42 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import ( + zcncore "github.com/0chain/gosdk/zcncore" + mock "github.com/stretchr/testify/mock" +) + +// QueryResultHandle is an autogenerated mock type for the QueryResultHandle type +type QueryResultHandle struct { + mock.Mock +} + +// Execute provides a mock function with given fields: result +func (_m *QueryResultHandle) Execute(result zcncore.QueryResult) bool { + ret := _m.Called(result) + + var r0 bool + if rf, ok := ret.Get(0).(func(zcncore.QueryResult) bool); ok { + r0 = rf(result) + } else { + r0 = ret.Get(0).(bool) + } + + return r0 +} + +type mockConstructorTestingTNewQueryResultHandle interface { + mock.TestingT + Cleanup(func()) +} + +// NewQueryResultHandle creates a new instance of QueryResultHandle. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewQueryResultHandle(t mockConstructorTestingTNewQueryResultHandle) *QueryResultHandle { + mock := &QueryResultHandle{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zcncore/mocks/TransactionCallback.go b/zcncore/mocks/TransactionCallback.go index ff51c4e7b..fa43d131e 100644 --- a/zcncore/mocks/TransactionCallback.go +++ b/zcncore/mocks/TransactionCallback.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.22.1. DO NOT EDIT. package mocks diff --git a/zcncore/mocks/TransactionCommon.go b/zcncore/mocks/TransactionCommon.go new file mode 100644 index 000000000..fd487b7b8 --- /dev/null +++ b/zcncore/mocks/TransactionCommon.go @@ -0,0 +1,567 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import ( + transaction "github.com/0chain/gosdk/core/transaction" + mock "github.com/stretchr/testify/mock" + + zcncore "github.com/0chain/gosdk/zcncore" +) + +// TransactionCommon is an autogenerated mock type for the TransactionCommon type +type TransactionCommon struct { + mock.Mock +} + +// CancelAllocation provides a mock function with given fields: allocID +func (_m *TransactionCommon) CancelAllocation(allocID string) error { + ret := _m.Called(allocID) + + var r0 error + if rf, ok := ret.Get(0).(func(string) error); ok { + r0 = rf(allocID) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// CreateAllocation provides a mock function with given fields: car, lock +func (_m *TransactionCommon) CreateAllocation(car *zcncore.CreateAllocationRequest, lock uint64) error { + ret := _m.Called(car, lock) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.CreateAllocationRequest, uint64) error); ok { + r0 = rf(car, lock) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// CreateReadPool provides a mock function with given fields: +func (_m *TransactionCommon) CreateReadPool() error { + ret := _m.Called() + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// ExecuteSmartContract provides a mock function with given fields: address, methodName, input, val, feeOpts +func (_m *TransactionCommon) ExecuteSmartContract(address string, methodName string, input interface{}, val uint64, feeOpts ...zcncore.FeeOption) (*transaction.Transaction, error) { + _va := make([]interface{}, len(feeOpts)) + for _i := range feeOpts { + _va[_i] = feeOpts[_i] + } + var _ca []interface{} + _ca = append(_ca, address, methodName, input, val) + _ca = append(_ca, _va...) + ret := _m.Called(_ca...) + + var r0 *transaction.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(string, string, interface{}, uint64, ...zcncore.FeeOption) (*transaction.Transaction, error)); ok { + return rf(address, methodName, input, val, feeOpts...) + } + if rf, ok := ret.Get(0).(func(string, string, interface{}, uint64, ...zcncore.FeeOption) *transaction.Transaction); ok { + r0 = rf(address, methodName, input, val, feeOpts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*transaction.Transaction) + } + } + + if rf, ok := ret.Get(1).(func(string, string, interface{}, uint64, ...zcncore.FeeOption) error); ok { + r1 = rf(address, methodName, input, val, feeOpts...) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// FaucetUpdateConfig provides a mock function with given fields: _a0 +func (_m *TransactionCommon) FaucetUpdateConfig(_a0 *zcncore.InputMap) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.InputMap) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// FinalizeAllocation provides a mock function with given fields: allocID +func (_m *TransactionCommon) FinalizeAllocation(allocID string) error { + ret := _m.Called(allocID) + + var r0 error + if rf, ok := ret.Get(0).(func(string) error); ok { + r0 = rf(allocID) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// GetVerifyConfirmationStatus provides a mock function with given fields: +func (_m *TransactionCommon) GetVerifyConfirmationStatus() zcncore.ConfirmationStatus { + ret := _m.Called() + + var r0 zcncore.ConfirmationStatus + if rf, ok := ret.Get(0).(func() zcncore.ConfirmationStatus); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(zcncore.ConfirmationStatus) + } + + return r0 +} + +// MinerSCCollectReward provides a mock function with given fields: providerID, providerType +func (_m *TransactionCommon) MinerSCCollectReward(providerID string, providerType zcncore.Provider) error { + ret := _m.Called(providerID, providerType) + + var r0 error + if rf, ok := ret.Get(0).(func(string, zcncore.Provider) error); ok { + r0 = rf(providerID, providerType) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// MinerSCDeleteMiner provides a mock function with given fields: _a0 +func (_m *TransactionCommon) MinerSCDeleteMiner(_a0 *zcncore.MinerSCMinerInfo) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.MinerSCMinerInfo) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// MinerSCDeleteSharder provides a mock function with given fields: _a0 +func (_m *TransactionCommon) MinerSCDeleteSharder(_a0 *zcncore.MinerSCMinerInfo) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.MinerSCMinerInfo) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// MinerSCKill provides a mock function with given fields: providerID, providerType +func (_m *TransactionCommon) MinerSCKill(providerID string, providerType zcncore.Provider) error { + ret := _m.Called(providerID, providerType) + + var r0 error + if rf, ok := ret.Get(0).(func(string, zcncore.Provider) error); ok { + r0 = rf(providerID, providerType) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// MinerSCLock provides a mock function with given fields: providerId, providerType, lock +func (_m *TransactionCommon) MinerSCLock(providerId string, providerType zcncore.Provider, lock uint64) error { + ret := _m.Called(providerId, providerType, lock) + + var r0 error + if rf, ok := ret.Get(0).(func(string, zcncore.Provider, uint64) error); ok { + r0 = rf(providerId, providerType, lock) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// MinerSCMinerSettings provides a mock function with given fields: _a0 +func (_m *TransactionCommon) MinerSCMinerSettings(_a0 *zcncore.MinerSCMinerInfo) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.MinerSCMinerInfo) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// MinerSCSharderSettings provides a mock function with given fields: _a0 +func (_m *TransactionCommon) MinerSCSharderSettings(_a0 *zcncore.MinerSCMinerInfo) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.MinerSCMinerInfo) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// MinerSCUnlock provides a mock function with given fields: providerId, providerType +func (_m *TransactionCommon) MinerSCUnlock(providerId string, providerType zcncore.Provider) error { + ret := _m.Called(providerId, providerType) + + var r0 error + if rf, ok := ret.Get(0).(func(string, zcncore.Provider) error); ok { + r0 = rf(providerId, providerType) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// MinerScUpdateConfig provides a mock function with given fields: _a0 +func (_m *TransactionCommon) MinerScUpdateConfig(_a0 *zcncore.InputMap) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.InputMap) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// MinerScUpdateGlobals provides a mock function with given fields: _a0 +func (_m *TransactionCommon) MinerScUpdateGlobals(_a0 *zcncore.InputMap) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.InputMap) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// ReadPoolLock provides a mock function with given fields: allocID, blobberID, duration, lock +func (_m *TransactionCommon) ReadPoolLock(allocID string, blobberID string, duration int64, lock uint64) error { + ret := _m.Called(allocID, blobberID, duration, lock) + + var r0 error + if rf, ok := ret.Get(0).(func(string, string, int64, uint64) error); ok { + r0 = rf(allocID, blobberID, duration, lock) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// ReadPoolUnlock provides a mock function with given fields: +func (_m *TransactionCommon) ReadPoolUnlock() error { + ret := _m.Called() + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// RegisterMultiSig provides a mock function with given fields: walletstr, mswallet +func (_m *TransactionCommon) RegisterMultiSig(walletstr string, mswallet string) error { + ret := _m.Called(walletstr, mswallet) + + var r0 error + if rf, ok := ret.Get(0).(func(string, string) error); ok { + r0 = rf(walletstr, mswallet) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// Send provides a mock function with given fields: toClientID, val, desc +func (_m *TransactionCommon) Send(toClientID string, val uint64, desc string) error { + ret := _m.Called(toClientID, val, desc) + + var r0 error + if rf, ok := ret.Get(0).(func(string, uint64, string) error); ok { + r0 = rf(toClientID, val, desc) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// StakePoolLock provides a mock function with given fields: providerId, providerType, lock +func (_m *TransactionCommon) StakePoolLock(providerId string, providerType zcncore.Provider, lock uint64) error { + ret := _m.Called(providerId, providerType, lock) + + var r0 error + if rf, ok := ret.Get(0).(func(string, zcncore.Provider, uint64) error); ok { + r0 = rf(providerId, providerType, lock) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// StakePoolUnlock provides a mock function with given fields: providerId, providerType +func (_m *TransactionCommon) StakePoolUnlock(providerId string, providerType zcncore.Provider) error { + ret := _m.Called(providerId, providerType) + + var r0 error + if rf, ok := ret.Get(0).(func(string, zcncore.Provider) error); ok { + r0 = rf(providerId, providerType) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// StorageSCCollectReward provides a mock function with given fields: providerID, providerType +func (_m *TransactionCommon) StorageSCCollectReward(providerID string, providerType zcncore.Provider) error { + ret := _m.Called(providerID, providerType) + + var r0 error + if rf, ok := ret.Get(0).(func(string, zcncore.Provider) error); ok { + r0 = rf(providerID, providerType) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// StorageScUpdateConfig provides a mock function with given fields: _a0 +func (_m *TransactionCommon) StorageScUpdateConfig(_a0 *zcncore.InputMap) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.InputMap) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// UpdateAllocation provides a mock function with given fields: allocID, sizeDiff, expirationDiff, lock +func (_m *TransactionCommon) UpdateAllocation(allocID string, sizeDiff int64, expirationDiff int64, lock uint64) error { + ret := _m.Called(allocID, sizeDiff, expirationDiff, lock) + + var r0 error + if rf, ok := ret.Get(0).(func(string, int64, int64, uint64) error); ok { + r0 = rf(allocID, sizeDiff, expirationDiff, lock) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// UpdateBlobberSettings provides a mock function with given fields: blobber +func (_m *TransactionCommon) UpdateBlobberSettings(blobber *zcncore.Blobber) error { + ret := _m.Called(blobber) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.Blobber) error); ok { + r0 = rf(blobber) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// UpdateValidatorSettings provides a mock function with given fields: validator +func (_m *TransactionCommon) UpdateValidatorSettings(validator *zcncore.Validator) error { + ret := _m.Called(validator) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.Validator) error); ok { + r0 = rf(validator) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// VestingAdd provides a mock function with given fields: ar, value +func (_m *TransactionCommon) VestingAdd(ar *zcncore.VestingAddRequest, value uint64) error { + ret := _m.Called(ar, value) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.VestingAddRequest, uint64) error); ok { + r0 = rf(ar, value) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// VestingUpdateConfig provides a mock function with given fields: _a0 +func (_m *TransactionCommon) VestingUpdateConfig(_a0 *zcncore.InputMap) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.InputMap) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// WritePoolLock provides a mock function with given fields: allocID, blobberID, duration, lock +func (_m *TransactionCommon) WritePoolLock(allocID string, blobberID string, duration int64, lock uint64) error { + ret := _m.Called(allocID, blobberID, duration, lock) + + var r0 error + if rf, ok := ret.Get(0).(func(string, string, int64, uint64) error); ok { + r0 = rf(allocID, blobberID, duration, lock) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// WritePoolUnlock provides a mock function with given fields: allocID +func (_m *TransactionCommon) WritePoolUnlock(allocID string) error { + ret := _m.Called(allocID) + + var r0 error + if rf, ok := ret.Get(0).(func(string) error); ok { + r0 = rf(allocID) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// ZCNSCAddAuthorizer provides a mock function with given fields: _a0 +func (_m *TransactionCommon) ZCNSCAddAuthorizer(_a0 *zcncore.AddAuthorizerPayload) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.AddAuthorizerPayload) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// ZCNSCAuthorizerHealthCheck provides a mock function with given fields: _a0 +func (_m *TransactionCommon) ZCNSCAuthorizerHealthCheck(_a0 *zcncore.AuthorizerHealthCheckPayload) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.AuthorizerHealthCheckPayload) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// ZCNSCDeleteAuthorizer provides a mock function with given fields: _a0 +func (_m *TransactionCommon) ZCNSCDeleteAuthorizer(_a0 *zcncore.DeleteAuthorizerPayload) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.DeleteAuthorizerPayload) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// ZCNSCUpdateAuthorizerConfig provides a mock function with given fields: _a0 +func (_m *TransactionCommon) ZCNSCUpdateAuthorizerConfig(_a0 *zcncore.AuthorizerNode) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.AuthorizerNode) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// ZCNSCUpdateGlobalConfig provides a mock function with given fields: _a0 +func (_m *TransactionCommon) ZCNSCUpdateGlobalConfig(_a0 *zcncore.InputMap) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.InputMap) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +type mockConstructorTestingTNewTransactionCommon interface { + mock.TestingT + Cleanup(func()) +} + +// NewTransactionCommon creates a new instance of TransactionCommon. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewTransactionCommon(t mockConstructorTestingTNewTransactionCommon) *TransactionCommon { + mock := &TransactionCommon{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zcncore/mocks/TransactionScheme.go b/zcncore/mocks/TransactionScheme.go index 72fc7f621..3cd02f514 100644 --- a/zcncore/mocks/TransactionScheme.go +++ b/zcncore/mocks/TransactionScheme.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.22.1. DO NOT EDIT. package mocks @@ -82,6 +82,10 @@ func (_m *TransactionScheme) ExecuteSmartContract(address string, methodName str ret := _m.Called(_ca...) var r0 *transaction.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(string, string, interface{}, uint64, ...zcncore.FeeOption) (*transaction.Transaction, error)); ok { + return rf(address, methodName, input, val, feeOpts...) + } if rf, ok := ret.Get(0).(func(string, string, interface{}, uint64, ...zcncore.FeeOption) *transaction.Transaction); ok { r0 = rf(address, methodName, input, val, feeOpts...) } else { @@ -90,7 +94,6 @@ func (_m *TransactionScheme) ExecuteSmartContract(address string, methodName str } } - var r1 error if rf, ok := ret.Get(1).(func(string, string, interface{}, uint64, ...zcncore.FeeOption) error); ok { r1 = rf(address, methodName, input, val, feeOpts...) } else { diff --git a/zcncore/mocks/WalletCallback.go b/zcncore/mocks/WalletCallback.go index 2cc410d17..267600db9 100644 --- a/zcncore/mocks/WalletCallback.go +++ b/zcncore/mocks/WalletCallback.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.22.1. DO NOT EDIT. package mocks From f54cd798a4b6f7603267ed42f55a7c7d97f97745 Mon Sep 17 00:00:00 2001 From: YarikRevich Date: Sat, 26 Aug 2023 15:09:02 +0200 Subject: [PATCH 014/134] fix: fixed bugs --- zcnbridge/bridge_test.go | 6 ------ 1 file changed, 6 deletions(-) diff --git a/zcnbridge/bridge_test.go b/zcnbridge/bridge_test.go index 2bc31878a..ce5ab810f 100644 --- a/zcnbridge/bridge_test.go +++ b/zcnbridge/bridge_test.go @@ -299,12 +299,6 @@ func Test_ZCNBridge(t *testing.T) { bridgeClient := getBridgeClient(ethereumClient, transactionProvider, keyStore) - t.Cleanup(func() { - if err := os.RemoveAll(testKeyStoreLocation); err != nil { - log.Fatalln(err) - } - }) - t.Run("should update authorizer config.", func(t *testing.T) { source := &authorizerNodeSource{ ID: "12345678", From b4b0d6c5d069c0ed6ee6d9e547da24cc0a1cb3d7 Mon Sep 17 00:00:00 2001 From: YarikRevich Date: Sat, 26 Aug 2023 16:49:28 +0200 Subject: [PATCH 015/134] fix: fixed bugs --- zcncore/transaction_base.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/zcncore/transaction_base.go b/zcncore/transaction_base.go index 2569f55ad..ea9bbd80b 100644 --- a/zcncore/transaction_base.go +++ b/zcncore/transaction_base.go @@ -435,7 +435,7 @@ func (t *Transaction) StoreData(data string) error { return nil } -type txnFeeOption struct { +type TxnFeeOption struct { // stop estimate txn fee, usually if txn fee was 0, the createSmartContractTxn method would // estimate the txn fee by calling API from 0chain network. With this option, we could force // the txn to have zero fee for those exempt transactions. @@ -443,11 +443,11 @@ type txnFeeOption struct { } // FeeOption represents txn fee related option type -type FeeOption func(*txnFeeOption) +type FeeOption func(*TxnFeeOption) // WithNoEstimateFee would prevent txn fee estimation from remote func WithNoEstimateFee() FeeOption { - return func(o *txnFeeOption) { + return func(o *TxnFeeOption) { o.noEstimateFee = true } } @@ -468,7 +468,7 @@ func (t *Transaction) createSmartContractTxn(address, methodName string, input i return nil } - tf := &txnFeeOption{} + tf := &TxnFeeOption{} for _, opt := range opts { opt(tf) } From c2f314ca4757420da7a4e0b1cdb24fc43bcae806 Mon Sep 17 00:00:00 2001 From: YarikRevich Date: Sat, 26 Aug 2023 16:50:03 +0200 Subject: [PATCH 016/134] fix: fixed bugs --- zboxcore/mocks/ChunkedUploadFormBuilder.go | 22 ++++----- zboxcore/mocks/EncryptionScheme.go | 42 ++++++++++++++++ zboxcore/mocks/codec.go | 56 ---------------------- zcncore/mocks/FeeOption.go | 7 ++- zcncore/mocks/GetUSDInfoCallback.go | 15 ------ 5 files changed, 58 insertions(+), 84 deletions(-) delete mode 100644 zboxcore/mocks/codec.go delete mode 100644 zcncore/mocks/GetUSDInfoCallback.go diff --git a/zboxcore/mocks/ChunkedUploadFormBuilder.go b/zboxcore/mocks/ChunkedUploadFormBuilder.go index cc8e3d6b8..96b05f33d 100644 --- a/zboxcore/mocks/ChunkedUploadFormBuilder.go +++ b/zboxcore/mocks/ChunkedUploadFormBuilder.go @@ -14,32 +14,32 @@ type ChunkedUploadFormBuilder struct { mock.Mock } -// Build provides a mock function with given fields: fileMeta, hasher, connectionID, chunkSize, chunkStartIndex, chunkEndIndex, isFinal, encryptedKey, fileChunksData, thumbnailChunkData -func (_m *ChunkedUploadFormBuilder) Build(fileMeta *sdk.FileMeta, hasher sdk.Hasher, connectionID string, chunkSize int64, chunkStartIndex int, chunkEndIndex int, isFinal bool, encryptedKey string, fileChunksData [][]byte, thumbnailChunkData []byte) (*bytes.Buffer, sdk.ChunkedUploadFormMetadata, error) { - ret := _m.Called(fileMeta, hasher, connectionID, chunkSize, chunkStartIndex, chunkEndIndex, isFinal, encryptedKey, fileChunksData, thumbnailChunkData) +// Build provides a mock function with given fields: fileMeta, hasher, connectionID, chunkSize, chunkStartIndex, chunkEndIndex, isFinal, encryptedKey, encryptedKeyPoint, fileChunksData, thumbnailChunkData, shardSize +func (_m *ChunkedUploadFormBuilder) Build(fileMeta *sdk.FileMeta, hasher sdk.Hasher, connectionID string, chunkSize int64, chunkStartIndex int, chunkEndIndex int, isFinal bool, encryptedKey string, encryptedKeyPoint string, fileChunksData [][]byte, thumbnailChunkData []byte, shardSize int64) (*bytes.Buffer, sdk.ChunkedUploadFormMetadata, error) { + ret := _m.Called(fileMeta, hasher, connectionID, chunkSize, chunkStartIndex, chunkEndIndex, isFinal, encryptedKey, encryptedKeyPoint, fileChunksData, thumbnailChunkData, shardSize) var r0 *bytes.Buffer var r1 sdk.ChunkedUploadFormMetadata var r2 error - if rf, ok := ret.Get(0).(func(*sdk.FileMeta, sdk.Hasher, string, int64, int, int, bool, string, [][]byte, []byte) (*bytes.Buffer, sdk.ChunkedUploadFormMetadata, error)); ok { - return rf(fileMeta, hasher, connectionID, chunkSize, chunkStartIndex, chunkEndIndex, isFinal, encryptedKey, fileChunksData, thumbnailChunkData) + if rf, ok := ret.Get(0).(func(*sdk.FileMeta, sdk.Hasher, string, int64, int, int, bool, string, string, [][]byte, []byte, int64) (*bytes.Buffer, sdk.ChunkedUploadFormMetadata, error)); ok { + return rf(fileMeta, hasher, connectionID, chunkSize, chunkStartIndex, chunkEndIndex, isFinal, encryptedKey, encryptedKeyPoint, fileChunksData, thumbnailChunkData, shardSize) } - if rf, ok := ret.Get(0).(func(*sdk.FileMeta, sdk.Hasher, string, int64, int, int, bool, string, [][]byte, []byte) *bytes.Buffer); ok { - r0 = rf(fileMeta, hasher, connectionID, chunkSize, chunkStartIndex, chunkEndIndex, isFinal, encryptedKey, fileChunksData, thumbnailChunkData) + if rf, ok := ret.Get(0).(func(*sdk.FileMeta, sdk.Hasher, string, int64, int, int, bool, string, string, [][]byte, []byte, int64) *bytes.Buffer); ok { + r0 = rf(fileMeta, hasher, connectionID, chunkSize, chunkStartIndex, chunkEndIndex, isFinal, encryptedKey, encryptedKeyPoint, fileChunksData, thumbnailChunkData, shardSize) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*bytes.Buffer) } } - if rf, ok := ret.Get(1).(func(*sdk.FileMeta, sdk.Hasher, string, int64, int, int, bool, string, [][]byte, []byte) sdk.ChunkedUploadFormMetadata); ok { - r1 = rf(fileMeta, hasher, connectionID, chunkSize, chunkStartIndex, chunkEndIndex, isFinal, encryptedKey, fileChunksData, thumbnailChunkData) + if rf, ok := ret.Get(1).(func(*sdk.FileMeta, sdk.Hasher, string, int64, int, int, bool, string, string, [][]byte, []byte, int64) sdk.ChunkedUploadFormMetadata); ok { + r1 = rf(fileMeta, hasher, connectionID, chunkSize, chunkStartIndex, chunkEndIndex, isFinal, encryptedKey, encryptedKeyPoint, fileChunksData, thumbnailChunkData, shardSize) } else { r1 = ret.Get(1).(sdk.ChunkedUploadFormMetadata) } - if rf, ok := ret.Get(2).(func(*sdk.FileMeta, sdk.Hasher, string, int64, int, int, bool, string, [][]byte, []byte) error); ok { - r2 = rf(fileMeta, hasher, connectionID, chunkSize, chunkStartIndex, chunkEndIndex, isFinal, encryptedKey, fileChunksData, thumbnailChunkData) + if rf, ok := ret.Get(2).(func(*sdk.FileMeta, sdk.Hasher, string, int64, int, int, bool, string, string, [][]byte, []byte, int64) error); ok { + r2 = rf(fileMeta, hasher, connectionID, chunkSize, chunkStartIndex, chunkEndIndex, isFinal, encryptedKey, encryptedKeyPoint, fileChunksData, thumbnailChunkData, shardSize) } else { r2 = ret.Error(2) } diff --git a/zboxcore/mocks/EncryptionScheme.go b/zboxcore/mocks/EncryptionScheme.go index 55711d55d..bbd4f0286 100644 --- a/zboxcore/mocks/EncryptionScheme.go +++ b/zboxcore/mocks/EncryptionScheme.go @@ -78,6 +78,20 @@ func (_m *EncryptionScheme) GetEncryptedKey() string { return r0 } +// GetEncryptedKeyPoint provides a mock function with given fields: +func (_m *EncryptionScheme) GetEncryptedKeyPoint() string { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + // GetPrivateKey provides a mock function with given fields: func (_m *EncryptionScheme) GetPrivateKey() (string, error) { ret := _m.Called() @@ -164,11 +178,39 @@ func (_m *EncryptionScheme) InitForDecryption(tag string, encryptedKey string) e return r0 } +// InitForDecryptionWithPoint provides a mock function with given fields: tag, point +func (_m *EncryptionScheme) InitForDecryptionWithPoint(tag string, point string) error { + ret := _m.Called(tag, point) + + var r0 error + if rf, ok := ret.Get(0).(func(string, string) error); ok { + r0 = rf(tag, point) + } else { + r0 = ret.Error(0) + } + + return r0 +} + // InitForEncryption provides a mock function with given fields: tag func (_m *EncryptionScheme) InitForEncryption(tag string) { _m.Called(tag) } +// InitForEncryptionWithPoint provides a mock function with given fields: tag, point +func (_m *EncryptionScheme) InitForEncryptionWithPoint(tag string, point string) error { + ret := _m.Called(tag, point) + + var r0 error + if rf, ok := ret.Get(0).(func(string, string) error); ok { + r0 = rf(tag, point) + } else { + r0 = ret.Error(0) + } + + return r0 +} + // Initialize provides a mock function with given fields: mnemonic func (_m *EncryptionScheme) Initialize(mnemonic string) ([]byte, error) { ret := _m.Called(mnemonic) diff --git a/zboxcore/mocks/codec.go b/zboxcore/mocks/codec.go deleted file mode 100644 index 8a9611e7e..000000000 --- a/zboxcore/mocks/codec.go +++ /dev/null @@ -1,56 +0,0 @@ -// Code generated by mockery v0.0.0-dev. DO NOT EDIT. - -package mocks - -import mock "github.com/stretchr/testify/mock" - -// codec is an autogenerated mock type for the codec type -type codec struct { - mock.Mock -} - -// Decode provides a mock function with given fields: in -func (_m *codec) Decode(in [][]byte) ([]byte, error) { - ret := _m.Called(in) - - var r0 []byte - if rf, ok := ret.Get(0).(func([][]byte) []byte); ok { - r0 = rf(in) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func([][]byte) error); ok { - r1 = rf(in) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// Encode provides a mock function with given fields: in -func (_m *codec) Encode(in []byte) ([][]byte, error) { - ret := _m.Called(in) - - var r0 [][]byte - if rf, ok := ret.Get(0).(func([]byte) [][]byte); ok { - r0 = rf(in) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([][]byte) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func([]byte) error); ok { - r1 = rf(in) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} diff --git a/zcncore/mocks/FeeOption.go b/zcncore/mocks/FeeOption.go index 9fbe7f4ed..38116bbf2 100644 --- a/zcncore/mocks/FeeOption.go +++ b/zcncore/mocks/FeeOption.go @@ -2,7 +2,10 @@ package mocks -import mock "github.com/stretchr/testify/mock" +import ( + zcncore "github.com/0chain/gosdk/zcncore" + mock "github.com/stretchr/testify/mock" +) // FeeOption is an autogenerated mock type for the FeeOption type type FeeOption struct { @@ -10,7 +13,7 @@ type FeeOption struct { } // Execute provides a mock function with given fields: _a0 -func (_m *FeeOption) Execute(_a0 *zcncore.txnFeeOption) { +func (_m *FeeOption) Execute(_a0 *zcncore.TxnFeeOption) { _m.Called(_a0) } diff --git a/zcncore/mocks/GetUSDInfoCallback.go b/zcncore/mocks/GetUSDInfoCallback.go deleted file mode 100644 index 90a801c46..000000000 --- a/zcncore/mocks/GetUSDInfoCallback.go +++ /dev/null @@ -1,15 +0,0 @@ -// Code generated by mockery v0.0.0-dev. DO NOT EDIT. - -package mocks - -import mock "github.com/stretchr/testify/mock" - -// GetUSDInfoCallback is an autogenerated mock type for the GetUSDInfoCallback type -type GetUSDInfoCallback struct { - mock.Mock -} - -// OnUSDInfoAvailable provides a mock function with given fields: status, info, err -func (_m *GetUSDInfoCallback) OnUSDInfoAvailable(status int, info string, err string) { - _m.Called(status, info, err) -} From 5b131ed9e58fb6309e620a50d345b7d6a00a6424 Mon Sep 17 00:00:00 2001 From: YarikRevich Date: Tue, 29 Aug 2023 20:54:36 +0200 Subject: [PATCH 017/134] fix: fixed bugs --- zboxcore/mocks/ChunkedUploadChunkReader.go | 80 ------------- zboxcore/mocks/ChunkedUploadFormBuilder.go | 63 ---------- zboxcore/mocks/ChunkedUploadOption.go | 33 ------ zboxcore/mocks/ChunkedUploadProgressStorer.go | 63 ---------- zboxcore/mocks/DownloadOption.go | 33 ------ zboxcore/mocks/Downloader.go | 72 ------------ zboxcore/mocks/LiveUploadOption.go | 33 ------ zboxcore/mocks/Operationer.go | 109 ------------------ 8 files changed, 486 deletions(-) delete mode 100644 zboxcore/mocks/ChunkedUploadChunkReader.go delete mode 100644 zboxcore/mocks/ChunkedUploadFormBuilder.go delete mode 100644 zboxcore/mocks/ChunkedUploadOption.go delete mode 100644 zboxcore/mocks/ChunkedUploadProgressStorer.go delete mode 100644 zboxcore/mocks/DownloadOption.go delete mode 100644 zboxcore/mocks/Downloader.go delete mode 100644 zboxcore/mocks/LiveUploadOption.go delete mode 100644 zboxcore/mocks/Operationer.go diff --git a/zboxcore/mocks/ChunkedUploadChunkReader.go b/zboxcore/mocks/ChunkedUploadChunkReader.go deleted file mode 100644 index f8bd909a8..000000000 --- a/zboxcore/mocks/ChunkedUploadChunkReader.go +++ /dev/null @@ -1,80 +0,0 @@ -// Code generated by mockery v2.22.1. DO NOT EDIT. - -package mocks - -import ( - sdk "github.com/0chain/gosdk/zboxcore/sdk" - mock "github.com/stretchr/testify/mock" -) - -// ChunkedUploadChunkReader is an autogenerated mock type for the ChunkedUploadChunkReader type -type ChunkedUploadChunkReader struct { - mock.Mock -} - -// Next provides a mock function with given fields: -func (_m *ChunkedUploadChunkReader) Next() (*sdk.ChunkData, error) { - ret := _m.Called() - - var r0 *sdk.ChunkData - var r1 error - if rf, ok := ret.Get(0).(func() (*sdk.ChunkData, error)); ok { - return rf() - } - if rf, ok := ret.Get(0).(func() *sdk.ChunkData); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*sdk.ChunkData) - } - } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// Read provides a mock function with given fields: buf -func (_m *ChunkedUploadChunkReader) Read(buf []byte) ([][]byte, error) { - ret := _m.Called(buf) - - var r0 [][]byte - var r1 error - if rf, ok := ret.Get(0).(func([]byte) ([][]byte, error)); ok { - return rf(buf) - } - if rf, ok := ret.Get(0).(func([]byte) [][]byte); ok { - r0 = rf(buf) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([][]byte) - } - } - - if rf, ok := ret.Get(1).(func([]byte) error); ok { - r1 = rf(buf) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -type mockConstructorTestingTNewChunkedUploadChunkReader interface { - mock.TestingT - Cleanup(func()) -} - -// NewChunkedUploadChunkReader creates a new instance of ChunkedUploadChunkReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewChunkedUploadChunkReader(t mockConstructorTestingTNewChunkedUploadChunkReader) *ChunkedUploadChunkReader { - mock := &ChunkedUploadChunkReader{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/zboxcore/mocks/ChunkedUploadFormBuilder.go b/zboxcore/mocks/ChunkedUploadFormBuilder.go deleted file mode 100644 index 96b05f33d..000000000 --- a/zboxcore/mocks/ChunkedUploadFormBuilder.go +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by mockery v2.22.1. DO NOT EDIT. - -package mocks - -import ( - bytes "bytes" - - sdk "github.com/0chain/gosdk/zboxcore/sdk" - mock "github.com/stretchr/testify/mock" -) - -// ChunkedUploadFormBuilder is an autogenerated mock type for the ChunkedUploadFormBuilder type -type ChunkedUploadFormBuilder struct { - mock.Mock -} - -// Build provides a mock function with given fields: fileMeta, hasher, connectionID, chunkSize, chunkStartIndex, chunkEndIndex, isFinal, encryptedKey, encryptedKeyPoint, fileChunksData, thumbnailChunkData, shardSize -func (_m *ChunkedUploadFormBuilder) Build(fileMeta *sdk.FileMeta, hasher sdk.Hasher, connectionID string, chunkSize int64, chunkStartIndex int, chunkEndIndex int, isFinal bool, encryptedKey string, encryptedKeyPoint string, fileChunksData [][]byte, thumbnailChunkData []byte, shardSize int64) (*bytes.Buffer, sdk.ChunkedUploadFormMetadata, error) { - ret := _m.Called(fileMeta, hasher, connectionID, chunkSize, chunkStartIndex, chunkEndIndex, isFinal, encryptedKey, encryptedKeyPoint, fileChunksData, thumbnailChunkData, shardSize) - - var r0 *bytes.Buffer - var r1 sdk.ChunkedUploadFormMetadata - var r2 error - if rf, ok := ret.Get(0).(func(*sdk.FileMeta, sdk.Hasher, string, int64, int, int, bool, string, string, [][]byte, []byte, int64) (*bytes.Buffer, sdk.ChunkedUploadFormMetadata, error)); ok { - return rf(fileMeta, hasher, connectionID, chunkSize, chunkStartIndex, chunkEndIndex, isFinal, encryptedKey, encryptedKeyPoint, fileChunksData, thumbnailChunkData, shardSize) - } - if rf, ok := ret.Get(0).(func(*sdk.FileMeta, sdk.Hasher, string, int64, int, int, bool, string, string, [][]byte, []byte, int64) *bytes.Buffer); ok { - r0 = rf(fileMeta, hasher, connectionID, chunkSize, chunkStartIndex, chunkEndIndex, isFinal, encryptedKey, encryptedKeyPoint, fileChunksData, thumbnailChunkData, shardSize) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*bytes.Buffer) - } - } - - if rf, ok := ret.Get(1).(func(*sdk.FileMeta, sdk.Hasher, string, int64, int, int, bool, string, string, [][]byte, []byte, int64) sdk.ChunkedUploadFormMetadata); ok { - r1 = rf(fileMeta, hasher, connectionID, chunkSize, chunkStartIndex, chunkEndIndex, isFinal, encryptedKey, encryptedKeyPoint, fileChunksData, thumbnailChunkData, shardSize) - } else { - r1 = ret.Get(1).(sdk.ChunkedUploadFormMetadata) - } - - if rf, ok := ret.Get(2).(func(*sdk.FileMeta, sdk.Hasher, string, int64, int, int, bool, string, string, [][]byte, []byte, int64) error); ok { - r2 = rf(fileMeta, hasher, connectionID, chunkSize, chunkStartIndex, chunkEndIndex, isFinal, encryptedKey, encryptedKeyPoint, fileChunksData, thumbnailChunkData, shardSize) - } else { - r2 = ret.Error(2) - } - - return r0, r1, r2 -} - -type mockConstructorTestingTNewChunkedUploadFormBuilder interface { - mock.TestingT - Cleanup(func()) -} - -// NewChunkedUploadFormBuilder creates a new instance of ChunkedUploadFormBuilder. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewChunkedUploadFormBuilder(t mockConstructorTestingTNewChunkedUploadFormBuilder) *ChunkedUploadFormBuilder { - mock := &ChunkedUploadFormBuilder{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/zboxcore/mocks/ChunkedUploadOption.go b/zboxcore/mocks/ChunkedUploadOption.go deleted file mode 100644 index 9d088e60a..000000000 --- a/zboxcore/mocks/ChunkedUploadOption.go +++ /dev/null @@ -1,33 +0,0 @@ -// Code generated by mockery v2.22.1. DO NOT EDIT. - -package mocks - -import ( - sdk "github.com/0chain/gosdk/zboxcore/sdk" - mock "github.com/stretchr/testify/mock" -) - -// ChunkedUploadOption is an autogenerated mock type for the ChunkedUploadOption type -type ChunkedUploadOption struct { - mock.Mock -} - -// Execute provides a mock function with given fields: su -func (_m *ChunkedUploadOption) Execute(su *sdk.ChunkedUpload) { - _m.Called(su) -} - -type mockConstructorTestingTNewChunkedUploadOption interface { - mock.TestingT - Cleanup(func()) -} - -// NewChunkedUploadOption creates a new instance of ChunkedUploadOption. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewChunkedUploadOption(t mockConstructorTestingTNewChunkedUploadOption) *ChunkedUploadOption { - mock := &ChunkedUploadOption{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/zboxcore/mocks/ChunkedUploadProgressStorer.go b/zboxcore/mocks/ChunkedUploadProgressStorer.go deleted file mode 100644 index ee958bd21..000000000 --- a/zboxcore/mocks/ChunkedUploadProgressStorer.go +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by mockery v2.22.1. DO NOT EDIT. - -package mocks - -import ( - sdk "github.com/0chain/gosdk/zboxcore/sdk" - mock "github.com/stretchr/testify/mock" -) - -// ChunkedUploadProgressStorer is an autogenerated mock type for the ChunkedUploadProgressStorer type -type ChunkedUploadProgressStorer struct { - mock.Mock -} - -// Load provides a mock function with given fields: id -func (_m *ChunkedUploadProgressStorer) Load(id string) *sdk.UploadProgress { - ret := _m.Called(id) - - var r0 *sdk.UploadProgress - if rf, ok := ret.Get(0).(func(string) *sdk.UploadProgress); ok { - r0 = rf(id) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*sdk.UploadProgress) - } - } - - return r0 -} - -// Remove provides a mock function with given fields: id -func (_m *ChunkedUploadProgressStorer) Remove(id string) error { - ret := _m.Called(id) - - var r0 error - if rf, ok := ret.Get(0).(func(string) error); ok { - r0 = rf(id) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// Save provides a mock function with given fields: up -func (_m *ChunkedUploadProgressStorer) Save(up sdk.UploadProgress) { - _m.Called(up) -} - -type mockConstructorTestingTNewChunkedUploadProgressStorer interface { - mock.TestingT - Cleanup(func()) -} - -// NewChunkedUploadProgressStorer creates a new instance of ChunkedUploadProgressStorer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewChunkedUploadProgressStorer(t mockConstructorTestingTNewChunkedUploadProgressStorer) *ChunkedUploadProgressStorer { - mock := &ChunkedUploadProgressStorer{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/zboxcore/mocks/DownloadOption.go b/zboxcore/mocks/DownloadOption.go deleted file mode 100644 index d5130e4e4..000000000 --- a/zboxcore/mocks/DownloadOption.go +++ /dev/null @@ -1,33 +0,0 @@ -// Code generated by mockery v2.22.1. DO NOT EDIT. - -package mocks - -import ( - sdk "github.com/0chain/gosdk/zboxcore/sdk" - mock "github.com/stretchr/testify/mock" -) - -// DownloadOption is an autogenerated mock type for the DownloadOption type -type DownloadOption struct { - mock.Mock -} - -// Execute provides a mock function with given fields: do -func (_m *DownloadOption) Execute(do *sdk.DownloadOptions) { - _m.Called(do) -} - -type mockConstructorTestingTNewDownloadOption interface { - mock.TestingT - Cleanup(func()) -} - -// NewDownloadOption creates a new instance of DownloadOption. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewDownloadOption(t mockConstructorTestingTNewDownloadOption) *DownloadOption { - mock := &DownloadOption{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/zboxcore/mocks/Downloader.go b/zboxcore/mocks/Downloader.go deleted file mode 100644 index d1b2af1f0..000000000 --- a/zboxcore/mocks/Downloader.go +++ /dev/null @@ -1,72 +0,0 @@ -// Code generated by mockery v2.22.1. DO NOT EDIT. - -package mocks - -import ( - sdk "github.com/0chain/gosdk/zboxcore/sdk" - mock "github.com/stretchr/testify/mock" -) - -// Downloader is an autogenerated mock type for the Downloader type -type Downloader struct { - mock.Mock -} - -// GetAllocation provides a mock function with given fields: -func (_m *Downloader) GetAllocation() *sdk.Allocation { - ret := _m.Called() - - var r0 *sdk.Allocation - if rf, ok := ret.Get(0).(func() *sdk.Allocation); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*sdk.Allocation) - } - } - - return r0 -} - -// GetFileName provides a mock function with given fields: -func (_m *Downloader) GetFileName() string { - ret := _m.Called() - - var r0 string - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(string) - } - - return r0 -} - -// Start provides a mock function with given fields: status, isFinal -func (_m *Downloader) Start(status sdk.StatusCallback, isFinal bool) error { - ret := _m.Called(status, isFinal) - - var r0 error - if rf, ok := ret.Get(0).(func(sdk.StatusCallback, bool) error); ok { - r0 = rf(status, isFinal) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -type mockConstructorTestingTNewDownloader interface { - mock.TestingT - Cleanup(func()) -} - -// NewDownloader creates a new instance of Downloader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewDownloader(t mockConstructorTestingTNewDownloader) *Downloader { - mock := &Downloader{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/zboxcore/mocks/LiveUploadOption.go b/zboxcore/mocks/LiveUploadOption.go deleted file mode 100644 index 88750015d..000000000 --- a/zboxcore/mocks/LiveUploadOption.go +++ /dev/null @@ -1,33 +0,0 @@ -// Code generated by mockery v2.22.1. DO NOT EDIT. - -package mocks - -import ( - sdk "github.com/0chain/gosdk/zboxcore/sdk" - mock "github.com/stretchr/testify/mock" -) - -// LiveUploadOption is an autogenerated mock type for the LiveUploadOption type -type LiveUploadOption struct { - mock.Mock -} - -// Execute provides a mock function with given fields: lu -func (_m *LiveUploadOption) Execute(lu *sdk.LiveUpload) { - _m.Called(lu) -} - -type mockConstructorTestingTNewLiveUploadOption interface { - mock.TestingT - Cleanup(func()) -} - -// NewLiveUploadOption creates a new instance of LiveUploadOption. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewLiveUploadOption(t mockConstructorTestingTNewLiveUploadOption) *LiveUploadOption { - mock := &LiveUploadOption{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/zboxcore/mocks/Operationer.go b/zboxcore/mocks/Operationer.go deleted file mode 100644 index 1d5b4cfe1..000000000 --- a/zboxcore/mocks/Operationer.go +++ /dev/null @@ -1,109 +0,0 @@ -// Code generated by mockery v2.22.1. DO NOT EDIT. - -package mocks - -import ( - allocationchange "github.com/0chain/gosdk/zboxcore/allocationchange" - fileref "github.com/0chain/gosdk/zboxcore/fileref" - - mock "github.com/stretchr/testify/mock" - - sdk "github.com/0chain/gosdk/zboxcore/sdk" - - uuid "github.com/google/uuid" - - zboxutil "github.com/0chain/gosdk/zboxcore/zboxutil" -) - -// Operationer is an autogenerated mock type for the Operationer type -type Operationer struct { - mock.Mock -} - -// Completed provides a mock function with given fields: allocObj -func (_m *Operationer) Completed(allocObj *sdk.Allocation) { - _m.Called(allocObj) -} - -// Error provides a mock function with given fields: allocObj, consensus, err -func (_m *Operationer) Error(allocObj *sdk.Allocation, consensus int, err error) { - _m.Called(allocObj, consensus, err) -} - -// Process provides a mock function with given fields: allocObj, connectionID -func (_m *Operationer) Process(allocObj *sdk.Allocation, connectionID string) ([]fileref.RefEntity, zboxutil.Uint128, error) { - ret := _m.Called(allocObj, connectionID) - - var r0 []fileref.RefEntity - var r1 zboxutil.Uint128 - var r2 error - if rf, ok := ret.Get(0).(func(*sdk.Allocation, string) ([]fileref.RefEntity, zboxutil.Uint128, error)); ok { - return rf(allocObj, connectionID) - } - if rf, ok := ret.Get(0).(func(*sdk.Allocation, string) []fileref.RefEntity); ok { - r0 = rf(allocObj, connectionID) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]fileref.RefEntity) - } - } - - if rf, ok := ret.Get(1).(func(*sdk.Allocation, string) zboxutil.Uint128); ok { - r1 = rf(allocObj, connectionID) - } else { - r1 = ret.Get(1).(zboxutil.Uint128) - } - - if rf, ok := ret.Get(2).(func(*sdk.Allocation, string) error); ok { - r2 = rf(allocObj, connectionID) - } else { - r2 = ret.Error(2) - } - - return r0, r1, r2 -} - -// Verify provides a mock function with given fields: allocObj -func (_m *Operationer) Verify(allocObj *sdk.Allocation) error { - ret := _m.Called(allocObj) - - var r0 error - if rf, ok := ret.Get(0).(func(*sdk.Allocation) error); ok { - r0 = rf(allocObj) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// buildChange provides a mock function with given fields: refs, uid -func (_m *Operationer) buildChange(refs []fileref.RefEntity, uid uuid.UUID) []allocationchange.AllocationChange { - ret := _m.Called(refs, uid) - - var r0 []allocationchange.AllocationChange - if rf, ok := ret.Get(0).(func([]fileref.RefEntity, uuid.UUID) []allocationchange.AllocationChange); ok { - r0 = rf(refs, uid) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]allocationchange.AllocationChange) - } - } - - return r0 -} - -type mockConstructorTestingTNewOperationer interface { - mock.TestingT - Cleanup(func()) -} - -// NewOperationer creates a new instance of Operationer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewOperationer(t mockConstructorTestingTNewOperationer) *Operationer { - mock := &Operationer{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} From f65eecf70a7bd7aa935b0c9d60092e3e375bda6e Mon Sep 17 00:00:00 2001 From: YarikRevich Date: Tue, 29 Aug 2023 21:35:14 +0200 Subject: [PATCH 018/134] fix: fixed bugs --- zcnbridge/bridge_test.go | 7 +------ zcnbridge/wallets/README.md | 1 + ...47.946612000Z--d8c9156e782c68ee671c09b6b92de76c97948432 | 1 + 3 files changed, 3 insertions(+), 6 deletions(-) create mode 100644 zcnbridge/wallets/README.md create mode 100644 zcnbridge/wallets/UTC--2023-08-29T19-30-47.946612000Z--d8c9156e782c68ee671c09b6b92de76c97948432 diff --git a/zcnbridge/bridge_test.go b/zcnbridge/bridge_test.go index ce5ab810f..c08b108cd 100644 --- a/zcnbridge/bridge_test.go +++ b/zcnbridge/bridge_test.go @@ -265,15 +265,10 @@ func getKeyStore(t mock.TestingT) *bridgemocks.KeyStore { func prepareKeyStoreGeneralMockCalls(keyStore *bridgemocks.KeyStore) { ks := keystore.NewKeyStore(testKeyStoreLocation, keystore.StandardScryptN, keystore.StandardScryptP) - _, err := ImportAccount(".", ethereumMnemonic, password) - if err != nil { - log.Fatalln(err) - } - keyStore.On("Find", mock.Anything).Return(accounts.Account{Address: common.HexToAddress(ethereumAddress)}, nil) keyStore.On("TimedUnlock", mock.Anything, mock.Anything, mock.Anything).Run( func(args mock.Arguments) { - err = ks.TimedUnlock(args.Get(0).(accounts.Account), args.Get(1).(string), args.Get(2).(time.Duration)) + err := ks.TimedUnlock(args.Get(0).(accounts.Account), args.Get(1).(string), args.Get(2).(time.Duration)) if err != nil { log.Fatalln(err) } diff --git a/zcnbridge/wallets/README.md b/zcnbridge/wallets/README.md new file mode 100644 index 000000000..9ab8bf214 --- /dev/null +++ b/zcnbridge/wallets/README.md @@ -0,0 +1 @@ +Contains Ethereum KeyStore wallets used for tests. \ No newline at end of file diff --git a/zcnbridge/wallets/UTC--2023-08-29T19-30-47.946612000Z--d8c9156e782c68ee671c09b6b92de76c97948432 b/zcnbridge/wallets/UTC--2023-08-29T19-30-47.946612000Z--d8c9156e782c68ee671c09b6b92de76c97948432 new file mode 100644 index 000000000..a3590fc0a --- /dev/null +++ b/zcnbridge/wallets/UTC--2023-08-29T19-30-47.946612000Z--d8c9156e782c68ee671c09b6b92de76c97948432 @@ -0,0 +1 @@ +{"address":"d8c9156e782c68ee671c09b6b92de76c97948432","crypto":{"cipher":"aes-128-ctr","ciphertext":"7048af9fa09a3a0ca22e7ef8afea41fec8dcce848b48be8fc0d59a1f04e8581f","cipherparams":{"iv":"c97dd7cb9c554965196dd4d5bc218e0e"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"aaccc85e65af50058262ee54a2e8952a91b47d0af266e4a3558425049e77c835"},"mac":"c5ac03cbe13375c6e4c3052ff5f23f92a2c595fca6c90c3ac908b57dccd78b0a"},"id":"16c89ced-50fd-4c78-86e3-40ff440078fb","version":3} \ No newline at end of file From 852ccc5175cea40db383ad4eefe14a82a832565b Mon Sep 17 00:00:00 2001 From: YarikRevich Date: Tue, 29 Aug 2023 21:38:35 +0200 Subject: [PATCH 019/134] fix: fixed bugs --- zcnbridge/bridge_test.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/zcnbridge/bridge_test.go b/zcnbridge/bridge_test.go index c08b108cd..177862800 100644 --- a/zcnbridge/bridge_test.go +++ b/zcnbridge/bridge_test.go @@ -32,8 +32,6 @@ import ( ) const ( - ethereumMnemonic = "symbol alley celery diesel donate moral almost opinion achieve since diamond page" - ethereumAddress = "0xD8c9156e782C68EE671C09b6b92de76C97948432" password = "02289b9" From 9a51ef3bf763ad65133cba11c2c057be7240d18a Mon Sep 17 00:00:00 2001 From: YarikRevich Date: Wed, 30 Aug 2023 16:47:06 +0200 Subject: [PATCH 020/134] fix: made components internal --- zcnbridge/bridge.go | 36 ++++++++++++++++++------------------ zcnbridge/config.go | 12 ++++++------ 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/zcnbridge/bridge.go b/zcnbridge/bridge.go index a69d3c250..a5992e72e 100644 --- a/zcnbridge/bridge.go +++ b/zcnbridge/bridge.go @@ -67,7 +67,7 @@ func (b *BridgeClient) CreateSignedTransactionFromKeyStore(client EthereumClient signer := accounts.Account{ Address: signerAddress, } - signerAcc, err := b.KeyStore.Find(signer) + signerAcc, err := b.keyStore.Find(signer) if err != nil { Logger.Fatal(errors.Wrapf(err, "signer: %s", signerAddress.Hex())) } @@ -87,12 +87,12 @@ func (b *BridgeClient) CreateSignedTransactionFromKeyStore(client EthereumClient Logger.Fatal(err) } - err = b.KeyStore.TimedUnlock(signer, password, time.Second*2) + err = b.keyStore.TimedUnlock(signer, password, time.Second*2) if err != nil { Logger.Fatal(err) } - opts, err := bind.NewKeyStoreTransactorWithChainID(b.KeyStore.GetEthereumKeyStore(), signerAcc, chainID) + opts, err := bind.NewKeyStoreTransactorWithChainID(b.keyStore.GetEthereumKeyStore(), signerAcc, chainID) if err != nil { Logger.Fatal(err) } @@ -123,7 +123,7 @@ func (b *BridgeClient) prepareAuthorizers(ctx context.Context, method string, pa from := common.HexToAddress(b.EthereumAddress) // Gas limits in units - gasLimitUnits, err := b.EthereumClient.EstimateGas(ctx, eth.CallMsg{ + gasLimitUnits, err := b.ethereumClient.EstimateGas(ctx, eth.CallMsg{ To: &contractAddress, From: from, Data: pack, @@ -135,10 +135,10 @@ func (b *BridgeClient) prepareAuthorizers(ctx context.Context, method string, pa // Update gas limits + 10% gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() - transactOpts := b.CreateSignedTransactionFromKeyStore(b.EthereumClient, gasLimitUnits) + transactOpts := b.CreateSignedTransactionFromKeyStore(b.ethereumClient, gasLimitUnits) // Authorizers instance - authorizersInstance, err := authorizers.NewAuthorizers(contractAddress, b.EthereumClient) + authorizersInstance, err := authorizers.NewAuthorizers(contractAddress, b.ethereumClient) if err != nil { return nil, nil, errors.Wrap(err, "failed to create authorizers instance") } @@ -212,7 +212,7 @@ func (b *BridgeClient) IncreaseBurnerAllowance(ctx context.Context, amountWei We return nil, errors.Wrap(err, "failed to pack arguments") } - gasLimitUnits, err := b.EthereumClient.EstimateGas(ctx, eth.CallMsg{ + gasLimitUnits, err := b.ethereumClient.EstimateGas(ctx, eth.CallMsg{ To: &tokenAddress, From: fromAddress, Data: pack, @@ -223,9 +223,9 @@ func (b *BridgeClient) IncreaseBurnerAllowance(ctx context.Context, amountWei We gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() - transactOpts := b.CreateSignedTransactionFromKeyStore(b.EthereumClient, gasLimitUnits) + transactOpts := b.CreateSignedTransactionFromKeyStore(b.ethereumClient, gasLimitUnits) - wzcnTokenInstance, err := erc20.NewERC20(tokenAddress, b.EthereumClient) + wzcnTokenInstance, err := erc20.NewERC20(tokenAddress, b.ethereumClient) if err != nil { return nil, errors.Wrap(err, "failed to initialize WZCN-ERC20 instance") } @@ -265,7 +265,7 @@ func (b *BridgeClient) GetBalance() (*big.Int, error) { tokenAddress := common.HexToAddress(b.TokenAddress) fromAddress := common.HexToAddress(b.EthereumAddress) - wzcnTokenInstance, err := erc20.NewERC20(tokenAddress, b.EthereumClient) + wzcnTokenInstance, err := erc20.NewERC20(tokenAddress, b.ethereumClient) if err != nil { return nil, errors.Wrap(err, "failed to initialize WZCN-ERC20 instance") } @@ -291,12 +291,12 @@ func (b *BridgeClient) SignWithEthereumChain(message string) ([]byte, error) { Address: common.HexToAddress(b.EthereumAddress), } - signerAcc, err := b.KeyStore.Find(signer) + signerAcc, err := b.keyStore.Find(signer) if err != nil { Logger.Fatal(err) } - signature, err := b.KeyStore.SignHash(signerAcc, hash.Bytes()) + signature, err := b.keyStore.SignHash(signerAcc, hash.Bytes()) if err != nil { return nil, err } @@ -315,7 +315,7 @@ func (b *BridgeClient) GetUserNonceMinted(ctx context.Context, rawEthereumAddres contractAddress := common.HexToAddress(b.BridgeAddress) var bridgeInstance *binding.Bridge - bridgeInstance, err := binding.NewBridge(contractAddress, b.EthereumClient) + bridgeInstance, err := binding.NewBridge(contractAddress, b.ethereumClient) if err != nil { return nil, errors.Wrap(err, "failed to create bridge instance") } @@ -432,7 +432,7 @@ func (b *BridgeClient) BurnWZCN(ctx context.Context, amountTokens uint64) (*type // MintZCN mints ZCN tokens after receiving proof-of-burn of WZCN tokens func (b *BridgeClient) MintZCN(ctx context.Context, payload *zcnsc.MintPayload) (string, error) { - trx, err := b.TransactionProvider.NewTransactionEntity(0) + trx, err := b.transactionProvider.NewTransactionEntity(0) if err != nil { log.Logger.Fatal("failed to create new transaction", zap.Error(err)) } @@ -468,7 +468,7 @@ func (b *BridgeClient) BurnZCN(ctx context.Context, amount, txnfee uint64) (tran EthereumAddress: b.EthereumAddress, } - trx, err := b.TransactionProvider.NewTransactionEntity(txnfee) + trx, err := b.transactionProvider.NewTransactionEntity(txnfee) if err != nil { log.Logger.Fatal("failed to create new transaction", zap.Error(err)) } @@ -528,7 +528,7 @@ func (b *BridgeClient) prepareBridge(ctx context.Context, ethereumAddress, metho //Gas limits in units fromAddress := common.HexToAddress(ethereumAddress) - gasLimitUnits, err := b.EthereumClient.EstimateGas(ctx, eth.CallMsg{ + gasLimitUnits, err := b.ethereumClient.EstimateGas(ctx, eth.CallMsg{ To: &contractAddress, From: fromAddress, Data: pack, @@ -540,10 +540,10 @@ func (b *BridgeClient) prepareBridge(ctx context.Context, ethereumAddress, metho //Update gas limits + 10% gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() - transactOpts := b.CreateSignedTransactionFromKeyStore(b.EthereumClient, gasLimitUnits) + transactOpts := b.CreateSignedTransactionFromKeyStore(b.ethereumClient, gasLimitUnits) // BridgeClient instance - bridgeInstance, err := binding.NewBridge(contractAddress, b.EthereumClient) + bridgeInstance, err := binding.NewBridge(contractAddress, b.ethereumClient) if err != nil { return nil, nil, errors.Wrap(err, "failed to create bridge instance") } diff --git a/zcnbridge/config.go b/zcnbridge/config.go index 7b9ce8252..2cdfde17f 100644 --- a/zcnbridge/config.go +++ b/zcnbridge/config.go @@ -29,9 +29,9 @@ type BridgeSDKConfig struct { } type BridgeClient struct { - KeyStore - transaction.TransactionProvider - EthereumClient + keyStore KeyStore + transactionProvider transaction.TransactionProvider + ethereumClient EthereumClient BridgeAddress, TokenAddress, @@ -61,9 +61,9 @@ func createBridgeClient(cfg *viper.Viper, ethereumClient EthereumClient, transac Password: cfg.GetString("bridge.password"), GasLimit: cfg.GetUint64("bridge.gas_limit"), ConsensusThreshold: cfg.GetFloat64("bridge.consensus_threshold"), - EthereumClient: ethereumClient, - TransactionProvider: transactionProvider, - KeyStore: keyStore, + ethereumClient: ethereumClient, + transactionProvider: transactionProvider, + keyStore: keyStore, } } From 47cfad467552e60046c7902be8cfc16a0eefbd0f Mon Sep 17 00:00:00 2001 From: Dinmukhammed Kambarov <52813950+din-mukhammed@users.noreply.github.com> Date: Mon, 28 Aug 2023 19:04:03 +0600 Subject: [PATCH 021/134] Add webstreaming to multiupload (#1190) * add webstreaming * fix typos * add webstreaming to wasm multiupload * fix typo --- mobilesdk/zbox/storage.go | 23 ++++++++++++++--------- wasmsdk/blobber.go | 12 +++++++----- winsdk/models.go | 7 ++++--- winsdk/storage.go | 19 +++++++++++-------- zboxcore/sdk/allocation.go | 22 +++++++++++++--------- zboxcore/sdk/upload_worker.go | 6 ++++-- 6 files changed, 53 insertions(+), 36 deletions(-) diff --git a/mobilesdk/zbox/storage.go b/mobilesdk/zbox/storage.go index 2dc193193..3e88bb6ef 100644 --- a/mobilesdk/zbox/storage.go +++ b/mobilesdk/zbox/storage.go @@ -26,13 +26,14 @@ type MultiOperationOption struct { } type MultiUploadOption struct { - FilePath string `json:"filePath,omitempty"` - FileName string `json:"fileName,omitempty"` - RemotePath string `json:"remotePath,omitempty"` - ThumbnailPath string `json:"thumbnailPath,omitempty"` - Encrypt bool `json:"encrypt,omitempty"` - ChunkNumber int `json:"chunkNumber,omitempty"` - IsUpdate bool `json:"isUpdate,omitempty"` + FilePath string `json:"filePath,omitempty"` + FileName string `json:"fileName,omitempty"` + RemotePath string `json:"remotePath,omitempty"` + ThumbnailPath string `json:"thumbnailPath,omitempty"` + Encrypt bool `json:"encrypt,omitempty"` + ChunkNumber int `json:"chunkNumber,omitempty"` + IsUpdate bool `json:"isUpdate,omitempty"` + IsWebstreaming bool `json:"isWebstreaming,omitempty"` } type MultiDownloadOption struct { @@ -336,6 +337,7 @@ func MultiUpload(allocationID string, workdir string, jsonMultiUploadOptions str encrypts := make([]bool, totalUploads) chunkNumbers := make([]int, totalUploads) isUpdates := make([]bool, totalUploads) + isWebstreaming := make([]bool, totalUploads) for idx, option := range options { filePaths[idx] = option.FilePath fileNames[idx] = option.FileName @@ -344,13 +346,14 @@ func MultiUpload(allocationID string, workdir string, jsonMultiUploadOptions str chunkNumbers[idx] = option.ChunkNumber encrypts[idx] = option.Encrypt isUpdates[idx] = false + isWebstreaming[idx] = option.IsWebstreaming } a, err := getAllocation(allocationID) if err != nil { return err } - return a.StartMultiUpload(workdir, filePaths, fileNames, thumbnailPaths, encrypts, chunkNumbers, remotePaths, isUpdates, &StatusCallbackWrapped{Callback: statusCb}) + return a.StartMultiUpload(workdir, filePaths, fileNames, thumbnailPaths, encrypts, chunkNumbers, remotePaths, isUpdates, isWebstreaming, &StatusCallbackWrapped{Callback: statusCb}) } @@ -373,6 +376,7 @@ func MultiUpdate(allocationID string, workdir string, jsonMultiUploadOptions str encrypts := make([]bool, totalUploads) chunkNumbers := make([]int, totalUploads) isUpdates := make([]bool, totalUploads) + isWebstreaming := make([]bool, totalUploads) for idx, option := range options { filePaths[idx] = option.FilePath fileNames[idx] = option.FileName @@ -381,6 +385,7 @@ func MultiUpdate(allocationID string, workdir string, jsonMultiUploadOptions str chunkNumbers[idx] = option.ChunkNumber encrypts[idx] = option.Encrypt isUpdates[idx] = true + isWebstreaming[idx] = option.IsWebstreaming } if err != nil { return err @@ -390,7 +395,7 @@ func MultiUpdate(allocationID string, workdir string, jsonMultiUploadOptions str if err != nil { return err } - return a.StartMultiUpload(workdir, filePaths, fileNames, thumbnailPaths, encrypts, chunkNumbers, remotePaths, isUpdates, &StatusCallbackWrapped{Callback: statusCb}) + return a.StartMultiUpload(workdir, filePaths, fileNames, thumbnailPaths, encrypts, chunkNumbers, remotePaths, isUpdates, isWebstreaming, &StatusCallbackWrapped{Callback: statusCb}) } diff --git a/wasmsdk/blobber.go b/wasmsdk/blobber.go index 7b06e9121..e7a6b110f 100644 --- a/wasmsdk/blobber.go +++ b/wasmsdk/blobber.go @@ -475,6 +475,7 @@ type BulkUploadOption struct { Webstreaming bool `json:"webstreaming,omitempty"` IsUpdate bool `json:"isUpdate,omitempty"` IsRepair bool `json:"isRepair,omitempty"` + IsWebstreaming bool `json:"isWebstreaming,omitempty"` NumBlocks int `json:"numBlocks,omitempty"` FileSize int64 `json:"fileSize,omitempty"` @@ -671,11 +672,12 @@ func multiUpload(jsonBulkUploadOptions string) (MultiUploadResult, error) { sdk.WithChunkNumber(numBlocks), } operationRequests[idx] = sdk.OperationRequest{ - FileMeta: fileMeta, - FileReader: fileReader, - OperationType: FileOperationInsert, - Opts: options, - Workdir: "/", + FileMeta: fileMeta, + FileReader: fileReader, + OperationType: FileOperationInsert, + Opts: options, + Workdir: "/", + IsWebstreaming: option.IsWebstreaming, } } diff --git a/winsdk/models.go b/winsdk/models.go index 8fb2723d7..ef86b5238 100644 --- a/winsdk/models.go +++ b/winsdk/models.go @@ -5,9 +5,10 @@ type UploadFile struct { Path string ThumbnailPath string - RemotePath string - Encrypt bool - IsUpdate bool + RemotePath string + Encrypt bool + IsUpdate bool + IsWebstreaming bool ChunkNumber int } diff --git a/winsdk/storage.go b/winsdk/storage.go index 00ffb40ad..005c3798f 100644 --- a/winsdk/storage.go +++ b/winsdk/storage.go @@ -163,13 +163,14 @@ type MultiOperationOption struct { } type MultiUploadOption struct { - FilePath string `json:"filePath,omitempty"` - FileName string `json:"fileName,omitempty"` - RemotePath string `json:"remotePath,omitempty"` - ThumbnailPath string `json:"thumbnailPath,omitempty"` - Encrypt bool `json:"encrypt,omitempty"` - ChunkNumber int `json:"chunkNumber,omitempty"` - IsUpdate bool `json:"isUpdate,omitempty"` + FilePath string `json:"filePath,omitempty"` + FileName string `json:"fileName,omitempty"` + RemotePath string `json:"remotePath,omitempty"` + ThumbnailPath string `json:"thumbnailPath,omitempty"` + Encrypt bool `json:"encrypt,omitempty"` + ChunkNumber int `json:"chunkNumber,omitempty"` + IsUpdate bool `json:"isUpdate,omitempty"` + IsWebstreaming bool `json:"isWebstreaming,omitempty"` } // MultiOperation - do copy, move, delete and createdir operation together @@ -323,6 +324,7 @@ func BulkUpload(uploadID, allocationID, files *C.char) *C.char { chunkNumbers := make([]int, totalUploads) encrypts := make([]bool, totalUploads) isUpdates := make([]bool, totalUploads) + isWebstreaming := make([]bool, totalUploads) statusBar := &StatusCallback{ status: make(map[string]*Status), @@ -335,6 +337,7 @@ func BulkUpload(uploadID, allocationID, files *C.char) *C.char { remotePaths[idx] = option.RemotePath chunkNumbers[idx] = option.ChunkNumber isUpdates[idx] = option.IsUpdate + isWebstreaming[idx] = option.IsWebstreaming encrypts[idx] = option.Encrypt statusBar.status[option.RemotePath+option.Name] = &Status{} } @@ -346,7 +349,7 @@ func BulkUpload(uploadID, allocationID, files *C.char) *C.char { statusCaches.Add(C.GoString(uploadID), statusBar) - err = a.StartMultiUpload(workdir, filePaths, fileNames, thumbnailPaths, encrypts, chunkNumbers, remotePaths, isUpdates, statusBar) + err = a.StartMultiUpload(workdir, filePaths, fileNames, thumbnailPaths, encrypts, chunkNumbers, remotePaths, isUpdates, isWebstreaming, statusBar) if err != nil { return WithJSON(nil, err) } diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 809febafc..30b84d973 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -208,12 +208,13 @@ type Allocation struct { } type OperationRequest struct { - OperationType string - LocalPath string - RemotePath string - DestName string // Required only for rename operation - DestPath string // Required for copy and move operation - IsUpdate bool + OperationType string + LocalPath string + RemotePath string + DestName string // Required only for rename operation + DestPath string // Required for copy and move operation + IsUpdate bool + IsWebstreaming bool // Required for uploads Workdir string @@ -495,7 +496,7 @@ func (a *Allocation) EncryptAndUploadFileWithThumbnail( ) } -func (a *Allocation) StartMultiUpload(workdir string, localPaths []string, fileNames []string, thumbnailPaths []string, encrypts []bool, chunkNumbers []int, remotePaths []string, isUpdate []bool, status StatusCallback) error { +func (a *Allocation) StartMultiUpload(workdir string, localPaths []string, fileNames []string, thumbnailPaths []string, encrypts []bool, chunkNumbers []int, remotePaths []string, isUpdate []bool, isWebstreaming []bool, status StatusCallback) error { if len(localPaths) != len(thumbnailPaths) { return errors.New("invalid_value", "length of localpaths and thumbnailpaths must be equal") } @@ -588,6 +589,9 @@ func (a *Allocation) StartMultiUpload(workdir string, localPaths []string, fileN if isUpdate[idx] { operationRequests[idx].OperationType = constants.FileOperationUpdate } + if isWebstreaming[idx] { + operationRequests[idx].IsWebstreaming = true + } } err := a.DoMultiOperation(operationRequests) @@ -873,13 +877,13 @@ func (a *Allocation) DoMultiOperation(operations []OperationRequest) error { operation = NewMoveOperation(op.RemotePath, op.DestPath, mo.operationMask, mo.maskMU, mo.consensusThresh, mo.fullconsensus, mo.ctx) case constants.FileOperationInsert: - operation = NewUploadOperation(op.Workdir, op.FileMeta, op.FileReader, false, op.Opts...) + operation = NewUploadOperation(op.Workdir, op.FileMeta, op.FileReader, false, op.IsWebstreaming, op.Opts...) case constants.FileOperationDelete: operation = NewDeleteOperation(op.RemotePath, mo.operationMask, mo.maskMU, mo.consensusThresh, mo.fullconsensus, mo.ctx) case constants.FileOperationUpdate: - operation = NewUploadOperation(op.Workdir, op.FileMeta, op.FileReader, true, op.Opts...) + operation = NewUploadOperation(op.Workdir, op.FileMeta, op.FileReader, true, op.IsWebstreaming, op.Opts...) case constants.FileOperationCreateDir: operation = NewDirOperation(op.RemotePath, mo.operationMask, mo.maskMU, mo.consensusThresh, mo.fullconsensus, mo.ctx) diff --git a/zboxcore/sdk/upload_worker.go b/zboxcore/sdk/upload_worker.go index f548ab1e5..5e90ec375 100644 --- a/zboxcore/sdk/upload_worker.go +++ b/zboxcore/sdk/upload_worker.go @@ -19,12 +19,13 @@ type UploadOperation struct { opts []ChunkedUploadOption refs []*fileref.FileRef isUpdate bool + isWebstreaming bool statusCallback StatusCallback opCode int } func (uo *UploadOperation) Process(allocObj *Allocation, connectionID string) ([]fileref.RefEntity, zboxutil.Uint128, error) { - cu, err := CreateChunkedUpload(uo.workdir, allocObj, uo.fileMeta, uo.fileReader, uo.isUpdate, false, false, connectionID, uo.opts...) + cu, err := CreateChunkedUpload(uo.workdir, allocObj, uo.fileMeta, uo.fileReader, uo.isUpdate, false, uo.isWebstreaming, connectionID, uo.opts...) if err != nil { uploadMask := zboxutil.NewUint128(1).Lsh(uint64(len(allocObj.Blobbers))).Sub64(1) return nil, uploadMask, err @@ -123,12 +124,13 @@ func (uo *UploadOperation) Error(allocObj *Allocation, consensus int, err error) } } -func NewUploadOperation(workdir string, fileMeta FileMeta, fileReader io.Reader, isUpdate bool, opts ...ChunkedUploadOption) *UploadOperation { +func NewUploadOperation(workdir string, fileMeta FileMeta, fileReader io.Reader, isUpdate, isWebstreaming bool, opts ...ChunkedUploadOption) *UploadOperation { uo := &UploadOperation{} uo.workdir = workdir uo.fileMeta = fileMeta uo.fileReader = fileReader uo.opts = opts uo.isUpdate = isUpdate + uo.isWebstreaming = isWebstreaming return uo } From 0e1c494ccc81815cef6a039e0d0942d32f37f7b8 Mon Sep 17 00:00:00 2001 From: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Date: Mon, 28 Aug 2023 18:34:46 +0530 Subject: [PATCH 022/134] fix dup upload consensus (#1195) --- zboxcore/sdk/chunked_upload.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/zboxcore/sdk/chunked_upload.go b/zboxcore/sdk/chunked_upload.go index 058fde3c2..3ae33d601 100644 --- a/zboxcore/sdk/chunked_upload.go +++ b/zboxcore/sdk/chunked_upload.go @@ -671,8 +671,12 @@ func (su *ChunkedUpload) processUpload(chunkStartIndex, chunkEndIndex int, err = b.sendUploadRequest(ctx, su, chunkEndIndex, isFinal, su.encryptedKey, body, formData, pos) if err != nil { if strings.Contains(err.Error(), "duplicate") { - atomic.AddInt32(&su.addConsensus, 1) - su.consensus.Done() + errC := atomic.AddInt32(&su.addConsensus, 1) + if errC >= int32(su.consensus.consensusThresh) { + wgErrors <- err + } else { + su.consensus.Done() + } return } logger.Logger.Error("error during sendUploadRequest", err) From d533a8fbcdca80028be685f4d5e26dc66c5f86f0 Mon Sep 17 00:00:00 2001 From: Dinmukhammed Kambarov <52813950+din-mukhammed@users.noreply.github.com> Date: Tue, 29 Aug 2023 17:57:59 +0600 Subject: [PATCH 023/134] Fix multiupload completed callback (#1172) * remove unnecessary print * fix delete and createdir * return major error * add webstreaming * fix typos * add webstreaming to wasm multiupload * fix typo * cleanup * fix completed callback --- zboxcore/sdk/allocation.go | 13 ++++++- zboxcore/sdk/commitworker.go | 7 +++- zboxcore/sdk/deleteworker.go | 2 +- zboxcore/sdk/dirworker.go | 54 +++++++++++++++----------- zboxcore/sdk/multi_operation_worker.go | 19 +++++---- zboxcore/sdk/upload_worker.go | 2 + 6 files changed, 60 insertions(+), 37 deletions(-) diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 30b84d973..c738a6015 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -388,6 +388,7 @@ func (a *Allocation) CreateDir(remotePath string) error { remotePath: remotePath, wg: &sync.WaitGroup{}, timestamp: timestamp, + alreadyExists: map[uint64]bool{}, Consensus: Consensus{ RWMutex: &sync.RWMutex{}, consensusThresh: a.consensusThreshold, @@ -555,7 +556,7 @@ func (a *Allocation) StartMultiUpload(workdir string, localPaths []string, fileN if err != nil { return err } - fmt.Println("fullRemotepath and localpath", fullRemotePath, localPath) + fileMeta := FileMeta{ Path: localPath, ActualSize: fileInfo.Size(), @@ -835,6 +836,7 @@ func (a *Allocation) DoMultiOperation(operations []OperationRequest) error { mo.connectionID = zboxutil.NewConnectionId() previousPaths := make(map[string]bool) + connectionErrors := make([]error, len(mo.allocationObj.Blobbers)) var wg sync.WaitGroup for blobberIdx := range mo.allocationObj.Blobbers { @@ -844,14 +846,21 @@ func (a *Allocation) DoMultiOperation(operations []OperationRequest) error { err := mo.createConnectionObj(pos) if err != nil { l.Logger.Error(err.Error()) + connectionErrors[pos] = err } }(blobberIdx) } wg.Wait() // Check consensus if mo.operationMask.CountOnes() < mo.consensusThresh { + majorErr := zboxutil.MajorError(connectionErrors) + if majorErr != nil { + return errors.New("consensus_not_met", + fmt.Sprintf("Multioperation: create connection failed. Required consensus %d got %d. Major error: %s", + mo.consensusThresh, mo.operationMask.CountOnes(), majorErr.Error())) + } return errors.New("consensus_not_met", - fmt.Sprintf("Multioperation failed. Required consensus %d got %d", + fmt.Sprintf("Multioperation: create connection failed. Required consensus %d got %d", mo.consensusThresh, mo.operationMask.CountOnes())) } diff --git a/zboxcore/sdk/commitworker.go b/zboxcore/sdk/commitworker.go index 9c6189275..81dab2470 100644 --- a/zboxcore/sdk/commitworker.go +++ b/zboxcore/sdk/commitworker.go @@ -101,10 +101,15 @@ func (commitreq *CommitRequest) processCommit() { var req *http.Request var lR ReferencePathResult req, err := zboxutil.NewReferencePathRequest(commitreq.blobber.Baseurl, commitreq.allocationID, commitreq.allocationTx, paths) - if err != nil || len(paths) == 0 { + if err != nil { l.Logger.Error("Creating ref path req", err) return } + if len(paths) == 0 { + l.Logger.Info("Nothing to commit") + commitreq.result = SuccessCommitResult() + return + } ctx, cncl := context.WithTimeout(context.Background(), (time.Second * 30)) err = zboxutil.HttpDo(ctx, cncl, req, func(resp *http.Response, err error) error { diff --git a/zboxcore/sdk/deleteworker.go b/zboxcore/sdk/deleteworker.go index f7dd01a1a..9e8c2330e 100644 --- a/zboxcore/sdk/deleteworker.go +++ b/zboxcore/sdk/deleteworker.go @@ -357,7 +357,7 @@ func (dop *DeleteOperation) Process(allocObj *Allocation, connectionID string) ( fmt.Sprintf("Delete failed. Required consensus %d, got %d", deleteReq.consensus.consensusThresh, deleteReq.consensus.consensus)) } - l.Logger.Info("Delete Processs Ended ") + l.Logger.Info("Delete Process Ended ") return objectTreeRefs, deleteReq.deleteMask, nil } diff --git a/zboxcore/sdk/dirworker.go b/zboxcore/sdk/dirworker.go index 60e63bd3a..c19ba468e 100644 --- a/zboxcore/sdk/dirworker.go +++ b/zboxcore/sdk/dirworker.go @@ -42,6 +42,7 @@ type DirRequest struct { mu *sync.Mutex connectionID string timestamp int64 + alreadyExists map[uint64]bool Consensus } @@ -63,6 +64,7 @@ func (req *DirRequest) ProcessWithBlobbers(a *Allocation) int { } if alreadyExists { countMu.Lock() + req.alreadyExists[pos] = true existingDirCount++ countMu.Unlock() } @@ -258,9 +260,6 @@ func (req *DirRequest) createDirInBlobber(blobber *blockchain.StorageNode, pos u l.Logger.Error(blobber.Baseurl, " Response: ", msg) if strings.Contains(msg, DirectoryExists) { req.Consensus.Done() - req.mu.Lock() - req.dirMask = req.dirMask.And(zboxutil.NewUint128(1).Lsh(pos).Not()) - req.mu.Unlock() alreadyExists = true return } @@ -286,11 +285,12 @@ func (req *DirRequest) createDirInBlobber(blobber *blockchain.StorageNode, pos u } type DirOperation struct { - remotePath string - ctx context.Context - ctxCncl context.CancelFunc - dirMask zboxutil.Uint128 - maskMU *sync.Mutex + remotePath string + ctx context.Context + ctxCncl context.CancelFunc + dirMask zboxutil.Uint128 + maskMU *sync.Mutex + alreadyExists map[uint64]bool Consensus } @@ -298,16 +298,17 @@ type DirOperation struct { func (dirOp *DirOperation) Process(allocObj *Allocation, connectionID string) ([]fileref.RefEntity, zboxutil.Uint128, error) { refs := make([]fileref.RefEntity, len(allocObj.Blobbers)) dR := &DirRequest{ - allocationID: allocObj.ID, - allocationTx: allocObj.Tx, - connectionID: connectionID, - blobbers: allocObj.Blobbers, - remotePath: dirOp.remotePath, - ctx: dirOp.ctx, - ctxCncl: dirOp.ctxCncl, - dirMask: dirOp.dirMask, - mu: dirOp.maskMU, - wg: &sync.WaitGroup{}, + allocationID: allocObj.ID, + allocationTx: allocObj.Tx, + connectionID: connectionID, + blobbers: allocObj.Blobbers, + remotePath: dirOp.remotePath, + ctx: dirOp.ctx, + ctxCncl: dirOp.ctxCncl, + dirMask: dirOp.dirMask, + mu: dirOp.maskMU, + wg: &sync.WaitGroup{}, + alreadyExists: make(map[uint64]bool), } dR.Consensus = Consensus{ RWMutex: &sync.RWMutex{}, @@ -316,6 +317,7 @@ func (dirOp *DirOperation) Process(allocObj *Allocation, connectionID string) ([ } _ = dR.ProcessWithBlobbers(allocObj) + dirOp.alreadyExists = dR.alreadyExists if !dR.isConsensusOk() { return nil, dR.dirMask, errors.New("consensus_not_met", "directory creation failed due to consensus not met") @@ -330,12 +332,17 @@ func (dirOp *DirOperation) buildChange(refs []fileref.RefEntity, uid uuid.UUID) changes := make([]allocationchange.AllocationChange, len(refs)) for i := dirOp.dirMask; !i.Equals(zboxutil.NewUint128(0)); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) { pos = uint64(i.TrailingZeros()) - newChange := &allocationchange.DirCreateChange{ - RemotePath: dirOp.remotePath, - Uuid: uid, - Timestamp: common.Now(), + if dirOp.alreadyExists[pos] { + newChange := &allocationchange.EmptyFileChange{} + changes[pos] = newChange + } else { + newChange := &allocationchange.DirCreateChange{ + RemotePath: dirOp.remotePath, + Uuid: uid, + Timestamp: common.Now(), + } + changes[pos] = newChange } - changes[pos] = newChange } return changes } @@ -367,5 +374,6 @@ func NewDirOperation(remotePath string, dirMask zboxutil.Uint128, maskMU *sync.M dirOp.consensusThresh = consensusTh dirOp.fullconsensus = fullConsensus dirOp.ctx, dirOp.ctxCncl = context.WithCancel(ctx) + dirOp.alreadyExists = make(map[uint64]bool) return dirOp } diff --git a/zboxcore/sdk/multi_operation_worker.go b/zboxcore/sdk/multi_operation_worker.go index 36079c5d3..c351042c2 100644 --- a/zboxcore/sdk/multi_operation_worker.go +++ b/zboxcore/sdk/multi_operation_worker.go @@ -151,7 +151,7 @@ func (mo *MultiOperation) Process() error { ctxCncl := mo.ctxCncl defer ctxCncl() - errs := make(chan error, 1) + errsSlice := make([]error, len(mo.operations)) mo.operationMask = zboxutil.NewUint128(0) for idx, op := range mo.operations { uid := util.GetNewUUID() @@ -169,13 +169,8 @@ func (mo *MultiOperation) Process() error { refs, mask, err := op.Process(mo.allocationObj, mo.connectionID) // Process with each blobber if err != nil { l.Logger.Error(err) - - select { - case errs <- errors.New("", err.Error()): - default: - } + errsSlice[idx] = errors.New("", err.Error()) ctxCncl() - return } mo.maskMU.Lock() @@ -187,11 +182,15 @@ func (mo *MultiOperation) Process() error { }(op, idx) } wg.Wait() - if ctx.Err() != nil { - return <-errs - } + // Check consensus if mo.operationMask.CountOnes() < mo.consensusThresh { + majorErr := zboxutil.MajorError(errsSlice) + if majorErr != nil { + return errors.New("consensus_not_met", + fmt.Sprintf("Multioperation failed. Required consensus %d got %d. Major error: %s", + mo.consensusThresh, mo.operationMask.CountOnes(), majorErr.Error())) + } return errors.New("consensus_not_met", fmt.Sprintf("Multioperation failed. Required consensus %d got %d", mo.consensusThresh, mo.operationMask.CountOnes())) diff --git a/zboxcore/sdk/upload_worker.go b/zboxcore/sdk/upload_worker.go index 5e90ec375..6ce700cc9 100644 --- a/zboxcore/sdk/upload_worker.go +++ b/zboxcore/sdk/upload_worker.go @@ -32,6 +32,8 @@ func (uo *UploadOperation) Process(allocObj *Allocation, connectionID string) ([ } uo.statusCallback = cu.statusCallback uo.opCode = cu.opCode + uo.fileMeta = cu.fileMeta + uo.fileReader = cu.fileReader err = cu.process() if err != nil { From da1e646b5c6a9f8af1b00574255b8949e882c09e Mon Sep 17 00:00:00 2001 From: Lz Date: Wed, 30 Aug 2023 11:17:23 +0800 Subject: [PATCH 024/134] Feat/update methods in WinSDK (#1198) --- winsdk/status.go | 59 +++++++------------ winsdk/status_test.go | 28 --------- winsdk/storage.go | 128 +++++++++--------------------------------- 3 files changed, 48 insertions(+), 167 deletions(-) delete mode 100644 winsdk/status_test.go diff --git a/winsdk/status.go b/winsdk/status.go index 557877b73..6683d809c 100644 --- a/winsdk/status.go +++ b/winsdk/status.go @@ -1,17 +1,11 @@ package main import ( - "errors" - "sync" - lru "github.com/hashicorp/golang-lru/v2" ) var ( - statusCaches, _ = lru.New[string, *StatusCallback](100) - - ErrInvalidUploadID = errors.New("bulkupload: invalid upload id") - ErrInvalidRemotePath = errors.New("bulkupload: invalid remotePath") + statusCaches, _ = lru.New[string, *Status](1000) ) type Status struct { @@ -24,66 +18,53 @@ type Status struct { } type StatusCallback struct { - sync.Mutex - status map[string]*Status -} - -func (c *StatusCallback) Get(remotePath string) *Status { - c.Lock() - defer c.Unlock() - s, ok := c.status[remotePath] - if ok { - return s - } - - return s } -func (c *StatusCallback) getStatus(remotePath string) *Status { - s, ok := c.status[remotePath] +func (c *StatusCallback) getOrCreate(lookupHash string) *Status { + s, ok := statusCaches.Get(lookupHash) if !ok { s = &Status{} - c.status[remotePath] = s + statusCaches.Add(lookupHash, s) } return s } func (c *StatusCallback) Started(allocationID, remotePath string, op int, totalBytes int) { - c.Lock() - defer c.Unlock() log.Info("status: Started ", remotePath, " ", totalBytes) - s := c.getStatus(remotePath) + lookupHash := getLookupHash(allocationID, remotePath) + s := c.getOrCreate(lookupHash) s.Started = true s.TotalBytes = totalBytes - s.LookupHash = getLookupHash(allocationID, remotePath) + s.LookupHash = lookupHash } func (c *StatusCallback) InProgress(allocationID, remotePath string, op int, completedBytes int, data []byte) { - c.Lock() - defer c.Unlock() log.Info("status: InProgress ", remotePath, " ", completedBytes) - s := c.getStatus(remotePath) + lookupHash := getLookupHash(allocationID, remotePath) + s := c.getOrCreate(lookupHash) s.CompletedBytes = completedBytes - s.LookupHash = getLookupHash(allocationID, remotePath) + s.LookupHash = lookupHash + if completedBytes >= s.TotalBytes { + s.Completed = true + } } func (c *StatusCallback) Error(allocationID string, remotePath string, op int, err error) { - c.Lock() - defer c.Unlock() log.Info("status: Error ", remotePath, " ", err) - s := c.getStatus(remotePath) + lookupHash := getLookupHash(allocationID, remotePath) + s := c.getOrCreate(lookupHash) s.Error = err.Error() - s.LookupHash = getLookupHash(allocationID, remotePath) + s.LookupHash = lookupHash } func (c *StatusCallback) Completed(allocationID, remotePath string, filename string, mimetype string, size int, op int) { - c.Lock() - defer c.Unlock() log.Info("status: Completed ", remotePath) - s := c.getStatus(remotePath) + lookupHash := getLookupHash(allocationID, remotePath) + s := c.getOrCreate(lookupHash) s.Completed = true - s.LookupHash = getLookupHash(allocationID, remotePath) + s.LookupHash = lookupHash + s.CompletedBytes = s.TotalBytes } func (c *StatusCallback) CommitMetaCompleted(request, response string, err error) { diff --git a/winsdk/status_test.go b/winsdk/status_test.go deleted file mode 100644 index 62787f5cc..000000000 --- a/winsdk/status_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "errors" - "testing" - - "github.com/stretchr/testify/require" -) - -func TestStatusCallback(t *testing.T) { - - status := &StatusCallback{ - status: make(map[string]*Status), - } - - status.Started("allocationId", "/remotePath", 0, 100) - status.InProgress("allocationId", "/remotePath", 0, 100, nil) - status.Completed("allocationId", "/remotePath", "", "", 100, 0) - status.Error("allocationId", "/remotePath", 0, errors.New("err")) - - s := status.Get("/remotePath") - - require.True(t, s.Started) - require.True(t, s.Completed) - require.EqualValues(t, 100, s.TotalBytes) - require.EqualValues(t, 100, s.CompletedBytes) - require.Equal(t, "err", s.Error) -} diff --git a/winsdk/storage.go b/winsdk/storage.go index 005c3798f..56c8ab658 100644 --- a/winsdk/storage.go +++ b/winsdk/storage.go @@ -70,63 +70,6 @@ func GetAllocation(allocationID *C.char) *C.char { return WithJSON(getAllocation(allocID)) } -// CreateDir create directory -// -// return -// { -// "error":"", -// "result":"true", -// } -// -//export CreateDir -func CreateDir(allocationID, path *C.char) *C.char { - allocID := C.GoString(allocationID) - - alloc, err := getAllocation(allocID) - if err != nil { - return WithJSON(false, err) - } - - s := C.GoString(path) - err = alloc.CreateDir(s) - - if err != nil { - return WithJSON(false, err) - } - - return WithJSON(true, nil) - -} - -// Rename rename path -// -// return -// { -// "error":"", -// "result":"true", -// } -// -//export Rename -func Rename(allocationID, path, destName *C.char) *C.char { - allocID := C.GoString(allocationID) - - alloc, err := getAllocation(allocID) - if err != nil { - return WithJSON(false, err) - } - - s := C.GoString(path) - d := C.GoString(destName) - err = alloc.RenameObject(s, d) - - if err != nil { - return WithJSON(false, err) - } - - return WithJSON(true, nil) - -} - // Delete delete path // // return @@ -152,25 +95,16 @@ func Delete(allocationID, path *C.char) *C.char { return WithJSON(false, err) } + log.Info("winsdk: deleted ", s) + return WithJSON(true, nil) } type MultiOperationOption struct { - OperationType string `json:"operationType,omitempty"` - RemotePath string `json:"remotePath,omitempty"` - DestName string `json:"destName,omitempty"` // Required only for rename operation - DestPath string `json:"destPath,omitempty"` // Required for copy and move operation` -} - -type MultiUploadOption struct { - FilePath string `json:"filePath,omitempty"` - FileName string `json:"fileName,omitempty"` - RemotePath string `json:"remotePath,omitempty"` - ThumbnailPath string `json:"thumbnailPath,omitempty"` - Encrypt bool `json:"encrypt,omitempty"` - ChunkNumber int `json:"chunkNumber,omitempty"` - IsUpdate bool `json:"isUpdate,omitempty"` - IsWebstreaming bool `json:"isWebstreaming,omitempty"` + OperationType string `json:"OperationType,omitempty"` + RemotePath string `json:"RemotePath,omitempty"` + DestName string `json:"DestName,omitempty"` // Required only for rename operation + DestPath string `json:"DestPath,omitempty"` // Required for copy and move operation` } // MultiOperation - do copy, move, delete and createdir operation together @@ -188,12 +122,13 @@ func MultiOperation(_allocationID, _jsonMultiOperationOptions *C.char) *C.char { allocationID := C.GoString(_allocationID) jsonMultiOperationOptions := C.GoString(_jsonMultiOperationOptions) if allocationID == "" { - return WithJSON(nil, errors.New("AllocationID is required")) + return WithJSON(false, errors.New("AllocationID is required")) } + var options []MultiOperationOption err := json.Unmarshal([]byte(jsonMultiOperationOptions), &options) if err != nil { - return WithJSON(nil, err) + return WithJSON(false, err) } totalOp := len(options) operations := make([]sdk.OperationRequest, totalOp) @@ -204,14 +139,16 @@ func MultiOperation(_allocationID, _jsonMultiOperationOptions *C.char) *C.char { DestName: op.DestName, DestPath: op.DestPath, } + + log.Info("multi-operation: index=", idx, " op=", op.OperationType, " remotePath=", op.RemotePath, " destName=", op.DestName, " destPath=", op.DestPath) } allocationObj, err := getAllocation(allocationID) if err != nil { - return WithJSON(nil, err) + return WithJSON(false, err) } err = allocationObj.DoMultiOperation(operations) if err != nil { - return WithJSON(nil, err) + return WithJSON(false, err) } return WithJSON(true, nil) @@ -307,7 +244,7 @@ func MultiDownload(_allocationID, _jsonMultiDownloadOptions *C.char) error { // } // //export BulkUpload -func BulkUpload(uploadID, allocationID, files *C.char) *C.char { +func BulkUpload(allocationID, files *C.char) *C.char { allocID := C.GoString(allocationID) workdir, _ := os.UserHomeDir() jsFiles := C.GoString(files) @@ -326,9 +263,7 @@ func BulkUpload(uploadID, allocationID, files *C.char) *C.char { isUpdates := make([]bool, totalUploads) isWebstreaming := make([]bool, totalUploads) - statusBar := &StatusCallback{ - status: make(map[string]*Status), - } + statusBar := &StatusCallback{} for idx, option := range options { filePaths[idx] = option.Path @@ -339,7 +274,7 @@ func BulkUpload(uploadID, allocationID, files *C.char) *C.char { isUpdates[idx] = option.IsUpdate isWebstreaming[idx] = option.IsWebstreaming encrypts[idx] = option.Encrypt - statusBar.status[option.RemotePath+option.Name] = &Status{} + statusCaches.Add(getLookupHash(allocID, option.RemotePath+option.Name), &Status{}) } a, err := getAllocation(allocID) @@ -347,8 +282,6 @@ func BulkUpload(uploadID, allocationID, files *C.char) *C.char { return WithJSON(nil, err) } - statusCaches.Add(C.GoString(uploadID), statusBar) - err = a.StartMultiUpload(workdir, filePaths, fileNames, thumbnailPaths, encrypts, chunkNumbers, remotePaths, isUpdates, isWebstreaming, statusBar) if err != nil { return WithJSON(nil, err) @@ -358,27 +291,22 @@ func BulkUpload(uploadID, allocationID, files *C.char) *C.char { // GetUploadStatus - get upload status // ## Inputs -// - uploadID -// - remotePath -// return -// { -// "error":"", -// "result":"{'Started':false,'CompletedBytes': 0,Error:”,'Completed':false}", -// } +// - lookupHash +// +// ## Outputs +// +// { +// "error":"", +// "result":"{'Started':false,'CompletedBytes': 0,Error:”,'Completed':false}", +// } // //export GetUploadStatus -func GetUploadStatus(uploadID, remotePath *C.char) *C.char { - id := C.GoString(uploadID) - scb, ok := statusCaches.Get(id) +func GetUploadStatus(lookupHash *C.char) *C.char { - if !ok { - return WithJSON(nil, ErrInvalidUploadID) - } + s, ok := statusCaches.Get(C.GoString(lookupHash)) - s := scb.getStatus(C.GoString(remotePath)) - - if s == nil { - return WithJSON(nil, ErrInvalidRemotePath) + if !ok { + s = &Status{} } return WithJSON(s, nil) From f18a03897672a1cda871a32695769a65debaa5a3 Mon Sep 17 00:00:00 2001 From: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Date: Wed, 30 Aug 2023 19:50:36 +0530 Subject: [PATCH 025/134] delete dir in repair (#1196) * delete dir in repair * replace ioutil * fix unit test * fix list worker test * fix rename dir error --- zboxcore/allocationchange/renameobject.go | 2 +- zboxcore/sdk/allocation_test.go | 7 ++++- zboxcore/sdk/listworker.go | 8 +++-- zboxcore/sdk/listworker_test.go | 5 +-- zboxcore/sdk/repairworker.go | 15 +++++++++ zboxcore/sdk/rollback.go | 38 +++++++++-------------- 6 files changed, 45 insertions(+), 30 deletions(-) diff --git a/zboxcore/allocationchange/renameobject.go b/zboxcore/allocationchange/renameobject.go index a0d0de28e..d9e3955a8 100644 --- a/zboxcore/allocationchange/renameobject.go +++ b/zboxcore/allocationchange/renameobject.go @@ -47,7 +47,7 @@ func (ch *RenameFileChange) ProcessChange(rootRef *fileref.Ref, _ map[string]str if ch.ObjectTree.GetType() == fileref.FILE { affectedRef = &(ch.ObjectTree.(*fileref.FileRef)).Ref } else { - affectedRef = ch.ObjectTree.(*fileref.Ref) + err = errors.New("invalid_rename_op", "Object to rename is not a file use move instead") } affectedRef.Path = pathutil.Join(parentPath, ch.NewName) diff --git a/zboxcore/sdk/allocation_test.go b/zboxcore/sdk/allocation_test.go index 56c9b5587..5570a5f3a 100644 --- a/zboxcore/sdk/allocation_test.go +++ b/zboxcore/sdk/allocation_test.go @@ -1601,7 +1601,9 @@ func TestAllocation_ListDirFromAuthTicket(t *testing.T) { DataShards: 2, ParityShards: 2, } - + if tt.parameters.expectedResult != nil { + tt.parameters.expectedResult.deleteMask = zboxutil.NewUint128(1).Lsh(uint64(a.DataShards + a.ParityShards)).Sub64(1) + } if tt.setup != nil { if teardown := tt.setup(t, tt.name, a, &mockClient); teardown != nil { defer teardown(t) @@ -1881,6 +1883,9 @@ func TestAllocation_listDir(t *testing.T) { DataShards: 2, ParityShards: 2, } + if tt.parameters.expectedResult != nil { + tt.parameters.expectedResult.deleteMask = zboxutil.NewUint128(1).Lsh(uint64(a.DataShards + a.ParityShards)).Sub64(1) + } a.InitAllocation() sdkInitialized = true for i := 0; i < numBlobbers; i++ { diff --git a/zboxcore/sdk/listworker.go b/zboxcore/sdk/listworker.go index 813ed9d82..daeec0bcd 100644 --- a/zboxcore/sdk/listworker.go +++ b/zboxcore/sdk/listworker.go @@ -58,6 +58,7 @@ type ListResult struct { UpdatedAt common.Timestamp `json:"updated_at"` Children []*ListResult `json:"list"` Consensus `json:"-"` + deleteMask zboxutil.Uint128 `json:"-"` } func (req *ListRequest) getListInfoFromBlobber(blobber *blockchain.StorageNode, blobberIdx int, rspCh chan<- *listResponse) { @@ -146,7 +147,9 @@ func (req *ListRequest) getlistFromBlobbers() []*listResponse { func (req *ListRequest) GetListFromBlobbers() (*ListResult, error) { lR := req.getlistFromBlobbers() - result := &ListResult{} + result := &ListResult{ + deleteMask: zboxutil.NewUint128(1).Lsh(uint64(len(req.blobbers))).Sub64(1), + } selected := make(map[string]*ListResult) childResultMap := make(map[string]*ListResult) var err error @@ -157,6 +160,7 @@ func (req *ListRequest) GetListFromBlobbers() (*ListResult, error) { if ti.err != nil { err = ti.err errNum++ + result.deleteMask = result.deleteMask.And(zboxutil.NewUint128(1).Lsh(uint64(ti.blobberIdx)).Not()) continue } if ti.ref == nil { @@ -193,7 +197,7 @@ func (req *ListRequest) GetListFromBlobbers() (*ListResult, error) { } } - if errNum == len(lR) { + if errNum >= req.consensusThresh && !req.forRepair { return nil, err } diff --git a/zboxcore/sdk/listworker_test.go b/zboxcore/sdk/listworker_test.go index 619f88ee8..4efbacefd 100644 --- a/zboxcore/sdk/listworker_test.go +++ b/zboxcore/sdk/listworker_test.go @@ -299,8 +299,9 @@ func TestListRequest_GetListFromBlobbers(t *testing.T) { } got, _ := req.GetListFromBlobbers() expectedResult := &ListResult{ - Type: mockType, - Size: 0, + Type: mockType, + Size: 0, + deleteMask: zboxutil.NewUint128(1).Lsh(uint64(len(req.blobbers))).Sub64(1), } if !tt.wantErr { require.EqualValues(expectedResult, got) diff --git a/zboxcore/sdk/repairworker.go b/zboxcore/sdk/repairworker.go index 7e23dcd04..ea999d34c 100644 --- a/zboxcore/sdk/repairworker.go +++ b/zboxcore/sdk/repairworker.go @@ -79,6 +79,21 @@ func (r *RepairRequest) iterateDir(a *Allocation, dir *ListResult) { return } } + if len(dir.Children) == 0 { + if dir.deleteMask.CountOnes() > 0 { + l.Logger.Info("Deleting minority shards for the path :", zap.Any("path", dir.Path)) + consensus := dir.deleteMask.CountOnes() + if consensus < a.DataShards { + + err := a.deleteFile(dir.Path, 0, consensus, dir.deleteMask) + if err != nil { + l.Logger.Error("repair_file_failed", zap.Error(err)) + return + } + r.filesRepaired++ + } + } + } for _, childDir := range dir.Children { if r.checkForCancel(a) { return diff --git a/zboxcore/sdk/rollback.go b/zboxcore/sdk/rollback.go index dc2216548..1b50772a3 100644 --- a/zboxcore/sdk/rollback.go +++ b/zboxcore/sdk/rollback.go @@ -5,7 +5,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "mime/multipart" "sync" "sync/atomic" @@ -73,7 +73,7 @@ func GetWritemarker(allocID, allocTx, id, baseUrl string) (*LatestPrevWriteMarke time.Sleep(time.Duration(r) * time.Second) continue } - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("writemarker error response %s with status %d", body, resp.StatusCode) @@ -182,7 +182,7 @@ func (rb *RollbackBlobber) processRollback(ctx context.Context, tx string) error return } - respBody, err = ioutil.ReadAll(resp.Body) + respBody, err = io.ReadAll(resp.Body) if err != nil { l.Logger.Error("Response read: ", err) return @@ -245,8 +245,11 @@ func (a *Allocation) CheckAllocStatus() (AllocStatus, error) { versionMap := make(map[string][]*RollbackBlobber) - var prevVersion string - var latestVersion string + var ( + prevVersion string + latestVersion string + highestTS int64 + ) for rb := range markerChan { @@ -256,10 +259,14 @@ func (a *Allocation) CheckAllocStatus() (AllocStatus, error) { version := rb.lpm.LatestWM.FileMetaRoot + if highestTS < rb.lpm.LatestWM.Timestamp { + prevVersion = latestVersion + highestTS = rb.lpm.LatestWM.Timestamp + latestVersion = version + } + if prevVersion == "" { prevVersion = version - } else if prevVersion != version && latestVersion == "" { - latestVersion = version } if _, ok := versionMap[version]; !ok { @@ -274,23 +281,6 @@ func (a *Allocation) CheckAllocStatus() (AllocStatus, error) { return Commit, nil } - maxTimestamp := int64(0) - for _, rb := range versionMap[latestVersion] { - if rb.lpm.LatestWM.Timestamp > maxTimestamp { - maxTimestamp = rb.lpm.LatestWM.Timestamp - } - } - toFlip := false - for _, rb := range versionMap[prevVersion] { - if rb.lpm.LatestWM.Timestamp > maxTimestamp { - toFlip = true - break - } - } - if toFlip { - prevVersion, latestVersion = latestVersion, prevVersion - } - req := a.DataShards if len(versionMap[latestVersion]) > req { From e12de4c620cc6913f9df14959236f62f9d6a7b35 Mon Sep 17 00:00:00 2001 From: YarikRevich Date: Wed, 30 Aug 2023 18:03:39 +0200 Subject: [PATCH 026/134] fix: fixed bugs --- wasmsdk/bridge.go | 25 +++++++++++++++++-------- zcnbridge/bridge.go | 37 ++++++++++++++++++------------------- zcnbridge/config.go | 12 ++++++------ 3 files changed, 41 insertions(+), 33 deletions(-) diff --git a/wasmsdk/bridge.go b/wasmsdk/bridge.go index d0d00178a..0195915ed 100644 --- a/wasmsdk/bridge.go +++ b/wasmsdk/bridge.go @@ -3,11 +3,13 @@ package main import ( "context" "encoding/json" + "path" "strconv" "time" "github.com/0chain/gosdk/zcnbridge" "github.com/0chain/gosdk/zcnbridge/errors" + "github.com/0chain/gosdk/zcnbridge/transaction" "github.com/0chain/gosdk/zcnbridge/wallet" "github.com/0chain/gosdk/zcncore" "github.com/ethereum/go-ethereum/ethclient" @@ -34,15 +36,22 @@ func initBridge( return errors.New("wallet_error", err.Error()) } + transactionProvider := transaction.NewTransactionProvider() + + keyStore := zcnbridge.NewKeyStore( + path.Join(".", zcnbridge.EthereumWalletStorageDir)) + bridge = &zcnbridge.BridgeClient{ - EthereumAddress: ethereumAddress, - BridgeAddress: bridgeAddress, - AuthorizersAddress: authorizersAddress, - TokenAddress: tokenAddress, - Password: "", - GasLimit: gasLimit, - ConsensusThreshold: consensusThreshold, - EthereumClient: ethereumClient, + EthereumAddress: ethereumAddress, + BridgeAddress: bridgeAddress, + AuthorizersAddress: authorizersAddress, + TokenAddress: tokenAddress, + Password: "", + GasLimit: gasLimit, + ConsensusThreshold: consensusThreshold, + EthereumClient: ethereumClient, + TransactionProvider: transactionProvider, + KeyStore: keyStore, } return nil diff --git a/zcnbridge/bridge.go b/zcnbridge/bridge.go index a5992e72e..fe29bf250 100644 --- a/zcnbridge/bridge.go +++ b/zcnbridge/bridge.go @@ -63,11 +63,10 @@ func (b *BridgeClient) CreateSignedTransactionFromKeyStore(client EthereumClient password = b.Password ) - // ks := b.getKeyStore(path.Join(b.Homedir, EthereumWalletStorageDir)) signer := accounts.Account{ Address: signerAddress, } - signerAcc, err := b.keyStore.Find(signer) + signerAcc, err := b.KeyStore.Find(signer) if err != nil { Logger.Fatal(errors.Wrapf(err, "signer: %s", signerAddress.Hex())) } @@ -87,12 +86,12 @@ func (b *BridgeClient) CreateSignedTransactionFromKeyStore(client EthereumClient Logger.Fatal(err) } - err = b.keyStore.TimedUnlock(signer, password, time.Second*2) + err = b.KeyStore.TimedUnlock(signer, password, time.Second*2) if err != nil { Logger.Fatal(err) } - opts, err := bind.NewKeyStoreTransactorWithChainID(b.keyStore.GetEthereumKeyStore(), signerAcc, chainID) + opts, err := bind.NewKeyStoreTransactorWithChainID(b.KeyStore.GetEthereumKeyStore(), signerAcc, chainID) if err != nil { Logger.Fatal(err) } @@ -123,7 +122,7 @@ func (b *BridgeClient) prepareAuthorizers(ctx context.Context, method string, pa from := common.HexToAddress(b.EthereumAddress) // Gas limits in units - gasLimitUnits, err := b.ethereumClient.EstimateGas(ctx, eth.CallMsg{ + gasLimitUnits, err := b.EthereumClient.EstimateGas(ctx, eth.CallMsg{ To: &contractAddress, From: from, Data: pack, @@ -135,10 +134,10 @@ func (b *BridgeClient) prepareAuthorizers(ctx context.Context, method string, pa // Update gas limits + 10% gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() - transactOpts := b.CreateSignedTransactionFromKeyStore(b.ethereumClient, gasLimitUnits) + transactOpts := b.CreateSignedTransactionFromKeyStore(b.EthereumClient, gasLimitUnits) // Authorizers instance - authorizersInstance, err := authorizers.NewAuthorizers(contractAddress, b.ethereumClient) + authorizersInstance, err := authorizers.NewAuthorizers(contractAddress, b.EthereumClient) if err != nil { return nil, nil, errors.Wrap(err, "failed to create authorizers instance") } @@ -212,7 +211,7 @@ func (b *BridgeClient) IncreaseBurnerAllowance(ctx context.Context, amountWei We return nil, errors.Wrap(err, "failed to pack arguments") } - gasLimitUnits, err := b.ethereumClient.EstimateGas(ctx, eth.CallMsg{ + gasLimitUnits, err := b.EthereumClient.EstimateGas(ctx, eth.CallMsg{ To: &tokenAddress, From: fromAddress, Data: pack, @@ -223,9 +222,9 @@ func (b *BridgeClient) IncreaseBurnerAllowance(ctx context.Context, amountWei We gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() - transactOpts := b.CreateSignedTransactionFromKeyStore(b.ethereumClient, gasLimitUnits) + transactOpts := b.CreateSignedTransactionFromKeyStore(b.EthereumClient, gasLimitUnits) - wzcnTokenInstance, err := erc20.NewERC20(tokenAddress, b.ethereumClient) + wzcnTokenInstance, err := erc20.NewERC20(tokenAddress, b.EthereumClient) if err != nil { return nil, errors.Wrap(err, "failed to initialize WZCN-ERC20 instance") } @@ -265,7 +264,7 @@ func (b *BridgeClient) GetBalance() (*big.Int, error) { tokenAddress := common.HexToAddress(b.TokenAddress) fromAddress := common.HexToAddress(b.EthereumAddress) - wzcnTokenInstance, err := erc20.NewERC20(tokenAddress, b.ethereumClient) + wzcnTokenInstance, err := erc20.NewERC20(tokenAddress, b.EthereumClient) if err != nil { return nil, errors.Wrap(err, "failed to initialize WZCN-ERC20 instance") } @@ -291,12 +290,12 @@ func (b *BridgeClient) SignWithEthereumChain(message string) ([]byte, error) { Address: common.HexToAddress(b.EthereumAddress), } - signerAcc, err := b.keyStore.Find(signer) + signerAcc, err := b.KeyStore.Find(signer) if err != nil { Logger.Fatal(err) } - signature, err := b.keyStore.SignHash(signerAcc, hash.Bytes()) + signature, err := b.KeyStore.SignHash(signerAcc, hash.Bytes()) if err != nil { return nil, err } @@ -315,7 +314,7 @@ func (b *BridgeClient) GetUserNonceMinted(ctx context.Context, rawEthereumAddres contractAddress := common.HexToAddress(b.BridgeAddress) var bridgeInstance *binding.Bridge - bridgeInstance, err := binding.NewBridge(contractAddress, b.ethereumClient) + bridgeInstance, err := binding.NewBridge(contractAddress, b.EthereumClient) if err != nil { return nil, errors.Wrap(err, "failed to create bridge instance") } @@ -432,7 +431,7 @@ func (b *BridgeClient) BurnWZCN(ctx context.Context, amountTokens uint64) (*type // MintZCN mints ZCN tokens after receiving proof-of-burn of WZCN tokens func (b *BridgeClient) MintZCN(ctx context.Context, payload *zcnsc.MintPayload) (string, error) { - trx, err := b.transactionProvider.NewTransactionEntity(0) + trx, err := b.TransactionProvider.NewTransactionEntity(0) if err != nil { log.Logger.Fatal("failed to create new transaction", zap.Error(err)) } @@ -468,7 +467,7 @@ func (b *BridgeClient) BurnZCN(ctx context.Context, amount, txnfee uint64) (tran EthereumAddress: b.EthereumAddress, } - trx, err := b.transactionProvider.NewTransactionEntity(txnfee) + trx, err := b.TransactionProvider.NewTransactionEntity(txnfee) if err != nil { log.Logger.Fatal("failed to create new transaction", zap.Error(err)) } @@ -528,7 +527,7 @@ func (b *BridgeClient) prepareBridge(ctx context.Context, ethereumAddress, metho //Gas limits in units fromAddress := common.HexToAddress(ethereumAddress) - gasLimitUnits, err := b.ethereumClient.EstimateGas(ctx, eth.CallMsg{ + gasLimitUnits, err := b.EthereumClient.EstimateGas(ctx, eth.CallMsg{ To: &contractAddress, From: fromAddress, Data: pack, @@ -540,10 +539,10 @@ func (b *BridgeClient) prepareBridge(ctx context.Context, ethereumAddress, metho //Update gas limits + 10% gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() - transactOpts := b.CreateSignedTransactionFromKeyStore(b.ethereumClient, gasLimitUnits) + transactOpts := b.CreateSignedTransactionFromKeyStore(b.EthereumClient, gasLimitUnits) // BridgeClient instance - bridgeInstance, err := binding.NewBridge(contractAddress, b.ethereumClient) + bridgeInstance, err := binding.NewBridge(contractAddress, b.EthereumClient) if err != nil { return nil, nil, errors.Wrap(err, "failed to create bridge instance") } diff --git a/zcnbridge/config.go b/zcnbridge/config.go index 2cdfde17f..7b9ce8252 100644 --- a/zcnbridge/config.go +++ b/zcnbridge/config.go @@ -29,9 +29,9 @@ type BridgeSDKConfig struct { } type BridgeClient struct { - keyStore KeyStore - transactionProvider transaction.TransactionProvider - ethereumClient EthereumClient + KeyStore + transaction.TransactionProvider + EthereumClient BridgeAddress, TokenAddress, @@ -61,9 +61,9 @@ func createBridgeClient(cfg *viper.Viper, ethereumClient EthereumClient, transac Password: cfg.GetString("bridge.password"), GasLimit: cfg.GetUint64("bridge.gas_limit"), ConsensusThreshold: cfg.GetFloat64("bridge.consensus_threshold"), - ethereumClient: ethereumClient, - transactionProvider: transactionProvider, - keyStore: keyStore, + EthereumClient: ethereumClient, + TransactionProvider: transactionProvider, + KeyStore: keyStore, } } From 30178b00d98138397571ebf62f10a9730edd17a4 Mon Sep 17 00:00:00 2001 From: YarikRevich Date: Wed, 30 Aug 2023 18:21:11 +0200 Subject: [PATCH 027/134] fix: fixed bugs --- wasmsdk/bridge.go | 24 +++++------ zcnbridge/bridge.go | 36 ++++++++-------- zcnbridge/bridge_test.go | 13 +++++- zcnbridge/config.go | 93 ++++++++++++++++++++++------------------ 4 files changed, 93 insertions(+), 73 deletions(-) diff --git a/wasmsdk/bridge.go b/wasmsdk/bridge.go index 0195915ed..730a16c3c 100644 --- a/wasmsdk/bridge.go +++ b/wasmsdk/bridge.go @@ -41,18 +41,18 @@ func initBridge( keyStore := zcnbridge.NewKeyStore( path.Join(".", zcnbridge.EthereumWalletStorageDir)) - bridge = &zcnbridge.BridgeClient{ - EthereumAddress: ethereumAddress, - BridgeAddress: bridgeAddress, - AuthorizersAddress: authorizersAddress, - TokenAddress: tokenAddress, - Password: "", - GasLimit: gasLimit, - ConsensusThreshold: consensusThreshold, - EthereumClient: ethereumClient, - TransactionProvider: transactionProvider, - KeyStore: keyStore, - } + bridge = zcnbridge.NewBridgeClient( + bridgeAddress, + tokenAddress, + authorizersAddress, + ethereumAddress, + "", + gasLimit, + consensusThreshold, + ethereumClient, + transactionProvider, + keyStore, + ) return nil } diff --git a/zcnbridge/bridge.go b/zcnbridge/bridge.go index fe29bf250..9fd90d0dc 100644 --- a/zcnbridge/bridge.go +++ b/zcnbridge/bridge.go @@ -66,7 +66,7 @@ func (b *BridgeClient) CreateSignedTransactionFromKeyStore(client EthereumClient signer := accounts.Account{ Address: signerAddress, } - signerAcc, err := b.KeyStore.Find(signer) + signerAcc, err := b.keyStore.Find(signer) if err != nil { Logger.Fatal(errors.Wrapf(err, "signer: %s", signerAddress.Hex())) } @@ -86,12 +86,12 @@ func (b *BridgeClient) CreateSignedTransactionFromKeyStore(client EthereumClient Logger.Fatal(err) } - err = b.KeyStore.TimedUnlock(signer, password, time.Second*2) + err = b.keyStore.TimedUnlock(signer, password, time.Second*2) if err != nil { Logger.Fatal(err) } - opts, err := bind.NewKeyStoreTransactorWithChainID(b.KeyStore.GetEthereumKeyStore(), signerAcc, chainID) + opts, err := bind.NewKeyStoreTransactorWithChainID(b.keyStore.GetEthereumKeyStore(), signerAcc, chainID) if err != nil { Logger.Fatal(err) } @@ -122,7 +122,7 @@ func (b *BridgeClient) prepareAuthorizers(ctx context.Context, method string, pa from := common.HexToAddress(b.EthereumAddress) // Gas limits in units - gasLimitUnits, err := b.EthereumClient.EstimateGas(ctx, eth.CallMsg{ + gasLimitUnits, err := b.ethereumClient.EstimateGas(ctx, eth.CallMsg{ To: &contractAddress, From: from, Data: pack, @@ -134,10 +134,10 @@ func (b *BridgeClient) prepareAuthorizers(ctx context.Context, method string, pa // Update gas limits + 10% gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() - transactOpts := b.CreateSignedTransactionFromKeyStore(b.EthereumClient, gasLimitUnits) + transactOpts := b.CreateSignedTransactionFromKeyStore(b.ethereumClient, gasLimitUnits) // Authorizers instance - authorizersInstance, err := authorizers.NewAuthorizers(contractAddress, b.EthereumClient) + authorizersInstance, err := authorizers.NewAuthorizers(contractAddress, b.ethereumClient) if err != nil { return nil, nil, errors.Wrap(err, "failed to create authorizers instance") } @@ -211,7 +211,7 @@ func (b *BridgeClient) IncreaseBurnerAllowance(ctx context.Context, amountWei We return nil, errors.Wrap(err, "failed to pack arguments") } - gasLimitUnits, err := b.EthereumClient.EstimateGas(ctx, eth.CallMsg{ + gasLimitUnits, err := b.ethereumClient.EstimateGas(ctx, eth.CallMsg{ To: &tokenAddress, From: fromAddress, Data: pack, @@ -222,9 +222,9 @@ func (b *BridgeClient) IncreaseBurnerAllowance(ctx context.Context, amountWei We gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() - transactOpts := b.CreateSignedTransactionFromKeyStore(b.EthereumClient, gasLimitUnits) + transactOpts := b.CreateSignedTransactionFromKeyStore(b.ethereumClient, gasLimitUnits) - wzcnTokenInstance, err := erc20.NewERC20(tokenAddress, b.EthereumClient) + wzcnTokenInstance, err := erc20.NewERC20(tokenAddress, b.ethereumClient) if err != nil { return nil, errors.Wrap(err, "failed to initialize WZCN-ERC20 instance") } @@ -264,7 +264,7 @@ func (b *BridgeClient) GetBalance() (*big.Int, error) { tokenAddress := common.HexToAddress(b.TokenAddress) fromAddress := common.HexToAddress(b.EthereumAddress) - wzcnTokenInstance, err := erc20.NewERC20(tokenAddress, b.EthereumClient) + wzcnTokenInstance, err := erc20.NewERC20(tokenAddress, b.ethereumClient) if err != nil { return nil, errors.Wrap(err, "failed to initialize WZCN-ERC20 instance") } @@ -290,12 +290,12 @@ func (b *BridgeClient) SignWithEthereumChain(message string) ([]byte, error) { Address: common.HexToAddress(b.EthereumAddress), } - signerAcc, err := b.KeyStore.Find(signer) + signerAcc, err := b.keyStore.Find(signer) if err != nil { Logger.Fatal(err) } - signature, err := b.KeyStore.SignHash(signerAcc, hash.Bytes()) + signature, err := b.keyStore.SignHash(signerAcc, hash.Bytes()) if err != nil { return nil, err } @@ -314,7 +314,7 @@ func (b *BridgeClient) GetUserNonceMinted(ctx context.Context, rawEthereumAddres contractAddress := common.HexToAddress(b.BridgeAddress) var bridgeInstance *binding.Bridge - bridgeInstance, err := binding.NewBridge(contractAddress, b.EthereumClient) + bridgeInstance, err := binding.NewBridge(contractAddress, b.ethereumClient) if err != nil { return nil, errors.Wrap(err, "failed to create bridge instance") } @@ -431,7 +431,7 @@ func (b *BridgeClient) BurnWZCN(ctx context.Context, amountTokens uint64) (*type // MintZCN mints ZCN tokens after receiving proof-of-burn of WZCN tokens func (b *BridgeClient) MintZCN(ctx context.Context, payload *zcnsc.MintPayload) (string, error) { - trx, err := b.TransactionProvider.NewTransactionEntity(0) + trx, err := b.transactionProvider.NewTransactionEntity(0) if err != nil { log.Logger.Fatal("failed to create new transaction", zap.Error(err)) } @@ -467,7 +467,7 @@ func (b *BridgeClient) BurnZCN(ctx context.Context, amount, txnfee uint64) (tran EthereumAddress: b.EthereumAddress, } - trx, err := b.TransactionProvider.NewTransactionEntity(txnfee) + trx, err := b.transactionProvider.NewTransactionEntity(txnfee) if err != nil { log.Logger.Fatal("failed to create new transaction", zap.Error(err)) } @@ -527,7 +527,7 @@ func (b *BridgeClient) prepareBridge(ctx context.Context, ethereumAddress, metho //Gas limits in units fromAddress := common.HexToAddress(ethereumAddress) - gasLimitUnits, err := b.EthereumClient.EstimateGas(ctx, eth.CallMsg{ + gasLimitUnits, err := b.ethereumClient.EstimateGas(ctx, eth.CallMsg{ To: &contractAddress, From: fromAddress, Data: pack, @@ -539,10 +539,10 @@ func (b *BridgeClient) prepareBridge(ctx context.Context, ethereumAddress, metho //Update gas limits + 10% gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() - transactOpts := b.CreateSignedTransactionFromKeyStore(b.EthereumClient, gasLimitUnits) + transactOpts := b.CreateSignedTransactionFromKeyStore(b.ethereumClient, gasLimitUnits) // BridgeClient instance - bridgeInstance, err := binding.NewBridge(contractAddress, b.EthereumClient) + bridgeInstance, err := binding.NewBridge(contractAddress, b.ethereumClient) if err != nil { return nil, nil, errors.Wrap(err, "failed to create bridge instance") } diff --git a/zcnbridge/bridge_test.go b/zcnbridge/bridge_test.go index 177862800..873390e43 100644 --- a/zcnbridge/bridge_test.go +++ b/zcnbridge/bridge_test.go @@ -228,7 +228,18 @@ func getBridgeClient(ethereumClient EthereumClient, transactionProvider transact cfg.SetDefault("bridge.gas_limit", 0) cfg.SetDefault("bridge.consensus_threshold", 0) - return createBridgeClient(cfg, ethereumClient, transactionProvider, keyStore) + return NewBridgeClient( + cfg.GetString("bridge.bridge_address"), + cfg.GetString("bridge.token_address"), + cfg.GetString("bridge.authorizers_address"), + cfg.GetString("bridge.ethereum_address"), + cfg.GetString("bridge.password"), + cfg.GetUint64("bridge.gas_limit"), + cfg.GetFloat64("bridge.consensus_threshold"), + ethereumClient, + transactionProvider, + keyStore, + ) } func prepareEthereumClientGeneralMockCalls(ethereumClient *mock.Mock) { diff --git a/zcnbridge/config.go b/zcnbridge/config.go index 7b9ce8252..d9e9c0e95 100644 --- a/zcnbridge/config.go +++ b/zcnbridge/config.go @@ -28,6 +28,13 @@ type BridgeSDKConfig struct { Development *bool } +// EthereumClient describes Ethereum JSON-RPC client generealized interface +type EthereumClient interface { + bind.ContractBackend + + ChainID(ctx context.Context) (*big.Int, error) +} + type BridgeClient struct { KeyStore transaction.TransactionProvider @@ -43,55 +50,22 @@ type BridgeClient struct { GasLimit uint64 } -// EthereumClient describes Ethereum JSON-RPC client generealized interface -type EthereumClient interface { - bind.ContractBackend - - ChainID(ctx context.Context) (*big.Int, error) -} - -// createBridgeClient initializes new bridge client with the help of the given -// Ethereum JSON-RPC client and locally-defined confiruration. -func createBridgeClient(cfg *viper.Viper, ethereumClient EthereumClient, transactionProvider transaction.TransactionProvider, keyStore KeyStore) *BridgeClient { +// NewBridgeClient creates BridgeClient with the given parameters. +func NewBridgeClient(bridgeAddress, tokenAddress, authorizersAddress, ethereumAddress, password string, gasLimit uint64, consensusThreshold float64, ethereumClient EthereumClient, transactionProvider transaction.TransactionProvider, keyStore KeyStore) *BridgeClient { return &BridgeClient{ - BridgeAddress: cfg.GetString("bridge.bridge_address"), - TokenAddress: cfg.GetString("bridge.token_address"), - AuthorizersAddress: cfg.GetString("bridge.authorizers_address"), - EthereumAddress: cfg.GetString("bridge.ethereum_address"), - Password: cfg.GetString("bridge.password"), - GasLimit: cfg.GetUint64("bridge.gas_limit"), - ConsensusThreshold: cfg.GetFloat64("bridge.consensus_threshold"), + BridgeAddress: bridgeAddress, + TokenAddress: tokenAddress, + AuthorizersAddress: authorizersAddress, + EthereumAddress: ethereumAddress, + Password: password, + GasLimit: gasLimit, + ConsensusThreshold: consensusThreshold, EthereumClient: ethereumClient, TransactionProvider: transactionProvider, KeyStore: keyStore, } } -// SetupBridgeClientSDK Use this from standalone application -// 0Chain SDK initialization is required -func SetupBridgeClientSDK(cfg *BridgeSDKConfig) *BridgeClient { - log.InitLogging(*cfg.Development, *cfg.LogPath, *cfg.LogLevel) - - chainCfg := initChainConfig(cfg) - - ethereumClient, err := ethclient.Dial(chainCfg.GetString("ethereum_node_url")) - if err != nil { - Logger.Error(err) - } - - transactionProvider := transaction.NewTransactionProvider() - - homedir := path.Dir(chainCfg.ConfigFileUsed()) - if homedir == "" { - log.Logger.Fatal("err happened during home directory retrieval") - } - - ks := NewKeyStore(path.Join(homedir, EthereumWalletStorageDir)) - - bridgeClient := createBridgeClient(chainCfg, ethereumClient, transactionProvider, ks) - return bridgeClient -} - func initChainConfig(sdkConfig *BridgeSDKConfig) *viper.Viper { cfg := readConfig(sdkConfig, func() string { return *sdkConfig.ConfigChainFile @@ -113,3 +87,38 @@ func readConfig(sdkConfig *BridgeSDKConfig, getConfigName func() string) *viper. } return cfg } + +// SetupBridgeClientSDK initializes new bridge client. +// Meant to be used from standalone application with 0chain SDK initialized. +func SetupBridgeClientSDK(cfg *BridgeSDKConfig) *BridgeClient { + log.InitLogging(*cfg.Development, *cfg.LogPath, *cfg.LogLevel) + + chainCfg := initChainConfig(cfg) + + ethereumClient, err := ethclient.Dial(chainCfg.GetString("ethereum_node_url")) + if err != nil { + Logger.Error(err) + } + + transactionProvider := transaction.NewTransactionProvider() + + homedir := path.Dir(chainCfg.ConfigFileUsed()) + if homedir == "" { + log.Logger.Fatal("err happened during home directory retrieval") + } + + keyStore := NewKeyStore(path.Join(homedir, EthereumWalletStorageDir)) + + return NewBridgeClient( + chainCfg.GetString("bridge.bridge_address"), + chainCfg.GetString("bridge.token_address"), + chainCfg.GetString("bridge.authorizers_address"), + chainCfg.GetString("bridge.ethereum_address"), + chainCfg.GetString("bridge.password"), + chainCfg.GetUint64("bridge.gas_limit"), + chainCfg.GetFloat64("bridge.consensus_threshold"), + ethereumClient, + transactionProvider, + keyStore, + ) +} From 74245edb9b60fffc1ae8e3a87de64bf60fa59279 Mon Sep 17 00:00:00 2001 From: YarikRevich Date: Wed, 30 Aug 2023 18:23:22 +0200 Subject: [PATCH 028/134] fix: fixed bugs --- zcnbridge/config.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/zcnbridge/config.go b/zcnbridge/config.go index d9e9c0e95..227e2bd2a 100644 --- a/zcnbridge/config.go +++ b/zcnbridge/config.go @@ -36,9 +36,9 @@ type EthereumClient interface { } type BridgeClient struct { - KeyStore - transaction.TransactionProvider - EthereumClient + keyStore KeyStore + transactionProvider transaction.TransactionProvider + ethereumClient EthereumClient BridgeAddress, TokenAddress, @@ -60,9 +60,9 @@ func NewBridgeClient(bridgeAddress, tokenAddress, authorizersAddress, ethereumAd Password: password, GasLimit: gasLimit, ConsensusThreshold: consensusThreshold, - EthereumClient: ethereumClient, - TransactionProvider: transactionProvider, - KeyStore: keyStore, + ethereumClient: ethereumClient, + transactionProvider: transactionProvider, + keyStore: keyStore, } } From 8dd3c114198346796b5d02635892b533456b246a Mon Sep 17 00:00:00 2001 From: Yaroslav Svitlytskyi Date: Sat, 9 Sep 2023 02:39:27 +0200 Subject: [PATCH 029/134] fix: fixed bugs --- zcnbridge/transaction/txn.go | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/zcnbridge/transaction/txn.go b/zcnbridge/transaction/txn.go index 08f48afd7..9d886f773 100644 --- a/zcnbridge/transaction/txn.go +++ b/zcnbridge/transaction/txn.go @@ -54,20 +54,20 @@ type ( // confirmation represents the acceptance that a transaction is included into the blockchain. confirmation struct { - Version string `json:"version"` - Hash string `json:"hash"` - BlockHash string `json:"block_hash"` - PreviousBlockHash string `json:"previous_block_hash"` - Transaction Transaction `json:"txn,omitempty"` - CreationDate ctime.Timestamp `json:"creation_date"` - MinerID string `json:"miner_id"` - Round int64 `json:"round"` - Status int `json:"transaction_status"` - RoundRandomSeed int64 `json:"round_random_seed"` - MerkleTreeRoot string `json:"merkle_tree_root"` - MerkleTreePath *util.MTPath `json:"merkle_tree_path"` - ReceiptMerkleTreeRoot string `json:"receipt_merkle_tree_root"` - ReceiptMerkleTreePath *util.MTPath `json:"receipt_merkle_tree_path"` + Version string `json:"version"` + Hash string `json:"hash"` + BlockHash string `json:"block_hash"` + PreviousBlockHash string `json:"previous_block_hash"` + Transaction *transactionEntity `json:"txn,omitempty"` + CreationDate ctime.Timestamp `json:"creation_date"` + MinerID string `json:"miner_id"` + Round int64 `json:"round"` + Status int `json:"transaction_status"` + RoundRandomSeed int64 `json:"round_random_seed"` + MerkleTreeRoot string `json:"merkle_tree_root"` + MerkleTreePath *util.MTPath `json:"merkle_tree_path"` + ReceiptMerkleTreeRoot string `json:"receipt_merkle_tree_root"` + ReceiptMerkleTreePath *util.MTPath `json:"receipt_merkle_tree_path"` } ) From c4c35285bef21aad6b563059b7793e77d806d958 Mon Sep 17 00:00:00 2001 From: peterlimg <54137706+peterlimg@users.noreply.github.com> Date: Sun, 10 Sep 2023 05:53:41 +1000 Subject: [PATCH 030/134] Add NFT Config contract (#1212) --- zcnbridge/bridge.go | 156 +++++ zcnbridge/config.go | 2 + zcnbridge/ethereum/nftconfig/nftconfig.go | 656 ++++++++++++++++++++++ 3 files changed, 814 insertions(+) create mode 100644 zcnbridge/ethereum/nftconfig/nftconfig.go diff --git a/zcnbridge/bridge.go b/zcnbridge/bridge.go index d46000e6a..0498568bb 100644 --- a/zcnbridge/bridge.go +++ b/zcnbridge/bridge.go @@ -14,6 +14,7 @@ import ( "github.com/0chain/gosdk/zcnbridge/ethereum/authorizers" binding "github.com/0chain/gosdk/zcnbridge/ethereum/bridge" "github.com/0chain/gosdk/zcnbridge/ethereum/erc20" + "github.com/0chain/gosdk/zcnbridge/ethereum/nftconfig" "github.com/0chain/gosdk/zcnbridge/log" "github.com/0chain/gosdk/zcncore" hdw "github.com/0chain/gosdk/zcncore/ethhdwallet" @@ -184,6 +185,161 @@ func (b *BridgeClient) AddEthereumAuthorizers(configDir string) { } } +func (b *BridgeClient) prepareNFTConfig(ctx context.Context, method string, params ...interface{}) (*nftconfig.NFTConfig, *bind.TransactOpts, error) { + etherClient, err := b.CreateEthClient() + if err != nil { + return nil, nil, errors.Wrap(err, "failed to create etherClient") + } + + // To (contract) + contractAddress := common.HexToAddress(b.NFTConfigAddress) + + // Get ABI of the contract + abi, err := nftconfig.NFTConfigMetaData.GetAbi() + if err != nil { + return nil, nil, errors.Wrap(err, "failed to get nftconfig ABI") + } + + // Pack the method argument + pack, err := abi.Pack(method, params...) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to pack arguments") + } + + from := common.HexToAddress(b.EthereumAddress) + + // Gas limits in units + gasLimitUnits, err := etherClient.EstimateGas(ctx, eth.CallMsg{ + To: &contractAddress, + From: from, + Data: pack, + }) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to estimate gas") + } + + // Update gas limits + 10% + gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() + + transactOpts := b.CreateSignedTransactionFromKeyStore(etherClient, gasLimitUnits) + + // NFTConfig instance + cfg, err := nftconfig.NewNFTConfig(contractAddress, etherClient) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to create nftconfig instance") + } + + return cfg, transactOpts, nil +} + +// EncodePackInt do abi.encodedPack(string, int), it is used for setting plan id for royalty +func EncodePackInt64(key string, param int64) common.Hash { + return crypto.Keccak256Hash( + []byte(key), + common.LeftPadBytes(big.NewInt(param).Bytes(), 32), + ) +} + +// NFTConfigSetUint256 call setUint256 method of NFTConfig contract +func (b *BridgeClient) NFTConfigSetUint256(ctx context.Context, key string, value int64) (*types.Transaction, error) { + kkey := crypto.Keccak256Hash([]byte(key)) + return b.NFTConfigSetUint256Raw(ctx, kkey, value) +} + +func (b *BridgeClient) NFTConfigSetUint256Raw(ctx context.Context, key common.Hash, value int64) (*types.Transaction, error) { + if value < 0 { + return nil, errors.New("value must be greater than zero") + } + + v := big.NewInt(value) + Logger.Debug("NFT config setUint256", zap.String("key", key.String()), zap.Any("value", v)) + instance, transactOpts, err := b.prepareNFTConfig(ctx, "setUint256", key, v) + if err != nil { + return nil, errors.Wrap(err, "failed to prepare bridge") + } + + tran, err := instance.SetUint256(transactOpts, key, v) + if err != nil { + msg := "failed to execute setUint256 transaction to ClientID = %s with key = %s, value = %v" + return nil, errors.Wrapf(err, msg, zcncore.GetClientWalletID(), key, v) + } + + return tran, err +} + +func (b *BridgeClient) NFTConfigGetUint256(ctx context.Context, key string, keyParam ...int64) (string, int64, error) { + kkey := crypto.Keccak256Hash([]byte(key)) + if len(keyParam) > 0 { + kkey = EncodePackInt64(key, keyParam[0]) + } + + etherClient, err := b.CreateEthClient() + if err != nil { + return "", 0, errors.Wrap(err, "failed to create etherClient") + } + + contractAddress := common.HexToAddress(b.NFTConfigAddress) + + cfg, err := nftconfig.NewNFTConfig(contractAddress, etherClient) + if err != nil { + return "", 0, errors.Wrap(err, "failed to create NFT config instance") + } + + v, err := cfg.GetUint256(nil, kkey) + if err != nil { + Logger.Error("NFTConfig GetUint256 FAILED", zap.Error(err)) + msg := "failed to execute getUint256 call, key = %s" + return "", 0, errors.Wrapf(err, msg, kkey) + } + return kkey.String(), v.Int64(), err +} + +func (b *BridgeClient) NFTConfigSetAddress(ctx context.Context, key, address string) (*types.Transaction, error) { + kkey := crypto.Keccak256Hash([]byte(key)) + // return b.NFTConfigSetAddress(ctx, kkey, address) + + Logger.Debug("NFT config setAddress", + zap.String("key", kkey.String()), + zap.String("address", address)) + + addr := common.HexToAddress(address) + instance, transactOpts, err := b.prepareNFTConfig(ctx, "setAddress", kkey, addr) + if err != nil { + return nil, errors.Wrap(err, "failed to prepare bridge") + } + + tran, err := instance.SetAddress(transactOpts, kkey, addr) + if err != nil { + msg := "failed to execute setAddress transaction to ClientID = %s with key = %s, value = %v" + return nil, errors.Wrapf(err, msg, zcncore.GetClientWalletID(), key, address) + } + + return tran, err +} + +func (b *BridgeClient) NFTConfigGetAddress(ctx context.Context, key string) (string, string, error) { + kkey := crypto.Keccak256Hash([]byte(key)) + etherClient, err := b.CreateEthClient() + if err != nil { + return "", "", errors.Wrap(err, "failed to create etherClient") + } + + contractAddress := common.HexToAddress(b.NFTConfigAddress) + + cfg, err := nftconfig.NewNFTConfig(contractAddress, etherClient) + if err != nil { + return "", "", errors.Wrap(err, "failed to create NFT config instance") + } + + v, err := cfg.GetAddress(nil, kkey) + if err != nil { + Logger.Error("NFTConfig GetAddress FAILED", zap.Error(err)) + msg := "failed to execute getAddress call, key = %s" + return "", "", errors.Wrapf(err, msg, kkey) + } + return kkey.String(), v.String(), err +} + // IncreaseBurnerAllowance Increases allowance for bridge contract address to transfer // WZCN tokens on behalf of the token owner to the Burn TokenPool // During the burn the script transfers amount from token owner to the bridge burn token pool diff --git a/zcnbridge/config.go b/zcnbridge/config.go index 7d5e06e72..20ddb46f9 100644 --- a/zcnbridge/config.go +++ b/zcnbridge/config.go @@ -27,6 +27,7 @@ type BridgeClient struct { BridgeAddress, TokenAddress, AuthorizersAddress, + NFTConfigAddress, EthereumAddress, Password, EthereumNodeURL, @@ -47,6 +48,7 @@ func CreateBridgeClient(cfg *viper.Viper) *BridgeClient { BridgeAddress: cfg.GetString("bridge.bridge_address"), TokenAddress: cfg.GetString("bridge.token_address"), AuthorizersAddress: cfg.GetString("bridge.authorizers_address"), + NFTConfigAddress: cfg.GetString("bridge.nft_config_address"), EthereumAddress: cfg.GetString("bridge.ethereum_address"), Password: cfg.GetString("bridge.password"), EthereumNodeURL: cfg.GetString("ethereum_node_url"), diff --git a/zcnbridge/ethereum/nftconfig/nftconfig.go b/zcnbridge/ethereum/nftconfig/nftconfig.go new file mode 100644 index 000000000..2961f9fce --- /dev/null +++ b/zcnbridge/ethereum/nftconfig/nftconfig.go @@ -0,0 +1,656 @@ +// Code generated - DO NOT EDIT. +// This file is a generated binding and any manual changes will be lost. + +package nftconfig + +import ( + "errors" + "math/big" + "strings" + + ethereum "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/event" +) + +// Reference imports to suppress errors if they are not otherwise used. +var ( + _ = errors.New + _ = big.NewInt + _ = strings.NewReader + _ = ethereum.NotFound + _ = bind.Bind + _ = common.Big1 + _ = types.BloomLookup + _ = event.NewSubscription +) + +// NFTConfigMetaData contains all meta data concerning the NFTConfig contract. +var NFTConfigMetaData = &bind.MetaData{ + ABI: "[{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"key\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"previous\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"updated\",\"type\":\"uint256\"}],\"name\":\"ConfigUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\",\"constant\":true},{\"inputs\":[],\"name\":\"renounceOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"key\",\"type\":\"bytes32\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"setUint256\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"key\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"value\",\"type\":\"address\"}],\"name\":\"setAddress\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"key\",\"type\":\"bytes32\"}],\"name\":\"getUint256\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\",\"constant\":true},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"key\",\"type\":\"bytes32\"}],\"name\":\"getAddress\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\",\"constant\":true}]", +} + +// NFTConfigABI is the input ABI used to generate the binding from. +// Deprecated: Use NFTConfigMetaData.ABI instead. +var NFTConfigABI = NFTConfigMetaData.ABI + +// NFTConfig is an auto generated Go binding around an Ethereum contract. +type NFTConfig struct { + NFTConfigCaller // Read-only binding to the contract + NFTConfigTransactor // Write-only binding to the contract + NFTConfigFilterer // Log filterer for contract events +} + +// NFTConfigCaller is an auto generated read-only Go binding around an Ethereum contract. +type NFTConfigCaller struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// NFTConfigTransactor is an auto generated write-only Go binding around an Ethereum contract. +type NFTConfigTransactor struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// NFTConfigFilterer is an auto generated log filtering Go binding around an Ethereum contract events. +type NFTConfigFilterer struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// NFTConfigSession is an auto generated Go binding around an Ethereum contract, +// with pre-set call and transact options. +type NFTConfigSession struct { + Contract *NFTConfig // Generic contract binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// NFTConfigCallerSession is an auto generated read-only Go binding around an Ethereum contract, +// with pre-set call options. +type NFTConfigCallerSession struct { + Contract *NFTConfigCaller // Generic contract caller binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session +} + +// NFTConfigTransactorSession is an auto generated write-only Go binding around an Ethereum contract, +// with pre-set transact options. +type NFTConfigTransactorSession struct { + Contract *NFTConfigTransactor // Generic contract transactor binding to set the session for + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// NFTConfigRaw is an auto generated low-level Go binding around an Ethereum contract. +type NFTConfigRaw struct { + Contract *NFTConfig // Generic contract binding to access the raw methods on +} + +// NFTConfigCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. +type NFTConfigCallerRaw struct { + Contract *NFTConfigCaller // Generic read-only contract binding to access the raw methods on +} + +// NFTConfigTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. +type NFTConfigTransactorRaw struct { + Contract *NFTConfigTransactor // Generic write-only contract binding to access the raw methods on +} + +// NewNFTConfig creates a new instance of NFTConfig, bound to a specific deployed contract. +func NewNFTConfig(address common.Address, backend bind.ContractBackend) (*NFTConfig, error) { + contract, err := bindNFTConfig(address, backend, backend, backend) + if err != nil { + return nil, err + } + return &NFTConfig{NFTConfigCaller: NFTConfigCaller{contract: contract}, NFTConfigTransactor: NFTConfigTransactor{contract: contract}, NFTConfigFilterer: NFTConfigFilterer{contract: contract}}, nil +} + +// NewNFTConfigCaller creates a new read-only instance of NFTConfig, bound to a specific deployed contract. +func NewNFTConfigCaller(address common.Address, caller bind.ContractCaller) (*NFTConfigCaller, error) { + contract, err := bindNFTConfig(address, caller, nil, nil) + if err != nil { + return nil, err + } + return &NFTConfigCaller{contract: contract}, nil +} + +// NewNFTConfigTransactor creates a new write-only instance of NFTConfig, bound to a specific deployed contract. +func NewNFTConfigTransactor(address common.Address, transactor bind.ContractTransactor) (*NFTConfigTransactor, error) { + contract, err := bindNFTConfig(address, nil, transactor, nil) + if err != nil { + return nil, err + } + return &NFTConfigTransactor{contract: contract}, nil +} + +// NewNFTConfigFilterer creates a new log filterer instance of NFTConfig, bound to a specific deployed contract. +func NewNFTConfigFilterer(address common.Address, filterer bind.ContractFilterer) (*NFTConfigFilterer, error) { + contract, err := bindNFTConfig(address, nil, nil, filterer) + if err != nil { + return nil, err + } + return &NFTConfigFilterer{contract: contract}, nil +} + +// bindNFTConfig binds a generic wrapper to an already deployed contract. +func bindNFTConfig(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { + parsed, err := abi.JSON(strings.NewReader(NFTConfigABI)) + if err != nil { + return nil, err + } + return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_NFTConfig *NFTConfigRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _NFTConfig.Contract.NFTConfigCaller.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_NFTConfig *NFTConfigRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _NFTConfig.Contract.NFTConfigTransactor.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_NFTConfig *NFTConfigRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _NFTConfig.Contract.NFTConfigTransactor.contract.Transact(opts, method, params...) +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_NFTConfig *NFTConfigCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _NFTConfig.Contract.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_NFTConfig *NFTConfigTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _NFTConfig.Contract.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_NFTConfig *NFTConfigTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _NFTConfig.Contract.contract.Transact(opts, method, params...) +} + +// GetAddress is a free data retrieval call binding the contract method 0x21f8a721. +// +// Solidity: function getAddress(bytes32 key) view returns(address) +func (_NFTConfig *NFTConfigCaller) GetAddress(opts *bind.CallOpts, key [32]byte) (common.Address, error) { + var out []interface{} + err := _NFTConfig.contract.Call(opts, &out, "getAddress", key) + + if err != nil { + return *new(common.Address), err + } + + out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) + + return out0, err + +} + +// GetAddress is a free data retrieval call binding the contract method 0x21f8a721. +// +// Solidity: function getAddress(bytes32 key) view returns(address) +func (_NFTConfig *NFTConfigSession) GetAddress(key [32]byte) (common.Address, error) { + return _NFTConfig.Contract.GetAddress(&_NFTConfig.CallOpts, key) +} + +// GetAddress is a free data retrieval call binding the contract method 0x21f8a721. +// +// Solidity: function getAddress(bytes32 key) view returns(address) +func (_NFTConfig *NFTConfigCallerSession) GetAddress(key [32]byte) (common.Address, error) { + return _NFTConfig.Contract.GetAddress(&_NFTConfig.CallOpts, key) +} + +// GetUint256 is a free data retrieval call binding the contract method 0x33598b00. +// +// Solidity: function getUint256(bytes32 key) view returns(uint256) +func (_NFTConfig *NFTConfigCaller) GetUint256(opts *bind.CallOpts, key [32]byte) (*big.Int, error) { + var out []interface{} + err := _NFTConfig.contract.Call(opts, &out, "getUint256", key) + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// GetUint256 is a free data retrieval call binding the contract method 0x33598b00. +// +// Solidity: function getUint256(bytes32 key) view returns(uint256) +func (_NFTConfig *NFTConfigSession) GetUint256(key [32]byte) (*big.Int, error) { + return _NFTConfig.Contract.GetUint256(&_NFTConfig.CallOpts, key) +} + +// GetUint256 is a free data retrieval call binding the contract method 0x33598b00. +// +// Solidity: function getUint256(bytes32 key) view returns(uint256) +func (_NFTConfig *NFTConfigCallerSession) GetUint256(key [32]byte) (*big.Int, error) { + return _NFTConfig.Contract.GetUint256(&_NFTConfig.CallOpts, key) +} + +// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. +// +// Solidity: function owner() view returns(address) +func (_NFTConfig *NFTConfigCaller) Owner(opts *bind.CallOpts) (common.Address, error) { + var out []interface{} + err := _NFTConfig.contract.Call(opts, &out, "owner") + + if err != nil { + return *new(common.Address), err + } + + out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) + + return out0, err + +} + +// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. +// +// Solidity: function owner() view returns(address) +func (_NFTConfig *NFTConfigSession) Owner() (common.Address, error) { + return _NFTConfig.Contract.Owner(&_NFTConfig.CallOpts) +} + +// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. +// +// Solidity: function owner() view returns(address) +func (_NFTConfig *NFTConfigCallerSession) Owner() (common.Address, error) { + return _NFTConfig.Contract.Owner(&_NFTConfig.CallOpts) +} + +// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. +// +// Solidity: function renounceOwnership() returns() +func (_NFTConfig *NFTConfigTransactor) RenounceOwnership(opts *bind.TransactOpts) (*types.Transaction, error) { + return _NFTConfig.contract.Transact(opts, "renounceOwnership") +} + +// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. +// +// Solidity: function renounceOwnership() returns() +func (_NFTConfig *NFTConfigSession) RenounceOwnership() (*types.Transaction, error) { + return _NFTConfig.Contract.RenounceOwnership(&_NFTConfig.TransactOpts) +} + +// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. +// +// Solidity: function renounceOwnership() returns() +func (_NFTConfig *NFTConfigTransactorSession) RenounceOwnership() (*types.Transaction, error) { + return _NFTConfig.Contract.RenounceOwnership(&_NFTConfig.TransactOpts) +} + +// SetAddress is a paid mutator transaction binding the contract method 0xca446dd9. +// +// Solidity: function setAddress(bytes32 key, address value) returns() +func (_NFTConfig *NFTConfigTransactor) SetAddress(opts *bind.TransactOpts, key [32]byte, value common.Address) (*types.Transaction, error) { + return _NFTConfig.contract.Transact(opts, "setAddress", key, value) +} + +// SetAddress is a paid mutator transaction binding the contract method 0xca446dd9. +// +// Solidity: function setAddress(bytes32 key, address value) returns() +func (_NFTConfig *NFTConfigSession) SetAddress(key [32]byte, value common.Address) (*types.Transaction, error) { + return _NFTConfig.Contract.SetAddress(&_NFTConfig.TransactOpts, key, value) +} + +// SetAddress is a paid mutator transaction binding the contract method 0xca446dd9. +// +// Solidity: function setAddress(bytes32 key, address value) returns() +func (_NFTConfig *NFTConfigTransactorSession) SetAddress(key [32]byte, value common.Address) (*types.Transaction, error) { + return _NFTConfig.Contract.SetAddress(&_NFTConfig.TransactOpts, key, value) +} + +// SetUint256 is a paid mutator transaction binding the contract method 0x4f3029c2. +// +// Solidity: function setUint256(bytes32 key, uint256 value) returns() +func (_NFTConfig *NFTConfigTransactor) SetUint256(opts *bind.TransactOpts, key [32]byte, value *big.Int) (*types.Transaction, error) { + return _NFTConfig.contract.Transact(opts, "setUint256", key, value) +} + +// SetUint256 is a paid mutator transaction binding the contract method 0x4f3029c2. +// +// Solidity: function setUint256(bytes32 key, uint256 value) returns() +func (_NFTConfig *NFTConfigSession) SetUint256(key [32]byte, value *big.Int) (*types.Transaction, error) { + return _NFTConfig.Contract.SetUint256(&_NFTConfig.TransactOpts, key, value) +} + +// SetUint256 is a paid mutator transaction binding the contract method 0x4f3029c2. +// +// Solidity: function setUint256(bytes32 key, uint256 value) returns() +func (_NFTConfig *NFTConfigTransactorSession) SetUint256(key [32]byte, value *big.Int) (*types.Transaction, error) { + return _NFTConfig.Contract.SetUint256(&_NFTConfig.TransactOpts, key, value) +} + +// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. +// +// Solidity: function transferOwnership(address newOwner) returns() +func (_NFTConfig *NFTConfigTransactor) TransferOwnership(opts *bind.TransactOpts, newOwner common.Address) (*types.Transaction, error) { + return _NFTConfig.contract.Transact(opts, "transferOwnership", newOwner) +} + +// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. +// +// Solidity: function transferOwnership(address newOwner) returns() +func (_NFTConfig *NFTConfigSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) { + return _NFTConfig.Contract.TransferOwnership(&_NFTConfig.TransactOpts, newOwner) +} + +// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. +// +// Solidity: function transferOwnership(address newOwner) returns() +func (_NFTConfig *NFTConfigTransactorSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) { + return _NFTConfig.Contract.TransferOwnership(&_NFTConfig.TransactOpts, newOwner) +} + +// NFTConfigConfigUpdatedIterator is returned from FilterConfigUpdated and is used to iterate over the raw logs and unpacked data for ConfigUpdated events raised by the NFTConfig contract. +type NFTConfigConfigUpdatedIterator struct { + Event *NFTConfigConfigUpdated // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *NFTConfigConfigUpdatedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(NFTConfigConfigUpdated) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(NFTConfigConfigUpdated) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *NFTConfigConfigUpdatedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *NFTConfigConfigUpdatedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// NFTConfigConfigUpdated represents a ConfigUpdated event raised by the NFTConfig contract. +type NFTConfigConfigUpdated struct { + Key [32]byte + Previous *big.Int + Updated *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterConfigUpdated is a free log retrieval operation binding the contract event 0xac2ccce3de9c0816ae772598f7f65fe69f9893b637f7c490497378cbb3ea043e. +// +// Solidity: event ConfigUpdated(bytes32 indexed key, uint256 previous, uint256 updated) +func (_NFTConfig *NFTConfigFilterer) FilterConfigUpdated(opts *bind.FilterOpts, key [][32]byte) (*NFTConfigConfigUpdatedIterator, error) { + + var keyRule []interface{} + for _, keyItem := range key { + keyRule = append(keyRule, keyItem) + } + + logs, sub, err := _NFTConfig.contract.FilterLogs(opts, "ConfigUpdated", keyRule) + if err != nil { + return nil, err + } + return &NFTConfigConfigUpdatedIterator{contract: _NFTConfig.contract, event: "ConfigUpdated", logs: logs, sub: sub}, nil +} + +// WatchConfigUpdated is a free log subscription operation binding the contract event 0xac2ccce3de9c0816ae772598f7f65fe69f9893b637f7c490497378cbb3ea043e. +// +// Solidity: event ConfigUpdated(bytes32 indexed key, uint256 previous, uint256 updated) +func (_NFTConfig *NFTConfigFilterer) WatchConfigUpdated(opts *bind.WatchOpts, sink chan<- *NFTConfigConfigUpdated, key [][32]byte) (event.Subscription, error) { + + var keyRule []interface{} + for _, keyItem := range key { + keyRule = append(keyRule, keyItem) + } + + logs, sub, err := _NFTConfig.contract.WatchLogs(opts, "ConfigUpdated", keyRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(NFTConfigConfigUpdated) + if err := _NFTConfig.contract.UnpackLog(event, "ConfigUpdated", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseConfigUpdated is a log parse operation binding the contract event 0xac2ccce3de9c0816ae772598f7f65fe69f9893b637f7c490497378cbb3ea043e. +// +// Solidity: event ConfigUpdated(bytes32 indexed key, uint256 previous, uint256 updated) +func (_NFTConfig *NFTConfigFilterer) ParseConfigUpdated(log types.Log) (*NFTConfigConfigUpdated, error) { + event := new(NFTConfigConfigUpdated) + if err := _NFTConfig.contract.UnpackLog(event, "ConfigUpdated", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// NFTConfigOwnershipTransferredIterator is returned from FilterOwnershipTransferred and is used to iterate over the raw logs and unpacked data for OwnershipTransferred events raised by the NFTConfig contract. +type NFTConfigOwnershipTransferredIterator struct { + Event *NFTConfigOwnershipTransferred // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *NFTConfigOwnershipTransferredIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(NFTConfigOwnershipTransferred) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(NFTConfigOwnershipTransferred) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *NFTConfigOwnershipTransferredIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *NFTConfigOwnershipTransferredIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// NFTConfigOwnershipTransferred represents a OwnershipTransferred event raised by the NFTConfig contract. +type NFTConfigOwnershipTransferred struct { + PreviousOwner common.Address + NewOwner common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterOwnershipTransferred is a free log retrieval operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. +// +// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) +func (_NFTConfig *NFTConfigFilterer) FilterOwnershipTransferred(opts *bind.FilterOpts, previousOwner []common.Address, newOwner []common.Address) (*NFTConfigOwnershipTransferredIterator, error) { + + var previousOwnerRule []interface{} + for _, previousOwnerItem := range previousOwner { + previousOwnerRule = append(previousOwnerRule, previousOwnerItem) + } + var newOwnerRule []interface{} + for _, newOwnerItem := range newOwner { + newOwnerRule = append(newOwnerRule, newOwnerItem) + } + + logs, sub, err := _NFTConfig.contract.FilterLogs(opts, "OwnershipTransferred", previousOwnerRule, newOwnerRule) + if err != nil { + return nil, err + } + return &NFTConfigOwnershipTransferredIterator{contract: _NFTConfig.contract, event: "OwnershipTransferred", logs: logs, sub: sub}, nil +} + +// WatchOwnershipTransferred is a free log subscription operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. +// +// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) +func (_NFTConfig *NFTConfigFilterer) WatchOwnershipTransferred(opts *bind.WatchOpts, sink chan<- *NFTConfigOwnershipTransferred, previousOwner []common.Address, newOwner []common.Address) (event.Subscription, error) { + + var previousOwnerRule []interface{} + for _, previousOwnerItem := range previousOwner { + previousOwnerRule = append(previousOwnerRule, previousOwnerItem) + } + var newOwnerRule []interface{} + for _, newOwnerItem := range newOwner { + newOwnerRule = append(newOwnerRule, newOwnerItem) + } + + logs, sub, err := _NFTConfig.contract.WatchLogs(opts, "OwnershipTransferred", previousOwnerRule, newOwnerRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(NFTConfigOwnershipTransferred) + if err := _NFTConfig.contract.UnpackLog(event, "OwnershipTransferred", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseOwnershipTransferred is a log parse operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. +// +// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) +func (_NFTConfig *NFTConfigFilterer) ParseOwnershipTransferred(log types.Log) (*NFTConfigOwnershipTransferred, error) { + event := new(NFTConfigOwnershipTransferred) + if err := _NFTConfig.contract.UnpackLog(event, "OwnershipTransferred", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} From d94e9f4d644229da60239036790c0c64a6b3e084 Mon Sep 17 00:00:00 2001 From: peterlimg <54137706+peterlimg@users.noreply.github.com> Date: Sun, 10 Sep 2023 05:54:48 +1000 Subject: [PATCH 031/134] Silent the zcnbridge http request when --silent (#1207) --- zcnbridge/http/client.go | 9 +++++---- zcnbridge/http/rest.go | 16 ++++++++++++++-- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/zcnbridge/http/client.go b/zcnbridge/http/client.go index eb53872c3..008c4ad3c 100644 --- a/zcnbridge/http/client.go +++ b/zcnbridge/http/client.go @@ -29,14 +29,15 @@ func CleanClient() *http.Client { } // NewRetryableClient creates default retryablehttp.Client with timeouts and embedded NewClient result. -func NewRetryableClient() *retryablehttp.Client { +func NewRetryableClient(verbose bool) *retryablehttp.Client { client := retryablehttp.NewClient() client.HTTPClient = &http.Client{ Transport: zboxutil.DefaultTransport, } - //client.RetryWaitMax = RetryWaitMax - //client.RetryMax = RetryMax - //client.Logger = nil + + if !verbose { + client.Logger = nil + } return client } diff --git a/zcnbridge/http/rest.go b/zcnbridge/http/rest.go index e3f1729db..7a32225ab 100644 --- a/zcnbridge/http/rest.go +++ b/zcnbridge/http/rest.go @@ -32,6 +32,7 @@ type Params map[string]string var Logger logger.Logger var defaultLogLevel = logger.DEBUG +var logVerbose = true func init() { Logger.Init(defaultLogLevel, "zcnbridge-http-sdk") @@ -44,6 +45,18 @@ func init() { Logger.SetLogFile(f, true) } +func SetLogFile(logFile string, verbose bool) { + Logger.Init(defaultLogLevel, "zcnbridge-sdk") + Logger.SetLevel(logger.DEBUG) + + f, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + if err != nil { + return + } + logVerbose = verbose + Logger.SetLogFile(f, logVerbose) +} + // MakeSCRestAPICall calls smart contract with provided address // and makes retryable request to smart contract resource with provided relative path using params. func MakeSCRestAPICall(opCode int, relativePath string, params Params, cb zcncore.GetInfoCallback) { @@ -63,7 +76,7 @@ func MakeSCRestAPICall(opCode int, relativePath string, params Params, cb zcncor results := make(chan *queryResult, len(sharders)) defer close(results) - var client = NewRetryableClient() + var client = NewRetryableClient(logVerbose) wg := &sync.WaitGroup{} for _, sharder := range sharders { @@ -73,7 +86,6 @@ func MakeSCRestAPICall(opCode int, relativePath string, params Params, cb zcncor var u = makeURL(params, sharderUrl, relativePath) Logger.Info("Query ", u.String()) - resp, err := client.Get(u.String()) if err != nil { Logger.Error("MakeSCRestAPICall - failed to get response from", zap.String("URL", sharderUrl), zap.Any("error", err)) From 075ca3212b1f17c2e55a46f30e141cb167ca6233 Mon Sep 17 00:00:00 2001 From: Manohar Reddy Date: Mon, 11 Sep 2023 14:50:23 +0200 Subject: [PATCH 032/134] Change the return type of downloadBlocks to []byte in wasm (#1218) --- wasmsdk/README.md | 11 +---------- wasmsdk/blobber.go | 12 ++---------- 2 files changed, 3 insertions(+), 20 deletions(-) diff --git a/wasmsdk/README.md b/wasmsdk/README.md index eafe54e21..d94a186b5 100644 --- a/wasmsdk/README.md +++ b/wasmsdk/README.md @@ -497,16 +497,7 @@ download blocks of a file **Output**: -> {commandSuccess:bool, fileName:string,url:string, error:string} - -**Example** - -```json -{ - "commandSuccess": true, - "fileName": "scan3.png", - "url": "blob:http://localhost:3000/42157751-1d33-4448-88c8-7d7e2ad887a5" -} +> {[]byte, error:string} ``` ### zcn.sdk.upload diff --git a/wasmsdk/blobber.go b/wasmsdk/blobber.go index e7a6b110f..579d946ae 100644 --- a/wasmsdk/blobber.go +++ b/wasmsdk/blobber.go @@ -860,7 +860,7 @@ func upload(allocationID, remotePath string, fileBytes, thumbnailBytes []byte, w } // download download file blocks -func downloadBlocks(allocationID, remotePath, authTicket, lookupHash string, numBlocks int, startBlockNumber, endBlockNumber int64, callbackFuncName string, isFinal bool) (*DownloadCommandResponse, error) { +func downloadBlocks(allocationID, remotePath, authTicket, lookupHash string, numBlocks int, startBlockNumber, endBlockNumber int64, callbackFuncName string, isFinal bool) ([]byte, error) { if len(remotePath) == 0 && len(authTicket) == 0 { return nil, RequiredArg("remotePath/authTicket") @@ -920,15 +920,7 @@ func downloadBlocks(allocationID, remotePath, authTicket, lookupHash string, num return nil, errors.New("Download failed: unknown error") } - resp := &DownloadCommandResponse{ - CommandSuccess: true, - FileName: fileName, - } - - resp.Url = CreateObjectURL(mf.Buffer.Bytes(), "application/octet-stream") - - return resp, nil - + return mf.Buffer.Bytes(), nil } // GetBlobbersList get list of active blobbers, and format them as array json string From d5d6721dae132d6b179ecf9b873a0ec8a6e842aa Mon Sep 17 00:00:00 2001 From: Manohar Reddy Date: Mon, 11 Sep 2023 14:51:02 +0200 Subject: [PATCH 033/134] change the order of exchanges to get the ZCN prices (#1216) --- core/tokenrate/tokenrate.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/tokenrate/tokenrate.go b/core/tokenrate/tokenrate.go index 7c4d4d98a..d7decffeb 100644 --- a/core/tokenrate/tokenrate.go +++ b/core/tokenrate/tokenrate.go @@ -12,9 +12,9 @@ func init() { //priority: uniswap > bancor > coingecko > coinmarketcap quotes = []quoteQuery{ - &uniswapQuoteQuery{}, - &bancorQuoteQuery{}, &coingeckoQuoteQuery{}, + &bancorQuoteQuery{}, + &uniswapQuoteQuery{}, createCoinmarketcapQuoteQuery(), //more query services } From 5fa2a66d8c9427e8b259e92b53edbcfef49844ca Mon Sep 17 00:00:00 2001 From: Manohar Reddy Date: Mon, 11 Sep 2023 14:55:01 +0200 Subject: [PATCH 034/134] Deprecate non multi-operation functions (#1214) * remove CreateDir, Rename, Copy, Move * use docker build wasm * use @v4 version of git action * Revert "use @v4 version of git action" This reverts commit fbb93f25a6ca63d6e205eac418d031bba428eb29. --- .github/workflows/sdk-release.yml | 2 +- mobilesdk/zbox/allocation.go | 32 +++- mobilesdk/zbox/storage.go | 35 +++- wasmsdk/README.md | 14 +- wasmsdk/blobber.go | 147 ++++------------- wasmsdk/demo/index.html | 2 +- wasmsdk/proxy.go | 5 - zboxcore/sdk/allocation.go | 171 -------------------- zboxcore/sdk/allocation_file_copy_test.go | 142 ---------------- zboxcore/sdk/allocation_file_move_test.go | 129 --------------- zboxcore/sdk/allocation_file_rename_test.go | 139 ---------------- 11 files changed, 92 insertions(+), 726 deletions(-) delete mode 100644 zboxcore/sdk/allocation_file_copy_test.go delete mode 100644 zboxcore/sdk/allocation_file_move_test.go delete mode 100644 zboxcore/sdk/allocation_file_rename_test.go diff --git a/.github/workflows/sdk-release.yml b/.github/workflows/sdk-release.yml index a8b5ee337..a52bad2ed 100644 --- a/.github/workflows/sdk-release.yml +++ b/.github/workflows/sdk-release.yml @@ -71,7 +71,7 @@ jobs: fi - name: Build - run: make wasm-build + run: docker run --rm -v $PWD:/gosdk -w /gosdk golang:1.18 make wasm-build - name: Upload binaries to release uses: svenstaro/upload-release-action@v2 diff --git a/mobilesdk/zbox/allocation.go b/mobilesdk/zbox/allocation.go index 51e1c6153..4114915e5 100644 --- a/mobilesdk/zbox/allocation.go +++ b/mobilesdk/zbox/allocation.go @@ -6,6 +6,7 @@ import ( "fmt" "time" + "github.com/0chain/gosdk/constants" "github.com/0chain/gosdk/core/common" "github.com/0chain/gosdk/zboxcore/blockchain" "github.com/0chain/gosdk/zboxcore/sdk" @@ -200,7 +201,13 @@ func (a *Allocation) RenameObject(remotePath string, destName string) error { if a == nil || a.sdkAllocation == nil { return ErrInvalidAllocation } - return a.sdkAllocation.RenameObject(remotePath, destName) + return a.sdkAllocation.DoMultiOperation([]sdk.OperationRequest{ + { + OperationType: constants.FileOperationRename, + RemotePath: remotePath, + DestName: destName, + }, + }) } // GetStatistics - get allocation stats @@ -374,7 +381,13 @@ func (a *Allocation) CopyObject(path string, destPath string) error { if a == nil || a.sdkAllocation == nil { return ErrInvalidAllocation } - return a.sdkAllocation.CopyObject(path, destPath) + return a.sdkAllocation.DoMultiOperation([]sdk.OperationRequest{ + { + OperationType: constants.FileOperationRename, + RemotePath: path, + DestPath: destPath, + }, + }) } // MoveObject - move object from path to dest @@ -382,7 +395,13 @@ func (a *Allocation) MoveObject(path string, destPath string) error { if a == nil || a.sdkAllocation == nil { return ErrInvalidAllocation } - return a.sdkAllocation.MoveObject(path, destPath) + return a.sdkAllocation.DoMultiOperation([]sdk.OperationRequest{ + { + OperationType: constants.FileOperationRename, + RemotePath: path, + DestPath: destPath, + }, + }) } // GetMinWriteRead - getting back cost for allocation @@ -455,7 +474,12 @@ func (a *Allocation) GetFirstSegment(localPath, remotePath, tmpPath string, dela } func (a *Allocation) CreateDir(dirName string) error { - return a.sdkAllocation.CreateDir(dirName) + return a.sdkAllocation.DoMultiOperation([]sdk.OperationRequest{ + { + OperationType: constants.FileOperationCreateDir, + RemotePath: dirName, + }, + }) } var currentPlayback StreamingImpl diff --git a/mobilesdk/zbox/storage.go b/mobilesdk/zbox/storage.go index 3e88bb6ef..da702d1da 100644 --- a/mobilesdk/zbox/storage.go +++ b/mobilesdk/zbox/storage.go @@ -6,12 +6,11 @@ import ( "strings" "time" + "github.com/0chain/gosdk/constants" "github.com/0chain/gosdk/zboxcore/fileref" "github.com/0chain/gosdk/zboxcore/sdk" ) -const SPACE string = " " - type fileResp struct { sdk.FileInfo Name string `json:"name"` @@ -468,7 +467,13 @@ func RenameObject(allocationID, remotePath string, destName string) error { if err != nil { return err } - return a.RenameObject(remotePath, destName) + return a.DoMultiOperation([]sdk.OperationRequest{ + { + OperationType: constants.FileOperationRename, + RemotePath: remotePath, + DestName: destName, + }, + }) } // GetStatistics - get allocation stats @@ -747,7 +752,13 @@ func CopyObject(allocationID, path string, destPath string) error { if err != nil { return err } - return a.CopyObject(path, destPath) + return a.DoMultiOperation([]sdk.OperationRequest{ + { + OperationType: constants.FileOperationCopy, + RemotePath: path, + DestPath: destPath, + }, + }) } // MoveObject - move object from path to dest @@ -760,7 +771,14 @@ func MoveObject(allocationID, path string, destPath string) error { if err != nil { return err } - return a.MoveObject(path, destPath) + return a.DoMultiOperation([]sdk.OperationRequest{ + { + OperationType: constants.FileOperationMove, + RemotePath: path, + DestPath: destPath, + }, + }) + } // CreateDir create empty directoy on remote blobbers @@ -773,7 +791,12 @@ func CreateDir(allocationID, dirName string) error { if err != nil { return err } - return a.CreateDir(dirName) + return a.DoMultiOperation([]sdk.OperationRequest{ + { + OperationType: constants.FileOperationCreateDir, + RemotePath: dirName, + }, + }) } // RevokeShare revoke authTicket diff --git a/wasmsdk/README.md b/wasmsdk/README.md index d94a186b5..a1dc459c2 100644 --- a/wasmsdk/README.md +++ b/wasmsdk/README.md @@ -18,18 +18,6 @@ set bls.SecretKey on runtime env(browser,nodejs...etc), and call `zcn.sdk.setWal > N/A -### zcn.bulkUpload - -bulk upload files. it will wrap options, and call `zcn.sdk.bulkUpload` to process upload - -**Input**: - -> bulkOptions: [ { allocationId:string,remotePath:string,file:FileReader, thumbnailBytes:[]byte, encrypt:bool,isUpdate:bool,isRepair:bool,numBlocks:int,callback:function(totalBytes, completedBytes, error) } ] - -**Output**: - -> [ {remotePath:"/d.png", success:true,error:""} ] - ## ZCN methods ### zcn.sdk.init @@ -512,7 +500,7 @@ upload file > {commandSuccess:bool, error:string} -### zcn.sdk.bulkUpload +### zcn.sdk.multiUpload bulk upload files with json options diff --git a/wasmsdk/blobber.go b/wasmsdk/blobber.go index 579d946ae..bc951826c 100644 --- a/wasmsdk/blobber.go +++ b/wasmsdk/blobber.go @@ -14,9 +14,11 @@ import ( "syscall/js" "time" + "github.com/0chain/gosdk/constants" "github.com/0chain/gosdk/core/common" "github.com/0chain/gosdk/core/pathutil" "github.com/0chain/gosdk/core/sys" + "github.com/0chain/gosdk/core/transaction" "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/fileref" @@ -52,7 +54,12 @@ func createDir(allocationID, remotePath string) error { return err } - return allocationObj.CreateDir(remotePath) + return allocationObj.DoMultiOperation([]sdk.OperationRequest{ + { + OperationType: constants.FileOperationCreateDir, + RemotePath: remotePath, + }, + }) } // getFileStats get file stats from blobbers @@ -152,7 +159,14 @@ func Rename(allocationID, remotePath, destName string) (*FileCommandResponse, er return nil, err } - err = allocationObj.RenameObject(remotePath, destName) + err = allocationObj.DoMultiOperation([]sdk.OperationRequest{ + { + OperationType: constants.FileOperationRename, + RemotePath: remotePath, + DestName: destName, + }, + }) + if err != nil { PrintError(err.Error()) return nil, err @@ -187,7 +201,14 @@ func Copy(allocationID, remotePath, destPath string) (*FileCommandResponse, erro return nil, err } - err = allocationObj.CopyObject(remotePath, destPath) + err = allocationObj.DoMultiOperation([]sdk.OperationRequest{ + { + OperationType: constants.FileOperationCopy, + RemotePath: remotePath, + DestPath: destPath, + }, + }) + if err != nil { PrintError(err.Error()) return nil, err @@ -222,7 +243,14 @@ func Move(allocationID, remotePath, destPath string) (*FileCommandResponse, erro return nil, err } - err = allocationObj.MoveObject(remotePath, destPath) + err = allocationObj.DoMultiOperation([]sdk.OperationRequest{ + { + OperationType: constants.FileOperationMove, + RemotePath: remotePath, + DestPath: destPath, + }, + }) + if err != nil { PrintError(err.Error()) return nil, err @@ -305,71 +333,6 @@ func Share(allocationID, remotePath, clientID, encryptionPublicKey string, expir } -// download file -func download( - allocationID, remotePath, authTicket, lookupHash string, - downloadThumbnailOnly bool, numBlocks int, callbackFuncName string, isFinal bool) (*DownloadCommandResponse, error) { - - wg := &sync.WaitGroup{} - statusBar := &StatusBar{wg: wg} - if callbackFuncName != "" { - callback := js.Global().Get(callbackFuncName) - statusBar.callback = func(totalBytes, completedBytes int, filename, objURL, err string) { - callback.Invoke(totalBytes, completedBytes, filename, objURL, err) - } - } - wg.Add(1) - - if len(remotePath) == 0 && len(authTicket) == 0 { - return nil, RequiredArg("remotePath/authTicket") - } - - fileName := strings.Replace(path.Base(remotePath), "/", "-", -1) - localPath := allocationID + "_" + fileName - var ( - err error - downloader sdk.Downloader - ) - - fs, _ := sys.Files.Open(localPath) - mf, _ := fs.(*sys.MemFile) - - downloader, err = sdk.CreateDownloader(allocationID, localPath, remotePath, - sdk.WithAuthticket(authTicket, lookupHash), - sdk.WithOnlyThumbnail(downloadThumbnailOnly), - sdk.WithBlocks(0, 0, numBlocks), - sdk.WithFileHandler(mf)) - - if err != nil { - PrintError(err.Error()) - return nil, err - } - - defer sys.Files.Remove(localPath) //nolint - - err = downloader.Start(statusBar, isFinal) - - if err == nil { - wg.Wait() - } else { - PrintError("Download failed.", err.Error()) - return nil, err - } - if !statusBar.success { - return nil, errors.New("Download failed: unknown error") - } - - resp := &DownloadCommandResponse{ - CommandSuccess: true, - FileName: downloader.GetFileName(), - } - - resp.Url = CreateObjectURL(mf.Buffer.Bytes(), "application/octet-stream") - - return resp, nil - -} - // MultiOperation - do copy, move, delete and createdir operation together // ## Inputs // - allocationID @@ -548,52 +511,6 @@ func MultiOperation(allocationID string, jsonMultiUploadOptions string) error { return allocationObj.DoMultiOperation(operations) } -func bulkUpload(jsonBulkUploadOptions string) ([]BulkUploadResult, error) { - var options []BulkUploadOption - err := json.Unmarshal([]byte(jsonBulkUploadOptions), &options) - if err != nil { - return nil, err - } - - n := len(options) - wait := make(chan BulkUploadResult, 1) - - for _, option := range options { - go func(o BulkUploadOption) { - result := BulkUploadResult{ - RemotePath: o.RemotePath, - } - defer func() { wait <- result }() - - ok, err := uploadWithJsFuncs(o.AllocationID, o.RemotePath, - o.ReadChunkFuncName, - o.FileSize, - o.ThumbnailBytes.Buffer, - o.Webstreaming, - o.Encrypt, - o.IsUpdate, - o.IsRepair, - o.NumBlocks, - o.CallbackFuncName) - result.Success = ok - if err != nil { - result.Error = err.Error() - result.Success = false - } - - }(option) - - } - - results := make([]BulkUploadResult, 0, n) - for i := 0; i < n; i++ { - result := <-wait - results = append(results, result) - } - - return results, nil -} - func multiUpload(jsonBulkUploadOptions string) (MultiUploadResult, error) { var options []BulkUploadOption result := MultiUploadResult{} diff --git a/wasmsdk/demo/index.html b/wasmsdk/demo/index.html index 6b5867813..58184593a 100644 --- a/wasmsdk/demo/index.html +++ b/wasmsdk/demo/index.html @@ -443,7 +443,7 @@

please download zcn.wasm from https://github.com/0chain/gosdk/releases/lates } }) } - const results = await goWasm.bulkUpload(objects) + const results = await goWasm.multiUpload(objects) console.log(JSON.stringify(results)) } }) diff --git a/wasmsdk/proxy.go b/wasmsdk/proxy.go index acd6cb950..76648d4b3 100644 --- a/wasmsdk/proxy.go +++ b/wasmsdk/proxy.go @@ -163,14 +163,9 @@ func main() { //blobber "delete": Delete, - "rename": Rename, - "copy": Copy, - "move": Move, "share": Share, - "download": download, "multiDownload": multiDownload, "upload": upload, - "bulkUpload": bulkUpload, "multiUpload": multiUpload, "multiOperation": MultiOperation, "listObjects": listObjects, diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 0328bbe9a..7696357c5 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -13,7 +13,6 @@ import ( "net/http" "net/url" "os" - "path" "path/filepath" "strconv" "strings" @@ -362,45 +361,6 @@ func (a *Allocation) UploadFile(workdir, localpath string, remotepath string, return a.StartChunkedUpload(workdir, localpath, remotepath, status, false, false, "", false, false) } -func (a *Allocation) CreateDir(remotePath string) error { - if !a.isInitialized() { - return notInitialized - } - - if remotePath == "" { - return errors.New("invalid_name", "Invalid name for dir") - } - - if !path.IsAbs(remotePath) { - return errors.New("invalid_path", "Path is not absolute") - } - - remotePath = zboxutil.RemoteClean(remotePath) - timestamp := int64(common.Now()) - req := DirRequest{ - allocationObj: a, - allocationID: a.ID, - allocationTx: a.Tx, - blobbers: a.Blobbers, - mu: &sync.Mutex{}, - dirMask: zboxutil.NewUint128(1).Lsh(uint64(len(a.Blobbers))).Sub64(1), - connectionID: zboxutil.NewConnectionId(), - remotePath: remotePath, - wg: &sync.WaitGroup{}, - timestamp: timestamp, - alreadyExists: map[uint64]bool{}, - Consensus: Consensus{ - RWMutex: &sync.RWMutex{}, - consensusThresh: a.consensusThreshold, - fullconsensus: a.fullconsensus, - }, - } - req.ctx, req.ctxCncl = context.WithCancel(a.ctx) - - err := req.ProcessDir(a) - return err -} - func (a *Allocation) RepairFile(file sys.File, remotepath string, status StatusCallback, mask zboxutil.Uint128, ref *fileref.FileRef) error { @@ -1634,137 +1594,6 @@ func (a *Allocation) deleteFile(path string, threshConsensus, fullConsensus int, return err } -func (a *Allocation) RenameObject(path string, destName string) error { - if !a.isInitialized() { - return notInitialized - } - - if !a.CanRename() { - return constants.ErrFileOptionNotPermitted - } - - if path == "" { - return errors.New("invalid_path", "Invalid path for the list") - } - - if path == "/" { - return errors.New("invalid_operation", "cannot rename root path") - } - - path = zboxutil.RemoteClean(path) - isabs := zboxutil.IsRemoteAbs(path) - if !isabs { - return errors.New("invalid_path", "Path should be valid and absolute") - } - - err := ValidateRemoteFileName(destName) - if err != nil { - return err - } - - req := &RenameRequest{consensus: Consensus{RWMutex: &sync.RWMutex{}}} - req.allocationObj = a - req.blobbers = a.Blobbers - req.allocationID = a.ID - req.allocationTx = a.Tx - req.newName = destName - req.consensus.fullconsensus = a.fullconsensus - req.consensus.consensusThresh = a.consensusThreshold - req.ctx, req.ctxCncl = context.WithCancel(a.ctx) - req.remotefilepath = path - req.renameMask = zboxutil.NewUint128(1).Lsh(uint64(len(a.Blobbers))).Sub64(1) - req.maskMU = &sync.Mutex{} - req.connectionID = zboxutil.NewConnectionId() - req.timestamp = int64(common.Now()) - return req.ProcessRename() -} - -func (a *Allocation) MoveObject(srcPath string, destPath string) error { - if !a.isInitialized() { - return notInitialized - } - - if !a.CanMove() { - return constants.ErrFileOptionNotPermitted - } - - if len(srcPath) == 0 || len(destPath) == 0 { - return errors.New("invalid_path", "Invalid path for copy") - } - srcPath = zboxutil.RemoteClean(srcPath) - isabs := zboxutil.IsRemoteAbs(srcPath) - if !isabs { - return errors.New("invalid_path", "Path should be valid and absolute") - } - - err := ValidateRemoteFileName(destPath) - if err != nil { - return err - } - - req := &MoveRequest{Consensus: Consensus{RWMutex: &sync.RWMutex{}}} - req.allocationObj = a - req.blobbers = a.Blobbers - req.allocationID = a.ID - req.allocationTx = a.Tx - if destPath != "/" { - destPath = strings.TrimSuffix(destPath, "/") - } - req.destPath = destPath - req.fullconsensus = a.fullconsensus - req.consensusThresh = a.consensusThreshold - req.ctx, req.ctxCncl = context.WithCancel(a.ctx) - req.remotefilepath = srcPath - req.moveMask = zboxutil.NewUint128(1).Lsh(uint64(len(a.Blobbers))).Sub64(1) - req.maskMU = &sync.Mutex{} - req.connectionID = zboxutil.NewConnectionId() - req.timestamp = int64(common.Now()) - return req.ProcessMove() -} - -func (a *Allocation) CopyObject(path string, destPath string) error { - if !a.isInitialized() { - return notInitialized - } - - if !a.CanCopy() { - return constants.ErrFileOptionNotPermitted - } - - if len(path) == 0 || len(destPath) == 0 { - return errors.New("invalid_path", "Invalid path for copy") - } - path = zboxutil.RemoteClean(path) - isabs := zboxutil.IsRemoteAbs(path) - if !isabs { - return errors.New("invalid_path", "Path should be valid and absolute") - } - - err := ValidateRemoteFileName(destPath) - if err != nil { - return err - } - - req := &CopyRequest{Consensus: Consensus{RWMutex: &sync.RWMutex{}}} - req.allocationObj = a - req.blobbers = a.Blobbers - req.allocationID = a.ID - req.allocationTx = a.Tx - if destPath != "/" { - destPath = strings.TrimSuffix(destPath, "/") - } - req.destPath = destPath - req.fullconsensus = a.fullconsensus - req.consensusThresh = a.consensusThreshold - req.ctx, req.ctxCncl = context.WithCancel(a.ctx) - req.remotefilepath = path - req.copyMask = zboxutil.NewUint128(1).Lsh(uint64(len(a.Blobbers))).Sub64(1) - req.maskMU = &sync.Mutex{} - req.connectionID = zboxutil.NewConnectionId() - req.timestamp = int64(common.Now()) - return req.ProcessCopy() -} - func (a *Allocation) GetAuthTicketForShare( path, filename, referenceType, refereeClientID string) (string, error) { diff --git a/zboxcore/sdk/allocation_file_copy_test.go b/zboxcore/sdk/allocation_file_copy_test.go deleted file mode 100644 index 317e4e580..000000000 --- a/zboxcore/sdk/allocation_file_copy_test.go +++ /dev/null @@ -1,142 +0,0 @@ -package sdk - -import ( - "encoding/json" - "net/http" - "strconv" - "testing" - "time" - - "github.com/0chain/errors" - "github.com/0chain/gosdk/core/resty" - "github.com/0chain/gosdk/core/zcncrypto" - "github.com/0chain/gosdk/zboxcore/blockchain" - zclient "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/mocks" - "github.com/0chain/gosdk/zboxcore/zboxutil" - "github.com/stretchr/testify/require" -) - -func TestAllocation_CopyObject(t *testing.T) { - const ( - mockType = "f" - ) - - rawClient := zboxutil.Client - createClient := resty.CreateClient - - var mockClient = mocks.HttpClient{} - zboxutil.Client = &mockClient - - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ - ClientID: mockClientId, - ClientKey: mockClientKey, - } - - zboxutil.Client = &mockClient - resty.CreateClient = func(t *http.Transport, timeout time.Duration) resty.Client { - return &mockClient - } - - defer func() { - zboxutil.Client = rawClient - resty.CreateClient = createClient - }() - - type parameters struct { - path string - destPath string - } - tests := []struct { - name string - parameters parameters - setup func(*testing.T, string, *Allocation) (teardown func(*testing.T)) - wantErr bool - errMsg string - }{ - { - name: "Test_Uninitialized_Failed", - setup: func(t *testing.T, testCaseName string, a *Allocation) (teardown func(t *testing.T)) { - a.initialized = false - return func(t *testing.T) { - a.initialized = true - } - }, - wantErr: true, - errMsg: "sdk_not_initialized: Please call InitStorageSDK Init and use GetAllocation to get the allocation object", - }, - { - name: "Test_Wrong_Path_Or_Destination_Path_Failed", - parameters: parameters{ - path: "", - destPath: "", - }, - wantErr: true, - errMsg: "invalid_path: Invalid path for copy", - }, - { - name: "Test_Invalid_Remote_Absolute_Path", - parameters: parameters{ - path: "abc", - destPath: "/d", - }, - wantErr: true, - errMsg: "invalid_path: Path should be valid and absolute", - }, - { - name: "Test_Success", - parameters: parameters{ - path: "/1.txt", - destPath: "/d", - }, - setup: func(t *testing.T, testCaseName string, a *Allocation) (teardown func(t *testing.T)) { - body, err := json.Marshal(&fileref.ReferencePath{ - Meta: map[string]interface{}{ - "type": mockType, - }, - }) - require.NoError(t, err) - setupMockHttpResponse(t, &mockClient, "TestAllocation_CopyObject", testCaseName, a, http.MethodGet, http.StatusOK, body) - setupMockHttpResponse(t, &mockClient, "TestAllocation_CopyObject", testCaseName, a, http.MethodPost, http.StatusOK, []byte("")) - setupMockRollback(a, &mockClient) - setupMockCommitRequest(a) - setupMockWriteLockRequest(a, &mockClient) - return nil - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - require := require.New(t) - a := &Allocation{ - DataShards: numBlobbers, - FileOptions: 63, - } - a.InitAllocation() - - setupMockAllocation(t, a) - - sdkInitialized = true - for i := 0; i < numBlobbers; i++ { - a.Blobbers = append(a.Blobbers, &blockchain.StorageNode{ - ID: tt.name + mockBlobberId + strconv.Itoa(i), - Baseurl: "http://TestAllocation_CopyObject" + tt.name + mockBlobberUrl + strconv.Itoa(i), - }) - } - if tt.setup != nil { - if teardown := tt.setup(t, tt.name, a); teardown != nil { - defer teardown(t) - } - } - err := a.CopyObject(tt.parameters.path, tt.parameters.destPath) - require.EqualValues(tt.wantErr, err != nil) - if err != nil { - require.EqualValues(tt.errMsg, errors.Top(err)) - return - } - require.NoErrorf(err, "unexpected error: %v", err) - }) - } -} diff --git a/zboxcore/sdk/allocation_file_move_test.go b/zboxcore/sdk/allocation_file_move_test.go deleted file mode 100644 index e1f437992..000000000 --- a/zboxcore/sdk/allocation_file_move_test.go +++ /dev/null @@ -1,129 +0,0 @@ -package sdk - -import ( - "encoding/json" - "net/http" - "strconv" - "testing" - - "github.com/0chain/errors" - "github.com/0chain/gosdk/core/zcncrypto" - "github.com/0chain/gosdk/zboxcore/blockchain" - zclient "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/mocks" - "github.com/0chain/gosdk/zboxcore/zboxutil" - "github.com/stretchr/testify/require" -) - -func TestAllocation_MoveObject(t *testing.T) { - - const ( - mockType = "f" - ) - - rawClient := zboxutil.Client - - var mockClient = mocks.HttpClient{} - zboxutil.Client = &mockClient - - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ - ClientID: mockClientId, - ClientKey: mockClientKey, - } - - zboxutil.Client = &mockClient - - defer func() { - zboxutil.Client = rawClient - }() - - type parameters struct { - path string - destPath string - } - tests := []struct { - name string - parameters parameters - setup func(*testing.T, string, *Allocation) (teardown func(*testing.T)) - wantErr bool - errMsg string - }{ - { - name: "Test_Cover_Copy_Object", - parameters: parameters{ - path: "/1.txt", - destPath: "/d", - }, - setup: func(t *testing.T, testCaseName string, a *Allocation) (teardown func(t *testing.T)) { - a.initialized = false - return func(t *testing.T) { - a.initialized = true - } - }, - wantErr: true, - errMsg: "sdk_not_initialized: Please call InitStorageSDK Init and use GetAllocation to get the allocation object", - }, - { - name: "Test_Cover_Delete_Object", - parameters: parameters{ - path: "/1.txt", - destPath: "/d", - }, - setup: func(t *testing.T, testCaseName string, a *Allocation) (teardown func(t *testing.T)) { - body, err := json.Marshal(&fileref.ReferencePath{ - Meta: map[string]interface{}{ - "type": mockType, - }, - }) - require.NoError(t, err) - setupMockHttpResponse(t, &mockClient, "TestAllocation_MoveObject", testCaseName, a, http.MethodGet, http.StatusOK, body) - setupMockHttpResponse(t, &mockClient, "TestAllocation_MoveObject", testCaseName, a, http.MethodPost, http.StatusOK, []byte("")) - setupMockHttpResponse(t, &mockClient, "TestAllocation_MoveObject", testCaseName, a, http.MethodPost, http.StatusOK, []byte(`{"status":2}`)) - setupMockHttpResponse(t, &mockClient, "TestAllocation_MoveObject", testCaseName, a, http.MethodPost, http.StatusOK, []byte(`{"status":2}`)) - setupMockHttpResponse(t, &mockClient, "TestAllocation_MoveObject", testCaseName, a, http.MethodGet, http.StatusOK, body) - setupMockHttpResponse(t, &mockClient, "TestAllocation_MoveObject", testCaseName, a, http.MethodDelete, http.StatusOK, []byte("")) - setupMockHttpResponse(t, &mockClient, "TestAllocation_MoveObject", testCaseName, a, http.MethodDelete, http.StatusOK, []byte("")) - setupMockHttpResponse(t, &mockClient, "TestAllocation_MoveObject", testCaseName, a, http.MethodDelete, http.StatusOK, []byte("")) - setupMockCommitRequest(a) - setupMockRollback(a, &mockClient) - return nil - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - require := require.New(t) - a := &Allocation{ - Tx: "TestAllocation_MoveObject", - DataShards: 2, - ParityShards: 2, - } - - setupMockAllocation(t, a) - - for i := 0; i < numBlobbers; i++ { - - path := "/TestAllocation_MoveObject" + tt.name + mockBlobberUrl + strconv.Itoa(i) - - a.Blobbers = append(a.Blobbers, &blockchain.StorageNode{ - ID: tt.name + mockBlobberId + strconv.Itoa(i), - Baseurl: path, - }) - } - if tt.setup != nil { - if teardown := tt.setup(t, tt.name, a); teardown != nil { - defer teardown(t) - } - } - err := a.MoveObject(tt.parameters.path, tt.parameters.destPath) - require.EqualValues(tt.wantErr, err != nil) - if err != nil { - require.EqualValues(tt.errMsg, errors.Top(err)) - return - } - require.NoErrorf(err, "unexpected error: %v", err) - }) - } -} diff --git a/zboxcore/sdk/allocation_file_rename_test.go b/zboxcore/sdk/allocation_file_rename_test.go deleted file mode 100644 index 32a9ec05b..000000000 --- a/zboxcore/sdk/allocation_file_rename_test.go +++ /dev/null @@ -1,139 +0,0 @@ -package sdk - -import ( - "encoding/json" - "net/http" - "strconv" - "testing" - "time" - - "github.com/0chain/errors" - "github.com/0chain/gosdk/core/resty" - "github.com/0chain/gosdk/core/zcncrypto" - "github.com/0chain/gosdk/zboxcore/blockchain" - zclient "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/mocks" - "github.com/0chain/gosdk/zboxcore/zboxutil" - "github.com/stretchr/testify/require" -) - -func TestAllocation_RenameObject(t *testing.T) { - const ( - mockType = "f" - ) - - rawClient := zboxutil.Client - createClient := resty.CreateClient - - var mockClient = mocks.HttpClient{} - zboxutil.Client = &mockClient - - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ - ClientID: mockClientId, - ClientKey: mockClientKey, - } - - zboxutil.Client = &mockClient - resty.CreateClient = func(t *http.Transport, timeout time.Duration) resty.Client { - return &mockClient - } - - defer func() { - zboxutil.Client = rawClient - resty.CreateClient = createClient - }() - type parameters struct { - path string - destName string - } - tests := []struct { - name string - parameters parameters - setup func(*testing.T, string, *Allocation) (teardown func(*testing.T)) - wantErr bool - errMsg string - }{ - { - name: "Test_Uninitialized_Failed", - setup: func(t *testing.T, testCaseName string, a *Allocation) (teardown func(t *testing.T)) { - a.initialized = false - return func(t *testing.T) { - a.initialized = true - } - }, - wantErr: true, - errMsg: "sdk_not_initialized: Please call InitStorageSDK Init and use GetAllocation to get the allocation object", - }, - { - name: "Test_Wrong_Path_Or_Destination_Path_Failed", - parameters: parameters{ - path: "", - destName: "", - }, - wantErr: true, - errMsg: "invalid_path: Invalid path for the list", - }, - { - name: "Test_Invalid_Remote_Absolute_Path", - parameters: parameters{ - path: "abc", - destName: "/2.txt", - }, - wantErr: true, - errMsg: "invalid_path: Path should be valid and absolute", - }, - { - name: "Test_Success", - parameters: parameters{ - path: "/1.txt", - destName: "/2.txt", - }, - setup: func(t *testing.T, testCaseName string, a *Allocation) (teardown func(t *testing.T)) { - body, err := json.Marshal(&fileref.ReferencePath{ - Meta: map[string]interface{}{ - "type": mockType, - }, - }) - require.NoError(t, err) - setupMockHttpResponse(t, &mockClient, "TestAllocation_RenameObject", testCaseName, a, http.MethodGet, http.StatusOK, body) - setupMockHttpResponse(t, &mockClient, "TestAllocation_RenameObject", testCaseName, a, http.MethodPost, http.StatusOK, []byte("")) - setupMockCommitRequest(a) - setupMockRollback(a, &mockClient) - setupMockWriteLockRequest(a, &mockClient) - return nil - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - require := require.New(t) - a := &Allocation{ - DataShards: 2, - ParityShards: 2, - FileOptions: 63, - } - a.InitAllocation() - sdkInitialized = true - for i := 0; i < numBlobbers; i++ { - a.Blobbers = append(a.Blobbers, &blockchain.StorageNode{ - ID: tt.name + mockBlobberId + strconv.Itoa(i), - Baseurl: "http://TestAllocation_RenameObject" + tt.name + mockBlobberUrl + strconv.Itoa(i), - }) - } - if tt.setup != nil { - if teardown := tt.setup(t, tt.name, a); teardown != nil { - defer teardown(t) - } - } - err := a.RenameObject(tt.parameters.path, tt.parameters.destName) - require.EqualValues(tt.wantErr, err != nil) - if err != nil { - require.EqualValues(tt.errMsg, errors.Top(err)) - return - } - require.NoErrorf(err, "unexpected error: %v", err) - }) - } -} From 1c9f143fe842e6c88fec1a6bc5fa0ced2ca84682 Mon Sep 17 00:00:00 2001 From: shahnawaz-creator <117025384+shahnawaz-creator@users.noreply.github.com> Date: Tue, 12 Sep 2023 18:17:55 +0530 Subject: [PATCH 035/134] Updated self hosted macos runner (#1219) * Updated self hosted macos runner * fixed runner name build-sdks.yml --- .github/workflows/build-sdks.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build-sdks.yml b/.github/workflows/build-sdks.yml index fcbdb8dc9..d21034514 100644 --- a/.github/workflows/build-sdks.yml +++ b/.github/workflows/build-sdks.yml @@ -18,7 +18,7 @@ env: jobs: build-ios: name: Build-ios - runs-on: macos-latest + runs-on: macos-runner steps: - name: Checkout code @@ -193,7 +193,7 @@ jobs: build-macos: name: Build-macos - runs-on: macos-latest + runs-on: macos-runner steps: - name: Checkout code From bd1c6857e6e78dfee362862cf358a90042d0a366 Mon Sep 17 00:00:00 2001 From: Dinmukhammed Kambarov <52813950+din-mukhammed@users.noreply.github.com> Date: Wed, 13 Sep 2023 20:51:46 +0600 Subject: [PATCH 036/134] remove path header, fix ws tag (#1220) --- wasmsdk/blobber.go | 3 +-- zboxcore/sdk/blockdownloadworker.go | 1 - zboxcore/sdk/download_reqeust_header.go | 5 ----- zboxcore/sdk/downloadworker.go | 1 - 4 files changed, 1 insertion(+), 9 deletions(-) diff --git a/wasmsdk/blobber.go b/wasmsdk/blobber.go index bc951826c..e9bf9a647 100644 --- a/wasmsdk/blobber.go +++ b/wasmsdk/blobber.go @@ -435,10 +435,9 @@ type BulkUploadOption struct { ThumbnailBytes jsbridge.Bytes `json:"thumbnailBytes,omitempty"` Encrypt bool `json:"encrypt,omitempty"` - Webstreaming bool `json:"webstreaming,omitempty"` + IsWebstreaming bool `json:"webstreaming,omitempty"` IsUpdate bool `json:"isUpdate,omitempty"` IsRepair bool `json:"isRepair,omitempty"` - IsWebstreaming bool `json:"isWebstreaming,omitempty"` NumBlocks int `json:"numBlocks,omitempty"` FileSize int64 `json:"fileSize,omitempty"` diff --git a/zboxcore/sdk/blockdownloadworker.go b/zboxcore/sdk/blockdownloadworker.go index f412b736a..5d496ad70 100644 --- a/zboxcore/sdk/blockdownloadworker.go +++ b/zboxcore/sdk/blockdownloadworker.go @@ -124,7 +124,6 @@ func (req *BlockDownloadRequest) downloadBlobberBlock() { } header := &DownloadRequestHeader{} - header.Path = req.remotefilepath header.PathHash = req.remotefilepathhash header.BlockNum = req.blockNum header.NumBlocks = req.numBlocks diff --git a/zboxcore/sdk/download_reqeust_header.go b/zboxcore/sdk/download_reqeust_header.go index 99b6c529e..cd0e24e52 100644 --- a/zboxcore/sdk/download_reqeust_header.go +++ b/zboxcore/sdk/download_reqeust_header.go @@ -10,7 +10,6 @@ import ( type DownloadRequestHeader struct { ClientID string PathHash string - Path string BlockNum int64 NumBlocks int64 ReadMarker []byte @@ -22,10 +21,6 @@ type DownloadRequestHeader struct { // ToHeader update header func (h *DownloadRequestHeader) ToHeader(req *http.Request) { - if h.Path != "" { - req.Header.Set("X-Path", h.Path) - } - if h.PathHash != "" { req.Header.Set("X-Path-Hash", h.PathHash) } diff --git a/zboxcore/sdk/downloadworker.go b/zboxcore/sdk/downloadworker.go index efc608d90..4359d46a2 100644 --- a/zboxcore/sdk/downloadworker.go +++ b/zboxcore/sdk/downloadworker.go @@ -591,7 +591,6 @@ func (req *DownloadRequest) attemptSubmitReadMarker(blobber *blockchain.StorageN } header := &DownloadRequestHeader{ - Path: req.remotefilepath, PathHash: req.remotefilepathhash, ReadMarker: rmData, ConnectionID: req.connectionID, From 58e7ff59241a9458879d73e27b3fa574af050662 Mon Sep 17 00:00:00 2001 From: Jayash Satolia <73050737+Jayashsatolia403@users.noreply.github.com> Date: Fri, 15 Sep 2023 23:49:17 +0530 Subject: [PATCH 037/134] Feature/ Challenge based on rounds (#1191) * Fix * Fix * Fix * Fix * Fix * Debug * Debug * Debug * Fix * Heavy logging * Fix * More logging * Changed logging * Removed logging * Debug * Fix * Fix * Fix --- core/transaction/cache.go | 5 +- zboxcore/sdk/common.go | 106 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 110 insertions(+), 1 deletion(-) diff --git a/core/transaction/cache.go b/core/transaction/cache.go index c9c24873d..57f915b49 100644 --- a/core/transaction/cache.go +++ b/core/transaction/cache.go @@ -13,7 +13,10 @@ import ( "github.com/0chain/gosdk/core/util" ) -const GET_BALANCE = `/v1/client/get/balance?client_id=` +const ( + GET_BALANCE = `/v1/client/get/balance?client_id=` +) + const consensusThresh = float32(25.0) var Cache *NonceCache diff --git a/zboxcore/sdk/common.go b/zboxcore/sdk/common.go index de37a85d9..02718b7c4 100644 --- a/zboxcore/sdk/common.go +++ b/zboxcore/sdk/common.go @@ -3,10 +3,13 @@ package sdk import ( "context" "encoding/json" + stdErrors "errors" "fmt" + "github.com/0chain/gosdk/core/util" "io/ioutil" "net/http" "path" + "sort" "strconv" "sync" "time" @@ -19,6 +22,10 @@ import ( "github.com/0chain/gosdk/zboxcore/zboxutil" ) +const ( + CURRENT_ROUND = "/v1/current-round" +) + func getObjectTreeFromBlobber(ctx context.Context, allocationID, allocationTx string, remoteFilePath string, blobber *blockchain.StorageNode) (fileref.RefEntity, error) { httpreq, err := zboxutil.NewObjectTreeRequest(blobber.Baseurl, allocationID, allocationTx, remoteFilePath) if err != nil { @@ -121,3 +128,102 @@ func ValidateRemoteFileName(remotePath string) error { return nil } + +func GetRoundFromSharders(sharders []string) (int64, error) { + + if len(sharders) == 0 { + return 0, stdErrors.New("get round failed. no sharders") + } + + result := make(chan *util.GetResponse, len(sharders)) + + var numSharders = len(sharders) + util.Shuffle(sharders) + + // use 5 sharders to get round + if numSharders > 5 { + numSharders = 5 + sharders = sharders[:numSharders] + } + + queryFromSharders(sharders, fmt.Sprintf("%v", CURRENT_ROUND), result) + + const consensusThresh = float32(25.0) + + var rounds []int64 + + consensus := int64(0) + roundMap := make(map[int64]int64) + + round := int64(0) + + waitTimeC := time.After(10 * time.Second) + for i := 0; i < numSharders; i++ { + select { + case <-waitTimeC: + return 0, stdErrors.New("get round failed. consensus not reached") + case rsp := <-result: + if rsp.StatusCode != http.StatusOK { + continue + } + + var respRound int64 + err := json.Unmarshal([]byte(rsp.Body), &respRound) + + if err != nil { + continue + } + + rounds = append(rounds, respRound) + + sort.Slice(rounds, func(i, j int) bool { + return false + }) + + medianRound := rounds[len(rounds)/2] + + roundMap[medianRound]++ + + if roundMap[medianRound] > consensus { + + consensus = roundMap[medianRound] + round = medianRound + rate := consensus * 100 / int64(numSharders) + + if rate >= int64(consensusThresh) { + return round, nil + } + } + } + } + + return round, nil +} + +func queryFromSharders(sharders []string, query string, + result chan *util.GetResponse) { + queryFromShardersContext(context.Background(), sharders, query, result) +} + +func queryFromShardersContext(ctx context.Context, sharders []string, + query string, result chan *util.GetResponse) { + + for _, sharder := range sharders { + go func(sharderurl string) { + url := fmt.Sprintf("%v%v", sharderurl, query) + req, err := util.NewHTTPGetRequestContext(ctx, url) + + if err != nil { + return + } + + res, err := req.Get() + + if err != nil { + return + } + + result <- res + }(sharder) + } +} From adbbd823e3000c5f08b4ccdf5d18830970ca29e3 Mon Sep 17 00:00:00 2001 From: Manohar Reddy Date: Sat, 16 Sep 2023 13:50:01 +0200 Subject: [PATCH 038/134] expose send in wasm (#1225) --- core/version/version.go | 2 +- wasmsdk/demo/index.html | 13 +++++++++++++ wasmsdk/proxy.go | 1 + wasmsdk/sdk.go | 36 ++++++++++++++++++++++++++++++++++++ 4 files changed, 51 insertions(+), 1 deletion(-) diff --git a/core/version/version.go b/core/version/version.go index 738463466..f2e673bbc 100644 --- a/core/version/version.go +++ b/core/version/version.go @@ -2,5 +2,5 @@ //====== THIS IS AUTOGENERATED FILE. DO NOT MODIFY ======== package version -const VERSIONSTR = "v1.8.17-78-g80b63345" +const VERSIONSTR = "v1.10.0-48-gbd1c6857" diff --git a/wasmsdk/demo/index.html b/wasmsdk/demo/index.html index 58184593a..2ef9429aa 100644 --- a/wasmsdk/demo/index.html +++ b/wasmsdk/demo/index.html @@ -49,6 +49,7 @@

please download zcn.wasm from https://github.com/0chain/gosdk/releases/lates + @@ -236,6 +237,18 @@

please download zcn.wasm from https://github.com/0chain/gosdk/releases/lates await goWasm.sdk.faucet("pour", JSON.stringify("{Pay day}"), 10) }) + onClick('btnSendTokensToOtherWallet', async () => { + try { + const output = await goWasm.sdk.send( + "5ad6e4d206d853833e96ff5c833369e567d2ef41ae1d5093141e1f90f1e8dcb0", + 10000000000, + ) + console.log("successfully sent with txn hash: ", output) + } catch (e) { + alert(e) + } + }) + onClick('btnGetBalance', async () => { const { clientID } = getWallet() const wallet = await goWasm.sdk.getWalletBalance(clientID) diff --git a/wasmsdk/proxy.go b/wasmsdk/proxy.go index 76648d4b3..9024bff8f 100644 --- a/wasmsdk/proxy.go +++ b/wasmsdk/proxy.go @@ -179,6 +179,7 @@ func main() { "updatecontainer": UpdateContainer, "searchcontainer": SearchContainer, "updateForbidAllocation": UpdateForbidAllocation, + "send": send, // player "play": play, diff --git a/wasmsdk/sdk.go b/wasmsdk/sdk.go index ad9892829..e97dda3d1 100644 --- a/wasmsdk/sdk.go +++ b/wasmsdk/sdk.go @@ -6,9 +6,11 @@ package main import ( "encoding/hex" "encoding/json" + "errors" "fmt" "io" "os" + "sync" "github.com/0chain/gosdk/core/encryption" "github.com/0chain/gosdk/core/imageutil" @@ -121,3 +123,37 @@ func makeSCRestAPICall(scAddress, relativePath, paramsJson string) (string, erro b, err := zboxutil.MakeSCRestAPICall(scAddress, relativePath, params, nil) return string(b), err } + +func send(to_client_id string, tokens uint64) (string, error) { + + wg := &sync.WaitGroup{} + cb := &transactionCallback{wg: wg} + txn, err := zcncore.NewTransaction(cb, 0, 0) + if err != nil { + return "", err + } + + wg.Add(1) + err = txn.Send(to_client_id, tokens, "") + if err == nil { + wg.Wait() + } else { + return "", err + } + + if cb.success { + cb.success = false + wg.Add(1) + err := txn.Verify() + if err == nil { + wg.Wait() + } else { + return "", err + } + if cb.success { + return txn.Hash(), nil + } + } + + return "", errors.New(cb.errMsg) +} From 3f83c7b2e982f9a57aa57bc77c8d5c543a402705 Mon Sep 17 00:00:00 2001 From: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Date: Sun, 17 Sep 2023 16:15:24 +0530 Subject: [PATCH 039/134] fix rename dir err (#1226) --- zboxcore/allocationchange/renameobject.go | 1 + 1 file changed, 1 insertion(+) diff --git a/zboxcore/allocationchange/renameobject.go b/zboxcore/allocationchange/renameobject.go index d9e3955a8..7d0886c82 100644 --- a/zboxcore/allocationchange/renameobject.go +++ b/zboxcore/allocationchange/renameobject.go @@ -48,6 +48,7 @@ func (ch *RenameFileChange) ProcessChange(rootRef *fileref.Ref, _ map[string]str affectedRef = &(ch.ObjectTree.(*fileref.FileRef)).Ref } else { err = errors.New("invalid_rename_op", "Object to rename is not a file use move instead") + return } affectedRef.Path = pathutil.Join(parentPath, ch.NewName) From 522e90c5429c8c4aa0fdb9e54eae35212798efb8 Mon Sep 17 00:00:00 2001 From: Manohar Reddy Date: Wed, 20 Sep 2023 17:05:23 +0200 Subject: [PATCH 040/134] Txnfee send (#1227) * add txnfee for send function * return txn verify output --- core/version/version.go | 2 +- wasmsdk/demo/index.html | 1 + wasmsdk/sdk.go | 7 +++---- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/core/version/version.go b/core/version/version.go index f2e673bbc..869920b30 100644 --- a/core/version/version.go +++ b/core/version/version.go @@ -2,5 +2,5 @@ //====== THIS IS AUTOGENERATED FILE. DO NOT MODIFY ======== package version -const VERSIONSTR = "v1.10.0-48-gbd1c6857" +const VERSIONSTR = "v1.10.0-51-g725742a3" diff --git a/wasmsdk/demo/index.html b/wasmsdk/demo/index.html index 2ef9429aa..2a8cafa62 100644 --- a/wasmsdk/demo/index.html +++ b/wasmsdk/demo/index.html @@ -242,6 +242,7 @@

please download zcn.wasm from https://github.com/0chain/gosdk/releases/lates const output = await goWasm.sdk.send( "5ad6e4d206d853833e96ff5c833369e567d2ef41ae1d5093141e1f90f1e8dcb0", 10000000000, + 0 ) console.log("successfully sent with txn hash: ", output) } catch (e) { diff --git a/wasmsdk/sdk.go b/wasmsdk/sdk.go index e97dda3d1..7eeccda23 100644 --- a/wasmsdk/sdk.go +++ b/wasmsdk/sdk.go @@ -124,11 +124,10 @@ func makeSCRestAPICall(scAddress, relativePath, paramsJson string) (string, erro return string(b), err } -func send(to_client_id string, tokens uint64) (string, error) { - +func send(to_client_id string, tokens uint64, fee uint64) (string, error) { wg := &sync.WaitGroup{} cb := &transactionCallback{wg: wg} - txn, err := zcncore.NewTransaction(cb, 0, 0) + txn, err := zcncore.NewTransaction(cb, fee, 0) if err != nil { return "", err } @@ -151,7 +150,7 @@ func send(to_client_id string, tokens uint64) (string, error) { return "", err } if cb.success { - return txn.Hash(), nil + return txn.GetVerifyOutput(), nil } } From 0d649990dbb6080f9b1ee2ec3b824ab60079a9d5 Mon Sep 17 00:00:00 2001 From: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Date: Mon, 25 Sep 2023 02:05:18 +0530 Subject: [PATCH 041/134] add rename dir (#1230) --- zboxcore/allocationchange/renameobject.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/zboxcore/allocationchange/renameobject.go b/zboxcore/allocationchange/renameobject.go index 7d0886c82..64f5851d9 100644 --- a/zboxcore/allocationchange/renameobject.go +++ b/zboxcore/allocationchange/renameobject.go @@ -16,7 +16,6 @@ type RenameFileChange struct { } func (ch *RenameFileChange) ProcessChange(rootRef *fileref.Ref, _ map[string]string) (err error) { - parentPath := path.Dir(ch.ObjectTree.GetPath()) fields, err := common.GetPathFields(parentPath) if err != nil { @@ -47,12 +46,12 @@ func (ch *RenameFileChange) ProcessChange(rootRef *fileref.Ref, _ map[string]str if ch.ObjectTree.GetType() == fileref.FILE { affectedRef = &(ch.ObjectTree.(*fileref.FileRef)).Ref } else { - err = errors.New("invalid_rename_op", "Object to rename is not a file use move instead") - return + affectedRef = ch.ObjectTree.(*fileref.Ref) } affectedRef.Path = pathutil.Join(parentPath, ch.NewName) affectedRef.Name = ch.NewName + affectedRef.HashToBeComputed = true dirRef.AddChild(ch.ObjectTree) found = true @@ -77,6 +76,7 @@ func (ch *RenameFileChange) processChildren(curRef *fileref.Ref) { } else { childRef = childRefEntity.(*fileref.Ref) } + childRef.HashToBeComputed = true childRef.Path = pathutil.Join(curRef.Path, childRef.Name) if childRefEntity.GetType() == fileref.DIRECTORY { ch.processChildren(childRef) From b8df9abfe46785cbca0812bb41f10b434af3e650 Mon Sep 17 00:00:00 2001 From: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Date: Mon, 25 Sep 2023 02:33:42 +0530 Subject: [PATCH 042/134] Async read (#1213) * basic timings for download * upload timings * to seconds * more timings for upload processing * display ms properly * cleanup * fix merge * fix merge * add more timing logs * fix dur to ms * add timings to read and build data * async read * range over errChan * fix unit test * rmv ctx cancel from multi upload * wait for last chunk * fix loop * rmv readChunk timing * increase buffer size * rmv timing logs * cleanup * updated go to version 1.20 * use -buildvcs=false --------- Co-authored-by: din-mukhammed Co-authored-by: Dinmukhammed Kambarov <52813950+din-mukhammed@users.noreply.github.com> Co-authored-by: shahnawaz-creator Co-authored-by: Manohar Reddy --- .github/workflows/codeql-analysis.yml | 2 +- .github/workflows/sdk-release.yml | 6 +- Makefile | 2 +- go.mod | 2 +- zboxcore/sdk/allocation.go | 17 +- zboxcore/sdk/chunked_upload.go | 220 ++++++++++---------- zboxcore/sdk/chunked_upload_chunk_reader.go | 3 - zboxcore/sdk/chunked_upload_form_builder.go | 7 +- zboxcore/sdk/chunked_upload_model.go | 98 ++++++++- zboxcore/sdk/commitworker.go | 3 +- zboxcore/sdk/downloadworker.go | 11 + zboxcore/sdk/multi_operation_worker.go | 10 +- zboxcore/sdk/upload_worker.go | 5 - 13 files changed, 246 insertions(+), 140 deletions(-) diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index ad6754aa0..78975fbb6 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -34,7 +34,7 @@ jobs: - name: Set up Go 1.x uses: actions/setup-go@v3 with: - go-version: ^1.18 + go-version: ^1.20 - name: Checkout repository uses: actions/checkout@v3 diff --git a/.github/workflows/sdk-release.yml b/.github/workflows/sdk-release.yml index a52bad2ed..a1db6e2b4 100644 --- a/.github/workflows/sdk-release.yml +++ b/.github/workflows/sdk-release.yml @@ -24,10 +24,10 @@ jobs: name: sdk-build runs-on: [self-hosted, arc-runner] steps: - - name: Set up Go 1.18 + - name: Set up Go 1.20 uses: actions/setup-go@v2 with: - go-version: ^1.18 + go-version: ^1.20 - name: Checkout uses: actions/checkout@v2 @@ -71,7 +71,7 @@ jobs: fi - name: Build - run: docker run --rm -v $PWD:/gosdk -w /gosdk golang:1.18 make wasm-build + run: docker run --rm -v $PWD:/gosdk -w /gosdk golang:1.20 make wasm-build - name: Upload binaries to release uses: svenstaro/upload-release-action@v2 diff --git a/Makefile b/Makefile index 22acd28d0..3398c21ea 100644 --- a/Makefile +++ b/Makefile @@ -35,7 +35,7 @@ gosdk-build: gomod-download go build -x -v -tags bn256 ./... wasm-build: getrev - CGO_ENABLED=0 GOOS=js GOARCH=wasm go build -o ./zcn.wasm ./wasmsdk + CGO_ENABLED=0 GOOS=js GOARCH=wasm go build -buildvcs=false -o ./zcn.wasm ./wasmsdk wasm-test: wasm-build env -i $(shell go env) PATH="$(shell go env GOROOT)/misc/wasm:$(PATH)" CGO_ENABLED=0 GOOS=js GOARCH=wasm go test -v github.com/0chain/gosdk/wasmsdk/jsbridge/... diff --git a/go.mod b/go.mod index 578f0e474..d7dd961e2 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/0chain/gosdk -go 1.18 +go 1.20 require ( github.com/0chain/common v0.0.6-0.20230127095721-8df4d1d72565 diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 7696357c5..9a8b40432 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -631,6 +631,7 @@ func (a *Allocation) StartChunkedUpload(workdir, localPath string, } connectionId := zboxutil.NewConnectionId() + now := time.Now() ChunkedUpload, err := CreateChunkedUpload(workdir, a, fileMeta, fileReader, isUpdate, isRepair, webStreaming, connectionId, @@ -638,6 +639,9 @@ func (a *Allocation) StartChunkedUpload(workdir, localPath string, if err != nil { return err } + elapsedCreateChunkedUpload := time.Since(now) + logger.Logger.Info("[StartChunkedUpload]", zap.String("allocation_id", a.ID), + zap.Duration("CreateChunkedUpload", elapsedCreateChunkedUpload)) return ChunkedUpload.Start() } @@ -894,7 +898,6 @@ func (a *Allocation) DoMultiOperation(operations []OperationRequest) error { } } } - return nil } @@ -1096,6 +1099,7 @@ func (a *Allocation) processReadMarker(drs []*DownloadRequest) { if a.ReadPriceRange.Max == 0 && a.ReadPriceRange.Min == 0 { isReadFree = true } + now := time.Now() for _, dr := range drs { wg.Add(1) @@ -1114,6 +1118,7 @@ func (a *Allocation) processReadMarker(drs []*DownloadRequest) { }(dr) } wg.Wait() + elapsedProcessDownloadRequest := time.Since(now) // Do not send readmarkers for free reads if isReadFree { @@ -1125,11 +1130,15 @@ func (a *Allocation) processReadMarker(drs []*DownloadRequest) { a.downloadChan <- dr }(dr) } + l.Logger.Info("[processReadMarker]", zap.String("allocation_id", a.ID), + zap.Int("num of download requests", len(drs)), + zap.Duration("processDownloadRequest", elapsedProcessDownloadRequest)) return } successMask := zboxutil.NewUint128(0) var redeemError error + for pos, totalBlocks := range blobberMap { if totalBlocks == 0 { continue @@ -1147,6 +1156,12 @@ func (a *Allocation) processReadMarker(drs []*DownloadRequest) { }(pos, totalBlocks) } wg.Wait() + elapsedSubmitReadmarker := time.Since(now) - elapsedProcessDownloadRequest + + l.Logger.Info("[processReadMarker]", zap.String("allocation_id", a.ID), + zap.Int("num of download requests", len(drs)), + zap.Duration("processDownloadRequest", elapsedProcessDownloadRequest), + zap.Duration("submitReadmarker", elapsedSubmitReadmarker)) for _, dr := range drs { if dr.skip { continue diff --git a/zboxcore/sdk/chunked_upload.go b/zboxcore/sdk/chunked_upload.go index 89d082629..03bb39add 100644 --- a/zboxcore/sdk/chunked_upload.go +++ b/zboxcore/sdk/chunked_upload.go @@ -165,7 +165,8 @@ func CreateChunkedUpload( opCode: opCode, } - su.ctx, su.ctxCncl = context.WithCancel(allocationObj.ctx) + // su.ctx, su.ctxCncl = context.WithCancel(allocationObj.ctx) + su.ctx, su.ctxCncl = context.WithCancelCause(allocationObj.ctx) if isUpdate { su.httpMethod = http.MethodPut @@ -277,76 +278,11 @@ func CreateChunkedUpload( su.formBuilder = CreateChunkedUploadFormBuilder() su.isRepair = isRepair + su.uploadChan = make(chan UploadData, 1) + su.uploadWG.Add(1) + go su.uploadProcessor() return su, nil - -} - -// ChunkedUpload upload manager with chunked upload feature -type ChunkedUpload struct { - consensus Consensus - - workdir string - - allocationObj *Allocation - progress UploadProgress - progressStorer ChunkedUploadProgressStorer - client zboxutil.HttpClient - - uploadMask zboxutil.Uint128 - - // httpMethod POST = Upload File / PUT = Update file - httpMethod string - buildChange func(ref *fileref.FileRef, - uid uuid.UUID, timestamp common.Timestamp) allocationchange.AllocationChange - - fileMeta FileMeta - fileReader io.Reader - fileErasureEncoder reedsolomon.Encoder - fileEncscheme encryption.EncryptionScheme - fileHasher Hasher - - thumbnailBytes []byte - thumbailErasureEncoder reedsolomon.Encoder - - chunkReader ChunkedUploadChunkReader - formBuilder ChunkedUploadFormBuilder - - // encryptOnUpload encrypt data on upload or not. - encryptOnUpload bool - // webStreaming whether data has to be encoded. - webStreaming bool - // chunkSize how much bytes a chunk has. 64KB is default value. - chunkSize int64 - // chunkNumber the number of chunks in a http upload request. 1 is default value - chunkNumber int - - // shardUploadedSize how much bytes a shard has. it is original size - shardUploadedSize int64 - // shardUploadedThumbnailSize how much thumbnail bytes a shard has. it is original size - shardUploadedThumbnailSize int64 - // size of shard - shardSize int64 - - // statusCallback trigger progress on StatusCallback - statusCallback StatusCallback - - blobbers []*ChunkedUploadBlobber - - writeMarkerMutex *WriteMarkerMutex - - // isRepair identifies if upload is repair operation - isRepair bool - - opCode int - uploadTimeOut time.Duration - commitTimeOut time.Duration - maskMu *sync.Mutex - ctx context.Context - ctxCncl context.CancelFunc - addConsensus int32 - encryptedKeyPoint string - encryptedKey string } // progressID build local progress id with [allocationid]_[Hash(LocalPath+"_"+RemotePath)]_[RemoteName] format @@ -445,6 +381,8 @@ func (su *ChunkedUpload) process() error { su.statusCallback.Started(su.allocationObj.ID, su.fileMeta.RemotePath, su.opCode, int(su.fileMeta.ActualSize)+int(su.fileMeta.ActualThumbnailSize)) } alreadyUploadedData := 0 + defer close(su.uploadChan) + defer su.ctxCncl(nil) for { chunks, err := su.readChunks(su.chunkNumber) @@ -538,13 +476,15 @@ func (su *ChunkedUpload) process() error { // Start start/resume upload func (su *ChunkedUpload) Start() error { - - defer su.ctxCncl() + now := time.Now() err := su.process() if err != nil { return err } + su.ctx, su.ctxCncl = context.WithCancelCause(su.allocationObj.ctx) + defer su.ctxCncl(nil) + elapsedProcess := time.Since(now) logger.Logger.Info("Completed the upload. Submitting for commit") blobbers := make([]*blockchain.StorageNode, len(su.blobbers)) @@ -566,15 +506,23 @@ func (su *ChunkedUpload) Start() error { } return err } + elapsedLock := time.Since(now) - elapsedProcess defer su.writeMarkerMutex.Unlock( su.ctx, su.uploadMask, blobbers, su.uploadTimeOut, su.progress.ConnectionID) //nolint: errcheck + defer func() { + elapsedProcessCommit := time.Since(now) - elapsedProcess - elapsedLock + logger.Logger.Info("[ChunkedUpload - start] Timings:\n", + fmt.Sprintf("allocation_id: %s", su.allocationObj.ID), + fmt.Sprintf("process: %d ms", elapsedProcess.Milliseconds()), + fmt.Sprintf("Lock: %d ms", elapsedLock.Milliseconds()), + fmt.Sprintf("processCommit: %d ms", elapsedProcessCommit.Milliseconds())) + }() return su.processCommit() } func (su *ChunkedUpload) readChunks(num int) (*batchChunksData, error) { - data := &batchChunksData{ chunkStartIndex: -1, chunkEndIndex: -1, @@ -624,7 +572,6 @@ func (su *ChunkedUpload) readChunks(num int) (*batchChunksData, error) { break } } - return data, nil } @@ -632,14 +579,17 @@ func (su *ChunkedUpload) readChunks(num int) (*batchChunksData, error) { func (su *ChunkedUpload) processUpload(chunkStartIndex, chunkEndIndex int, fileShards []blobberShards, thumbnailShards blobberShards, isFinal bool, uploadLength int64) error { - su.consensus.Reset() - - ctx, cancel := context.WithCancel(context.TODO()) - defer cancel() var errCount int32 + blobberUpload := UploadData{ + chunkStartIndex: chunkStartIndex, + chunkEndIndex: chunkEndIndex, + isFinal: isFinal, + encryptedKey: su.encryptedKey, + uploadBody: make([]blobberData, len(su.blobbers)), + } + wgErrors := make(chan error, len(su.blobbers)) - wgDone := make(chan bool) if len(fileShards) == 0 { return thrown.New("upload_failed", "Upload failed. No data to upload") } @@ -670,51 +620,35 @@ func (su *ChunkedUpload) processUpload(chunkStartIndex, chunkEndIndex int, } return } - - err = b.sendUploadRequest(ctx, su, chunkEndIndex, isFinal, su.encryptedKey, body, formData, pos) - if err != nil { - if strings.Contains(err.Error(), "duplicate") { - su.consensus.Done() - errC := atomic.AddInt32(&su.addConsensus, 1) - if errC >= int32(su.consensus.consensusThresh) { - wgErrors <- err - } - return - } - logger.Logger.Error("error during sendUploadRequest", err) - errC := atomic.AddInt32(&errCount, 1) - if errC > int32(su.allocationObj.ParityShards-1) { // If atleast data shards + 1 number of blobbers can process the upload, it can be repaired later - wgErrors <- err - } - + blobberUpload.uploadBody[pos] = blobberData{ + body: body, + formData: formData, } }(blobber, thumbnailChunkData, pos) } - go func() { - wg.Wait() - close(wgDone) - close(wgErrors) - }() - - if su.addConsensus >= int32(su.consensus.consensusThresh) { - su.removeProgress() - return thrown.New("upload_failed", "Duplicate upload for path "+su.fileMeta.RemotePath) - } + wg.Wait() + close(wgErrors) - select { - case <-wgDone: - break - case err := <-wgErrors: + for err := range wgErrors { su.removeProgress() return thrown.New("upload_failed", fmt.Sprintf("Upload failed. %s", err)) } - if !su.consensus.isConsensusOk() { - return thrown.New("consensus_not_met", fmt.Sprintf("Upload failed File not found for path %s. Required consensus atleast %d, got %d", - su.fileMeta.RemotePath, su.consensus.consensusThresh, su.consensus.getConsensus())) + select { + case <-su.ctx.Done(): + return context.Cause(su.ctx) + default: + } + su.uploadChan <- blobberUpload + if isFinal { + su.uploadWG.Wait() + select { + case <-su.ctx.Done(): + return context.Cause(su.ctx) + default: + } } - return nil } @@ -793,3 +727,63 @@ func getShardSize(dataSize int64, dataShards int, isEncrypted bool) int64 { } return n*DefaultChunkSize + remainderShards } + +func (su *ChunkedUpload) uploadProcessor() { + defer su.uploadWG.Done() + for { + select { + case <-su.ctx.Done(): + return + case uploadData, ok := <-su.uploadChan: + if !ok { + return + } + wgErrors := make(chan error, len(su.blobbers)) + wg := &sync.WaitGroup{} + ctx, cancel := context.WithCancel(context.TODO()) + defer cancel() + su.consensus.Reset() + var pos uint64 + var errCount int32 + for i := su.uploadMask; !i.Equals64(0); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) { + pos = uint64(i.TrailingZeros()) + wg.Add(1) + go func(pos uint64) { + defer wg.Done() + err := su.blobbers[pos].sendUploadRequest(ctx, su, uploadData.chunkEndIndex, uploadData.isFinal, su.encryptedKey, uploadData.uploadBody[pos].body, uploadData.uploadBody[pos].formData, pos) + + if err != nil { + if strings.Contains(err.Error(), "duplicate") { + su.consensus.Done() + errC := atomic.AddInt32(&su.addConsensus, 1) + if errC >= int32(su.consensus.consensusThresh) { + wgErrors <- err + } + return + } + logger.Logger.Error("error during sendUploadRequest", err) + errC := atomic.AddInt32(&errCount, 1) + if errC > int32(su.allocationObj.ParityShards-1) { // If atleast data shards + 1 number of blobbers can process the upload, it can be repaired later + wgErrors <- err + } + } + }(pos) + } + wg.Wait() + close(wgErrors) + for err := range wgErrors { + su.removeProgress() + su.ctxCncl(thrown.New("upload_failed", fmt.Sprintf("Upload failed. %s", err))) + return + } + if !su.consensus.isConsensusOk() { + su.ctxCncl(thrown.New("consensus_not_met", fmt.Sprintf("Upload failed File not found for path %s. Required consensus atleast %d, got %d", + su.fileMeta.RemotePath, su.consensus.consensusThresh, su.consensus.getConsensus()))) + return + } + if uploadData.isFinal { + return + } + } + } +} diff --git a/zboxcore/sdk/chunked_upload_chunk_reader.go b/zboxcore/sdk/chunked_upload_chunk_reader.go index d3daed0e5..0642397b3 100644 --- a/zboxcore/sdk/chunked_upload_chunk_reader.go +++ b/zboxcore/sdk/chunked_upload_chunk_reader.go @@ -157,7 +157,6 @@ func (r *chunkedUploadChunkReader) Next() (*ChunkData, error) { } chunk.FragmentSize = int64(math.Ceil(float64(readLen)/float64(r.dataShards))) + r.chunkHeaderSize - if readLen < int(r.chunkDataSizePerRead) { chunkBytes = chunkBytes[:readLen] chunk.IsFinal = true @@ -175,7 +174,6 @@ func (r *chunkedUploadChunkReader) Next() (*ChunkData, error) { if err != nil { return chunk, err } - fragments, err := r.erasureEncoder.Split(chunkBytes) if err != nil { return nil, err @@ -185,7 +183,6 @@ func (r *chunkedUploadChunkReader) Next() (*ChunkData, error) { if err != nil { return nil, err } - var pos uint64 if r.encryptOnUpload { for i := r.uploadMask; !i.Equals64(0); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) { diff --git a/zboxcore/sdk/chunked_upload_form_builder.go b/zboxcore/sdk/chunked_upload_form_builder.go index dfb1aa69f..0d2e6952f 100644 --- a/zboxcore/sdk/chunked_upload_form_builder.go +++ b/zboxcore/sdk/chunked_upload_form_builder.go @@ -7,10 +7,8 @@ import ( "io" "mime/multipart" "sync" - "time" "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/logger" "golang.org/x/crypto/sha3" ) @@ -90,7 +88,6 @@ func (b *chunkedUploadFormBuilder) Build( if err != nil { return nil, metadata, err } - for _, chunkBytes := range fileChunksData { _, err = uploadFile.Write(chunkBytes) if err != nil { @@ -109,7 +106,7 @@ func (b *chunkedUploadFormBuilder) Build( metadata.FileBytesLen += len(chunkBytes) } - start := time.Now() + if isFinal { err = hasher.Finalize() if err != nil { @@ -140,7 +137,6 @@ func (b *chunkedUploadFormBuilder) Build( for err := range errChan { return nil, metadata, err } - logger.Logger.Info("[hasherTime]", time.Since(start).Milliseconds()) actualHashSignature, err := client.Sign(fileMeta.ActualHash) if err != nil { return nil, metadata, err @@ -200,6 +196,5 @@ func (b *chunkedUploadFormBuilder) Build( metadata.FixedMerkleRoot = formData.FixedMerkleRoot metadata.ValidationRoot = formData.ValidationRoot metadata.ThumbnailContentHash = formData.ThumbnailContentHash - return body, metadata, nil } diff --git a/zboxcore/sdk/chunked_upload_model.go b/zboxcore/sdk/chunked_upload_model.go index 773d43f7e..21e11ae44 100644 --- a/zboxcore/sdk/chunked_upload_model.go +++ b/zboxcore/sdk/chunked_upload_model.go @@ -1,13 +1,94 @@ package sdk import ( + "bytes" + "context" "encoding/json" "hash/fnv" + "io" "strconv" - + "sync" + "time" + + "github.com/0chain/gosdk/core/common" + "github.com/0chain/gosdk/zboxcore/allocationchange" + "github.com/0chain/gosdk/zboxcore/encryption" + "github.com/0chain/gosdk/zboxcore/fileref" + "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/google/uuid" + "github.com/klauspost/reedsolomon" "golang.org/x/crypto/sha3" ) +// ChunkedUpload upload manager with chunked upload feature +type ChunkedUpload struct { + consensus Consensus + + workdir string + + allocationObj *Allocation + progress UploadProgress + progressStorer ChunkedUploadProgressStorer + client zboxutil.HttpClient + + uploadMask zboxutil.Uint128 + + // httpMethod POST = Upload File / PUT = Update file + httpMethod string + buildChange func(ref *fileref.FileRef, + uid uuid.UUID, timestamp common.Timestamp) allocationchange.AllocationChange + + fileMeta FileMeta + fileReader io.Reader + fileErasureEncoder reedsolomon.Encoder + fileEncscheme encryption.EncryptionScheme + fileHasher Hasher + + thumbnailBytes []byte + thumbailErasureEncoder reedsolomon.Encoder + + chunkReader ChunkedUploadChunkReader + formBuilder ChunkedUploadFormBuilder + + // encryptOnUpload encrypt data on upload or not. + encryptOnUpload bool + // webStreaming whether data has to be encoded. + webStreaming bool + // chunkSize how much bytes a chunk has. 64KB is default value. + chunkSize int64 + // chunkNumber the number of chunks in a http upload request. 1 is default value + chunkNumber int + + // shardUploadedSize how much bytes a shard has. it is original size + shardUploadedSize int64 + // shardUploadedThumbnailSize how much thumbnail bytes a shard has. it is original size + shardUploadedThumbnailSize int64 + // size of shard + shardSize int64 + + // statusCallback trigger progress on StatusCallback + statusCallback StatusCallback + + blobbers []*ChunkedUploadBlobber + + writeMarkerMutex *WriteMarkerMutex + + // isRepair identifies if upload is repair operation + isRepair bool + + opCode int + uploadTimeOut time.Duration + commitTimeOut time.Duration + maskMu *sync.Mutex + ctx context.Context + ctxCncl context.CancelCauseFunc + addConsensus int32 + encryptedKeyPoint string + encryptedKey string + uploadChan chan UploadData + uploadWG sync.WaitGroup +} + // FileMeta metadata of stream input/local type FileMeta struct { // Mimetype mime type of source file @@ -113,6 +194,21 @@ type UploadBlobberStatus struct { UploadLength int64 `json:"upload_length,omitempty"` } +// err = b.sendUploadRequest(ctx, su, chunkEndIndex, isFinal, su.encryptedKey, body, formData, pos) + +type UploadData struct { + chunkStartIndex int + chunkEndIndex int + isFinal bool + encryptedKey string + uploadBody []blobberData +} + +type blobberData struct { + body *bytes.Buffer + formData ChunkedUploadFormMetadata +} + type status struct { Hasher hasher UploadLength int64 `json:"upload_length,omitempty"` diff --git a/zboxcore/sdk/commitworker.go b/zboxcore/sdk/commitworker.go index 81dab2470..634eb4aaa 100644 --- a/zboxcore/sdk/commitworker.go +++ b/zboxcore/sdk/commitworker.go @@ -92,7 +92,7 @@ func startCommitWorker(blobberChan chan *CommitRequest, blobberID string) { func (commitreq *CommitRequest) processCommit() { defer commitreq.wg.Done() - + start := time.Now() l.Logger.Info("received a commit request") paths := make([]string, 0) for _, change := range commitreq.changes { @@ -187,6 +187,7 @@ func (commitreq *CommitRequest) processCommit() { commitreq.result = ErrorCommitResult(err.Error()) return } + l.Logger.Info("[commitBlobber]", time.Since(start).Milliseconds()) commitreq.result = SuccessCommitResult() } diff --git a/zboxcore/sdk/downloadworker.go b/zboxcore/sdk/downloadworker.go index 4359d46a2..05a39254d 100644 --- a/zboxcore/sdk/downloadworker.go +++ b/zboxcore/sdk/downloadworker.go @@ -375,6 +375,7 @@ func (req *DownloadRequest) processDownload(ctx context.Context) { "Blocks per blobber: %d", size, req.startBlock, req.endBlock, blocksPerShard), ) + now := time.Now() err := req.initEC() if err != nil { logger.Logger.Error(err) @@ -383,6 +384,7 @@ func (req *DownloadRequest) processDownload(ctx context.Context) { err), remotePathCB) return } + elapsedInitEC := time.Since(now) if req.encryptedKey != "" { err = req.initEncryption() if err != nil { @@ -392,6 +394,7 @@ func (req *DownloadRequest) processDownload(ctx context.Context) { return } } + elapsedInitEncryption := time.Since(now) - elapsedInitEC var downloaded int startBlock, endBlock, numBlocks := req.startBlock, req.endBlock, req.numBlocks @@ -527,6 +530,14 @@ func (req *DownloadRequest) processDownload(ctx context.Context) { close(blocks) wg.Wait() + elapsedGetBlocksAndWrite := time.Since(now) - elapsedInitEC - elapsedInitEncryption + l.Logger.Info(fmt.Sprintf("[processDownload] Timings:\n allocation_id: %s,\n remotefilepath: %s,\n initEC: %d ms,\n initEncryption: %d ms,\n getBlocks and writes: %d ms", + req.allocationID, + req.remotefilepath, + elapsedInitEC.Milliseconds(), + elapsedInitEncryption.Milliseconds(), + elapsedGetBlocksAndWrite.Milliseconds(), + )) if req.statusCallback != nil { req.statusCallback.Completed( diff --git a/zboxcore/sdk/multi_operation_worker.go b/zboxcore/sdk/multi_operation_worker.go index f9ef35d61..5d38664d4 100644 --- a/zboxcore/sdk/multi_operation_worker.go +++ b/zboxcore/sdk/multi_operation_worker.go @@ -200,6 +200,7 @@ func (mo *MultiOperation) Process() error { // in row instead of column. Currently mo.change[0] contains allocationChange for operation 1 and so on. // But we want mo.changes[0] to have allocationChange for blobber 1 and mo.changes[1] to have allocationChange for // blobber 2 and so on. + start := time.Now() mo.changes = zboxutil.Transpose(mo.changes) writeMarkerMutex, err := CreateWriteMarkerMutex(client.GetClient(), mo.allocationObj) @@ -213,8 +214,8 @@ func (mo *MultiOperation) Process() error { if err != nil { return fmt.Errorf("Operation failed: %s", err.Error()) } - l.Logger.Info("WriteMarker locked") - + logger.Logger.Info("[writemarkerLocked]", time.Since(start).Milliseconds()) + start = time.Now() status, err := mo.allocationObj.CheckAllocStatus() if err != nil { logger.Logger.Error("Error checking allocation status", err) @@ -245,11 +246,11 @@ func (mo *MultiOperation) Process() error { if status != Commit { return ErrRetryOperation } - + logger.Logger.Info("[checkAllocStatus]", time.Since(start).Milliseconds()) mo.Consensus.Reset() activeBlobbers := mo.operationMask.CountOnes() commitReqs := make([]*CommitRequest, activeBlobbers) - + start = time.Now() wg.Add(activeBlobbers) var pos uint64 var counter = 0 @@ -273,6 +274,7 @@ func (mo *MultiOperation) Process() error { counter++ } wg.Wait() + logger.Logger.Info("[commitRequests]", time.Since(start).Milliseconds()) rollbackMask := zboxutil.NewUint128(0) for _, commitReq := range commitReqs { if commitReq.result != nil { diff --git a/zboxcore/sdk/upload_worker.go b/zboxcore/sdk/upload_worker.go index bb062e719..3aab0b32b 100644 --- a/zboxcore/sdk/upload_worker.go +++ b/zboxcore/sdk/upload_worker.go @@ -7,7 +7,6 @@ import ( "github.com/0chain/gosdk/constants" "github.com/0chain/gosdk/zboxcore/allocationchange" "github.com/0chain/gosdk/zboxcore/fileref" - l "github.com/0chain/gosdk/zboxcore/logger" "github.com/0chain/gosdk/zboxcore/zboxutil" "github.com/google/uuid" ) @@ -22,7 +21,6 @@ type UploadOperation struct { func (uo *UploadOperation) Process(allocObj *Allocation, connectionID string) ([]fileref.RefEntity, zboxutil.Uint128, error) { err := uo.chunkedUpload.process() if err != nil { - uo.chunkedUpload.ctxCncl() return nil, uo.chunkedUpload.uploadMask, err } @@ -35,7 +33,6 @@ func (uo *UploadOperation) Process(allocObj *Allocation, connectionID string) ([ uo.refs[pos].ChunkSize = uo.chunkedUpload.chunkSize } - l.Logger.Info("Completed the upload") return nil, uo.chunkedUpload.uploadMask, nil } @@ -119,7 +116,6 @@ func (uo *UploadOperation) Error(allocObj *Allocation, consensus int, err error) func NewUploadOperation(workdir string, allocObj *Allocation, connectionID string, fileMeta FileMeta, fileReader io.Reader, isUpdate, isWebstreaming bool, opts ...ChunkedUploadOption) (*UploadOperation, string, error) { uo := &UploadOperation{} - cu, err := CreateChunkedUpload(workdir, allocObj, fileMeta, fileReader, isUpdate, false, isWebstreaming, connectionID, opts...) if err != nil { return nil, "", err @@ -128,6 +124,5 @@ func NewUploadOperation(workdir string, allocObj *Allocation, connectionID strin uo.chunkedUpload = cu uo.opCode = cu.opCode uo.isUpdate = isUpdate - return uo, cu.progress.ConnectionID, nil } From 684e1aa8054cf1ceba350e7c4dd984e3e0f3cccd Mon Sep 17 00:00:00 2001 From: Manohar Reddy Date: Sun, 24 Sep 2023 23:14:51 +0200 Subject: [PATCH 043/134] Wasm for `move`, `rename`, `copy` (#1233) * add demo for move, rename and copy * remove debug logs --------- Co-authored-by: Yury --- wasmsdk/demo/index.html | 29 ++++++++++++++++----- zboxcore/sdk/chunked_upload.go | 2 -- zboxcore/sdk/chunked_upload_blobber.go | 2 -- zboxcore/sdk/chunked_upload_form_builder.go | 2 +- 4 files changed, 24 insertions(+), 11 deletions(-) diff --git a/wasmsdk/demo/index.html b/wasmsdk/demo/index.html index 2a8cafa62..80d30d7cc 100644 --- a/wasmsdk/demo/index.html +++ b/wasmsdk/demo/index.html @@ -457,7 +457,7 @@

please download zcn.wasm from https://github.com/0chain/gosdk/releases/lates } }) } - const results = await goWasm.multiUpload(objects) + const results = await goWasm.bulkUpload(objects) console.log(JSON.stringify(results)) } }) @@ -810,16 +810,33 @@

please download zcn.wasm from https://github.com/0chain/gosdk/releases/lates } const objects = [] - objects.push({ + objects.push( + { // rename file operationType: `move`, - remotePath: `/zcn.wasm`, - destPath: `/folder1`, - }) + remotePath: `/small2-182b.txt`, + destPath: `/folder/small-182b.txt`, + }, + { // todo: rename folder + operationType: `move`, + remotePath: `/folder`, + destPath: `/folder2`, + }, + { // move a file to an other folder + operationType: `move`, + remotePath: `/small-182b.txt`, + destPath: `/folder/`, + }, + { // copy a file to an other folder + operationType: `copy`, + remotePath: `/small2-182b.txt`, + destPath: `/folder/`, + }, + ) let stringifiedArray = JSON.stringify(objects); try { - console.log("execting", objects[0]) + console.log("executing MultiOps", objects[0]) const output = await goWasm.sdk.multiOperation(allocationId, stringifiedArray) } catch (e) { alert(e) diff --git a/zboxcore/sdk/chunked_upload.go b/zboxcore/sdk/chunked_upload.go index 03bb39add..e093e5b4d 100644 --- a/zboxcore/sdk/chunked_upload.go +++ b/zboxcore/sdk/chunked_upload.go @@ -420,7 +420,6 @@ func (su *ChunkedUpload) process() error { //chunk has not be uploaded yet if chunks.chunkEndIndex > su.progress.ChunkIndex { - start := time.Now() err = su.processUpload( chunks.chunkStartIndex, chunks.chunkEndIndex, chunks.fileShards, chunks.thumbnailShards, @@ -432,7 +431,6 @@ func (su *ChunkedUpload) process() error { } return err } - logger.Logger.Info("[processUpload]", time.Since(start).Milliseconds()) } else { // Write data to hashers for i, blobberShard := range chunks.fileShards { diff --git a/zboxcore/sdk/chunked_upload_blobber.go b/zboxcore/sdk/chunked_upload_blobber.go index b03b03200..4e3662a89 100644 --- a/zboxcore/sdk/chunked_upload_blobber.go +++ b/zboxcore/sdk/chunked_upload_blobber.go @@ -84,14 +84,12 @@ func (sb *ChunkedUploadBlobber) sendUploadRequest( for i := 0; i < 3; i++ { err, shouldContinue = func() (err error, shouldContinue bool) { reqCtx, ctxCncl := context.WithTimeout(ctx, su.uploadTimeOut) - start := time.Now() var resp *http.Response err = zboxutil.HttpDo(reqCtx, ctxCncl, req, func(r *http.Response, err error) error { resp = r return err }) defer ctxCncl() - logger.Logger.Info("[sendUploadRequestBlobber] ", time.Since(start).Milliseconds()) if err != nil { logger.Logger.Error("Upload : ", err) diff --git a/zboxcore/sdk/chunked_upload_form_builder.go b/zboxcore/sdk/chunked_upload_form_builder.go index 0d2e6952f..f0637fa7b 100644 --- a/zboxcore/sdk/chunked_upload_form_builder.go +++ b/zboxcore/sdk/chunked_upload_form_builder.go @@ -106,7 +106,7 @@ func (b *chunkedUploadFormBuilder) Build( metadata.FileBytesLen += len(chunkBytes) } - + if isFinal { err = hasher.Finalize() if err != nil { From 0ffbf8a8887887a3fa1126f9dc3e53a7a09d6a73 Mon Sep 17 00:00:00 2001 From: Lz Date: Mon, 25 Sep 2023 17:34:07 +0800 Subject: [PATCH 044/134] Feat/streaming server in winsdk (#1228) --- winsdk/cache.go | 37 ++++++ winsdk/status.go | 13 ++- winsdk/storage.go | 5 + winsdk/stream.go | 252 ++++++++++++++++++++++++++++++++++++++++ winsdk/stream_models.go | 101 ++++++++++++++++ 5 files changed, 405 insertions(+), 3 deletions(-) create mode 100644 winsdk/stream.go create mode 100644 winsdk/stream_models.go diff --git a/winsdk/cache.go b/winsdk/cache.go index 63efccde4..493868e98 100644 --- a/winsdk/cache.go +++ b/winsdk/cache.go @@ -12,8 +12,14 @@ type cachedAllocation struct { Allocation *sdk.Allocation } +type cachedFileMeta struct { + CacheExpiresAt time.Time + FileMeta *sdk.ConsolidatedFileMeta +} + var ( cachedAllocations, _ = lru.New[string, *cachedAllocation](100) + cachedFileMetas, _ = lru.New[string, *cachedFileMeta](1000) ) func getAllocation(allocationID string) (*sdk.Allocation, error) { @@ -41,3 +47,34 @@ func getAllocation(allocationID string) (*sdk.Allocation, error) { return it.Allocation, nil } + +func getFileMeta(allocationID, remotePath string) (*sdk.ConsolidatedFileMeta, error) { + + var it *cachedFileMeta + var ok bool + + it, ok = cachedFileMetas.Get(allocationID + ":" + remotePath) + + if ok && it.CacheExpiresAt.After(time.Now()) { + return it.FileMeta, nil + } + + a, err := getAllocation(allocationID) + if err != nil { + return nil, err + } + + f, err := a.GetFileMeta(remotePath) + if err != nil { + return nil, err + } + + it = &cachedFileMeta{ + FileMeta: f, + CacheExpiresAt: time.Now().Add(5 * time.Minute), + } + + cachedFileMetas.Add(allocationID, it) + + return it.FileMeta, nil +} diff --git a/winsdk/status.go b/winsdk/status.go index c1d0caa69..a5d5845d1 100644 --- a/winsdk/status.go +++ b/winsdk/status.go @@ -1,7 +1,8 @@ package main import ( - "github.com/0chain/gosdk/zboxcore/sdk" + "sync" + lru "github.com/hashicorp/golang-lru/v2" ) @@ -17,6 +18,7 @@ type Status struct { Error string Completed bool LookupHash string + wg sync.WaitGroup } type StatusCallback struct { @@ -24,11 +26,13 @@ type StatusCallback struct { items *lru.Cache[string, *Status] } -func NewStatusBar(items *lru.Cache[string, *Status], key string) sdk.StatusCallback { - return &StatusCallback{ +func NewStatusBar(items *lru.Cache[string, *Status], key string) *StatusCallback { + sc := &StatusCallback{ key: key, items: items, } + + return sc } func (c *StatusCallback) getStatus(lookupHash string) *Status { @@ -69,6 +73,7 @@ func (c *StatusCallback) InProgress(allocationID, remotePath string, op int, com s.LookupHash = lookupHash if completedBytes >= s.TotalBytes { s.Completed = true + s.wg.Done() } } @@ -78,6 +83,7 @@ func (c *StatusCallback) Error(allocationID string, remotePath string, op int, e s := c.getStatus(lookupHash) s.Error = err.Error() s.LookupHash = lookupHash + s.wg.Done() } func (c *StatusCallback) Completed(allocationID, remotePath string, filename string, mimetype string, size int, op int) { @@ -87,6 +93,7 @@ func (c *StatusCallback) Completed(allocationID, remotePath string, filename str s.Completed = true s.LookupHash = lookupHash s.CompletedBytes = s.TotalBytes + s.wg.Done() } func (c *StatusCallback) CommitMetaCompleted(request, response string, err error) { diff --git a/winsdk/storage.go b/winsdk/storage.go index 493f3d02b..e80de99f4 100644 --- a/winsdk/storage.go +++ b/winsdk/storage.go @@ -329,6 +329,11 @@ func DownloadFile(allocationID, localPath, remotePath *C.char, verifyDownload, i // //export DownloadThumbnail func DownloadThumbnail(allocationID, localPath, remotePath *C.char, verifyDownload bool, isFinal bool) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: DownloadThumbnail ", r) + } + }() allocID := C.GoString(allocationID) alloc, err := getAllocation(allocID) diff --git a/winsdk/stream.go b/winsdk/stream.go new file mode 100644 index 000000000..d4c5b2000 --- /dev/null +++ b/winsdk/stream.go @@ -0,0 +1,252 @@ +package main + +/* +#include +*/ +import ( + "C" +) + +import ( + "fmt" + "math" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "strings" + + "github.com/0chain/gosdk/zboxcore/sdk" + lru "github.com/hashicorp/golang-lru/v2" +) + +var ( + numBlocks int = 100 + sizePerRequest int64 = sdk.CHUNK_SIZE * int64(numBlocks) // 6400K 100 blocks + server *httptest.Server + streamAllocationID string + cachedDownloadedBlocks, _ = lru.New[string, []byte](1000) +) + +// StartStreamServer - start local media stream server +// ## Inputs +// - allocationID +// +// ## Outputs +// +// { +// "error":"", +// "result":"http://127.0.0.1:4313/", +// } +// +//export StartStreamServer +func StartStreamServer(allocationID *C.char) *C.char { + allocID := C.GoString(allocationID) + + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + streamingMedia(w, r) + }) + + if server != nil { + server.Close() + } + + server = httptest.NewServer(handler) + streamAllocationID = allocID + log.Info("win: ", server.URL) + return WithJSON(server.URL, nil) +} + +func streamingMedia(w http.ResponseWriter, req *http.Request) { + + remotePath := req.URL.Path + log.Info("win: start streaming media: ", streamAllocationID, remotePath) + + f, err := getFileMeta(streamAllocationID, remotePath) + if err != nil { + http.Error(w, err.Error(), 500) + return + } + + w.Header().Set("Content-Type", f.MimeType) + + rangeHeader := req.Header.Get("Range") + + log.Info("win: range: ", rangeHeader, " mimetype: ", f.MimeType, " numBlocks:", f.NumBlocks, " ActualNumBlocks:", f.ActualNumBlocks, " ActualFileSize:", f.ActualFileSize) + // we can simply hint Chrome to send serial range requests for media file by + // + // if rangeHeader == "" { + // w.Header().Set("Accept-Ranges", "bytes") + // w.Header().Set("Content-Length", strconv.FormatInt(size, 10)) + // w.WriteHeader(200) + // fmt.Printf("hint browser to send range requests, total size: %d\n", size) + // return + // } + // + // but this not worked for Safari and Firefox + if rangeHeader == "" { + ra := httpRange{ + start: 0, + length: sizePerRequest, + total: f.ActualFileSize, + } + w.Header().Set("Accept-Ranges", "bytes") + + w.Header().Set("Content-Range", ra.Header()) + + w.WriteHeader(http.StatusPartialContent) + + if req.Method != "HEAD" { + buf, err := downloadBlocks(remotePath, f, ra) + if err != nil { + http.Error(w, err.Error(), 500) + } + + written, err := w.Write(buf) + + if err != nil { + http.Error(w, err.Error(), 500) + } + + w.Header().Set("Content-Length", strconv.Itoa(written)) + + for k, v := range w.Header() { + log.Info("win: response ", k, " = ", v[0]) + } + + } else { + w.Header().Set("Content-Length", "0") + } + return + } + + ranges, err := parseRange(rangeHeader, f.ActualFileSize) + if err != nil { + http.Error(w, err.Error(), 400) + return + } + + // multi-part requests are not supported + if len(ranges) > 1 { + http.Error(w, "unsupported multi-part", http.StatusRequestedRangeNotSatisfiable) + return + } + + ra := ranges[0] + + w.Header().Set("Accept-Ranges", "bytes") + w.Header().Set("Content-Range", ra.Header()) + + w.WriteHeader(http.StatusPartialContent) + + if req.Method != "HEAD" { + + buf, err := downloadBlocks(remotePath, f, ra) + + if err != nil { + http.Error(w, err.Error(), 500) + } + + written, err := w.Write(buf) + if err != nil { + http.Error(w, err.Error(), 500) + } + w.Header().Set("Content-Length", strconv.Itoa(written)) + + for k, v := range w.Header() { + log.Info("win: response ", k, " = ", v[0]) + } + } else { + w.Header().Set("Content-Length", "0") + } +} + +func downloadBlocks(remotePath string, f *sdk.ConsolidatedFileMeta, ra httpRange) ([]byte, error) { + defer func() { + if r := recover(); r != nil { + log.Error("win: ", r) + } + }() + alloc, err := getAllocation(streamAllocationID) + + if err != nil { + return nil, err + } + var startBlock int64 + + if ra.start == 0 { + startBlock = 1 + } else { + startBlock = int64(math.Floor(float64(ra.start)/float64(sdk.CHUNK_SIZE)/float64(alloc.DataShards))) + 1 + } + + if startBlock > f.NumBlocks { + startBlock = f.NumBlocks + } + + blocks := int(math.Ceil(float64(ra.length) / float64(sdk.CHUNK_SIZE) / float64(alloc.DataShards))) + + endBlock := startBlock + int64(blocks) + + if endBlock > f.NumBlocks { + endBlock = f.NumBlocks + } + + if startBlock == endBlock { + endBlock = 0 + } + + offset := 0 + blockStart := (startBlock - 1) * sdk.CHUNK_SIZE * int64(alloc.DataShards) + if ra.start > blockStart { + offset = int(ra.start) - int(blockStart) + } + + lookupHash := getLookupHash(streamAllocationID, remotePath) + key := lookupHash + fmt.Sprintf(":%v-%v", startBlock, endBlock) + log.Info("win: start download blocks ", startBlock, " - ", endBlock, "/", f.NumBlocks, "(", f.ActualNumBlocks, ") for ", remotePath) + buf, ok := cachedDownloadedBlocks.Get(key) + if ok { + return buf, nil + } + + mf := filepath.Join(os.TempDir(), strings.ReplaceAll(remotePath, "/", "_")+fmt.Sprintf("_%v_%v", startBlock, endBlock)) + defer os.Remove(mf) + + // _, err = os.Stat(mf) + + // if os.IsNotExist(err) { + statusBar := NewStatusBar(statusDownload, key) + status := statusBar.getStatus(key) + status.wg.Add(1) + log.Info("win: download blocks to ", mf) + err = alloc.DownloadFileByBlock(mf, remotePath, startBlock, endBlock, numBlocks, false, statusBar, true) + //err = alloc.DownloadFile(mf, remotePath, true, statusBar, true) + if err != nil { + return nil, err + } + + log.Info("win: waiting for download to done") + status.wg.Wait() + // } + + buf, err = os.ReadFile(mf) + if err != nil { + return nil, err + } + + log.Info("win: downloaded blocks ", len(buf), " start:", ra.start, " blockStart:", blockStart, " offset:", offset, " len:", ra.length) + if len(buf) > 0 { + if len(buf) > int(ra.length) { + b := buf[offset : offset+int(ra.length)] + cachedDownloadedBlocks.Add(key, b) + return b, nil + } + cachedDownloadedBlocks.Add(key, buf) + return buf[offset:], nil + } + + // os.Remove(mf) + return nil, nil +} diff --git a/winsdk/stream_models.go b/winsdk/stream_models.go new file mode 100644 index 000000000..96f0a7874 --- /dev/null +++ b/winsdk/stream_models.go @@ -0,0 +1,101 @@ +package main + +import ( + "errors" + "fmt" + "net/textproto" + "strconv" + "strings" +) + +var errNoOverlap = errors.New("invalid range: failed to overlap") + +type httpRange struct { + start, length, total int64 +} + +func (r httpRange) Header() string { + return fmt.Sprintf("bytes %d-%d/%d", r.start, r.start+r.length-1, r.total) +} + +// parseRange parses a Range header string as per RFC 7233. +// errNoOverlap is returned if none of the ranges overlap. +// +// Examples of valid byte ranges (assuming a resource of length 10240): +// bytes=0-499, the first 500 bytes +// bytes=1000-1999, 1000 bytes start from offset 1000 +// bytes=-500, the final 500 bytes (byte offsets 9739-10239, inclusive) +// bytes=0-0,-1, the first and last bytes only +// bytes=0-, bytes=0-10250, be interpreted as bytes=0-10239 +func parseRange(s string, total int64) ([]httpRange, error) { + if s == "" { + return nil, nil // header not present + } + const b = "bytes=" + if !strings.HasPrefix(s, b) { + return nil, errors.New("invalid range") + } + var ranges []httpRange + noOverlap := false + for _, ra := range strings.Split(s[len(b):], ",") { + ra = textproto.TrimString(ra) + if ra == "" { + continue + } + start, end, ok := strings.Cut(ra, "-") + if !ok { + return nil, errors.New("invalid range") + } + start, end = textproto.TrimString(start), textproto.TrimString(end) + var r httpRange + if start == "" { + if end == "" || end[0] == '-' { + return nil, errors.New("invalid range") + } + i, err := strconv.ParseInt(end, 10, 64) + if i < 0 || err != nil { + return nil, errors.New("invalid range") + } + if i > total { + i = total + } + r.start = total - i + r.length = total - r.start + } else { + i, err := strconv.ParseInt(start, 10, 64) + if err != nil || i < 0 { + return nil, errors.New("invalid range") + } + if i >= total { + // If the range begins after the size of the content, + // then it does not overlap. + noOverlap = true + i = total - 1 + //continue, since server may attempt to return a largeEnoughLen, errNoOverlap never happen + } + r.start = i + if end == "" { + r.length = sizePerRequest + if r.length > total-r.start && !noOverlap { + r.length = total - r.start + } + } else { + i, err := strconv.ParseInt(end, 10, 64) + if err != nil || r.start > i { + return nil, errors.New("invalid range") + } + if i >= total { + i = total - 1 + } + r.length = i - r.start + 1 + } + } + r.total = total + ranges = append(ranges, r) + } + if noOverlap && len(ranges) == 0 { + // The specified ranges did not overlap with the content. + return nil, errNoOverlap + } + return ranges, nil +} From 49e6b13987e46d3affcb954606c1e378d9d9a04f Mon Sep 17 00:00:00 2001 From: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Date: Sun, 1 Oct 2023 00:28:18 +0530 Subject: [PATCH 045/134] fix move when srcPath is same as destPath (#1239) --- zboxcore/allocationchange/moveobject.go | 86 +++++++++++++------------ zboxcore/sdk/moveworker.go | 1 + 2 files changed, 47 insertions(+), 40 deletions(-) diff --git a/zboxcore/allocationchange/moveobject.go b/zboxcore/allocationchange/moveobject.go index a8119b760..5f7ed9b63 100644 --- a/zboxcore/allocationchange/moveobject.go +++ b/zboxcore/allocationchange/moveobject.go @@ -7,18 +7,58 @@ import ( "github.com/0chain/errors" "github.com/0chain/gosdk/core/common" "github.com/0chain/gosdk/core/pathutil" + "github.com/0chain/gosdk/core/util" "github.com/0chain/gosdk/zboxcore/fileref" + "github.com/google/uuid" ) type MoveFileChange struct { change ObjectTree fileref.RefEntity DestPath string + Uuid uuid.UUID } -func (ch *MoveFileChange) ProcessChange(rootRef *fileref.Ref, _ map[string]string) (err error) { +func (ch *MoveFileChange) ProcessChange(rootRef *fileref.Ref, fileIDMeta map[string]string) (err error) { + oldParentPath, oldFileName := pathutil.Split(ch.ObjectTree.GetPath()) + fields, err := common.GetPathFields(oldParentPath) + if err != nil { + return + } - fields, err := common.GetPathFields(ch.DestPath) + delRef := rootRef + for i := 0; i < len(fields); i++ { + found := false + for _, child := range delRef.Children { + if child.GetName() == fields[i] { + delRef = child.(*fileref.Ref) + delRef.HashToBeComputed = true + found = true + break + } + } + + if !found { + err = errors.New("invalid_reference_path", "Ref not found in root reference object") + return + } + } + + var removed bool + for i, child := range delRef.Children { + if child.GetName() == oldFileName { + delRef.RemoveChild(i) + removed = true + break + } + } + + if !removed { + err = errors.New("incomplete_move", "could not remove ref from source path") + return + } + + fields, err = common.GetPathFields(ch.DestPath) if err != nil { return } @@ -39,12 +79,16 @@ func (ch *MoveFileChange) ProcessChange(rootRef *fileref.Ref, _ map[string]strin } if !found { + uid := util.GetSHA1Uuid(ch.Uuid, fields[i]) + ch.Uuid = uid newRef := &fileref.Ref{ Type: fileref.DIRECTORY, AllocationID: dirRef.AllocationID, Path: path.Join("/", strings.Join(fields[:i+1], "/")), Name: fields[i], + FileID: uid.String(), } + fileIDMeta[newRef.Path] = newRef.FileID dirRef.AddChild(newRef) dirRef = newRef } @@ -63,49 +107,11 @@ func (ch *MoveFileChange) ProcessChange(rootRef *fileref.Ref, _ map[string]strin affectedRef = ch.ObjectTree.(*fileref.Ref) } - oldParentPath, oldFileName := pathutil.Split(ch.ObjectTree.GetPath()) affectedRef.Path = pathutil.Join(dirRef.GetPath(), affectedRef.Name) ch.processChildren(affectedRef) dirRef.AddChild(ch.ObjectTree) - fields, err = common.GetPathFields(oldParentPath) - if err != nil { - return - } - - delRef := rootRef - for i := 0; i < len(fields); i++ { - found := false - for _, child := range delRef.Children { - if child.GetName() == fields[i] { - delRef = child.(*fileref.Ref) - delRef.HashToBeComputed = true - found = true - break - } - } - - if !found { - err = errors.New("invalid_reference_path", "Ref not found in root reference object") - return - } - } - - var removed bool - for i, child := range delRef.Children { - if child.GetName() == oldFileName { - delRef.RemoveChild(i) - removed = true - break - } - } - - if !removed { - err = errors.New("incomplete_move", "could not remove ref from source path") - return - } - rootRef.CalculateHash() return } diff --git a/zboxcore/sdk/moveworker.go b/zboxcore/sdk/moveworker.go index 4487437b7..2380cd542 100644 --- a/zboxcore/sdk/moveworker.go +++ b/zboxcore/sdk/moveworker.go @@ -345,6 +345,7 @@ func (mo *MoveOperation) buildChange(refs []fileref.RefEntity, uid uuid.UUID) [] moveChange.NumBlocks = 0 moveChange.Operation = constants.FileOperationMove moveChange.Size = 0 + moveChange.Uuid = uid changes[idx] = moveChange } return changes From 86d5d017406a2de0e821038f396677fd6ef49742 Mon Sep 17 00:00:00 2001 From: Lz Date: Sun, 1 Oct 2023 04:10:47 +0800 Subject: [PATCH 046/134] fix(upload):fixed invalid ffmpeg command in transcode feature (#1236) * fix(upload):fixed invalid ffmpeg command in transcode feature * fix(upload): always delete transcode output file * fix(upload): fixed HideWindow issue * fix(upload): fixed HideWindow issue * fix(upload): fixed HideWindow issue * fix(upload): fixed HideWindow issue * fix(upload): fixed HideWindow issue * fix(upload): fixed HideWindow issue * fix(upload): fixed HideWindow issue * fix(devops): fixed build-windows * fix(mobilesdk): add logging for MultiUpload * fix(mobilesdk): fixed file permission issue on transcode * fixed lint error --------- Co-authored-by: dabasov --- core/version/version.go | 2 +- mobilesdk/zbox/storage.go | 4 ++ winsdk/sdk.go | 22 ++++++- winsdk/status.go | 18 ++++-- winsdk/storage.go | 5 ++ winsdk/stream.go | 2 + zboxcore/sdk/chunk_upload_vars.go | 10 +++ zboxcore/sdk/chunk_upload_vars_windows.go | 10 +++ zboxcore/sdk/chunked_upload.go | 9 ++- zboxcore/sdk/chunked_upload_web_streaming.go | 65 ++++++++++++++------ 10 files changed, 121 insertions(+), 26 deletions(-) create mode 100644 zboxcore/sdk/chunk_upload_vars.go create mode 100644 zboxcore/sdk/chunk_upload_vars_windows.go diff --git a/core/version/version.go b/core/version/version.go index 869920b30..aa525ac10 100644 --- a/core/version/version.go +++ b/core/version/version.go @@ -2,5 +2,5 @@ //====== THIS IS AUTOGENERATED FILE. DO NOT MODIFY ======== package version -const VERSIONSTR = "v1.10.0-51-g725742a3" +const VERSIONSTR = "v1.10.0-62-g0fba09a8" diff --git a/mobilesdk/zbox/storage.go b/mobilesdk/zbox/storage.go index da702d1da..e0b1bb855 100644 --- a/mobilesdk/zbox/storage.go +++ b/mobilesdk/zbox/storage.go @@ -8,6 +8,7 @@ import ( "github.com/0chain/gosdk/constants" "github.com/0chain/gosdk/zboxcore/fileref" + "github.com/0chain/gosdk/zboxcore/logger" "github.com/0chain/gosdk/zboxcore/sdk" ) @@ -324,8 +325,10 @@ func RepairFile(allocationID, workdir, localPath, remotePath, thumbnailPath stri // - error func MultiUpload(allocationID string, workdir string, jsonMultiUploadOptions string, statusCb StatusCallbackMocked) error { var options []MultiUploadOption + logger.Logger.Info("multiupload: ", jsonMultiUploadOptions) err := json.Unmarshal([]byte(jsonMultiUploadOptions), &options) if err != nil { + logger.Logger.Error("multiupload: ", err) return err } totalUploads := len(options) @@ -350,6 +353,7 @@ func MultiUpload(allocationID string, workdir string, jsonMultiUploadOptions str a, err := getAllocation(allocationID) if err != nil { + logger.Logger.Error("multiupload: ", err) return err } return a.StartMultiUpload(workdir, filePaths, fileNames, thumbnailPaths, encrypts, chunkNumbers, remotePaths, isUpdates, isWebstreaming, &StatusCallbackWrapped{Callback: statusCb}) diff --git a/winsdk/sdk.go b/winsdk/sdk.go index 2dbcacc2d..71f5e1153 100644 --- a/winsdk/sdk.go +++ b/winsdk/sdk.go @@ -29,7 +29,6 @@ import ( var log logger.Logger func main() { - } // SetLogFile - set log file @@ -260,3 +259,24 @@ func GetLookupHash(allocationID *C.char, path *C.char) *C.char { hash := getLookupHash(C.GoString(allocationID), C.GoString(path)) return WithJSON(hash, nil) } + +// SetFFmpeg set the full file name of ffmpeg.exe +// ## Inputs: +// - fullFileName +// return +// { +// "error":"", +// "result":true, +// } +// +//export SetFFmpeg +func SetFFmpeg(fullFileName *C.char) *C.char { + f := C.GoString(fullFileName) + + _, err := os.Stat(f) + if os.IsNotExist(err) { + return WithJSON(false, err) + } + sdk.CmdFFmpeg = C.GoString(fullFileName) + return WithJSON(true, nil) +} diff --git a/winsdk/status.go b/winsdk/status.go index a5d5845d1..836608ed4 100644 --- a/winsdk/status.go +++ b/winsdk/status.go @@ -18,7 +18,7 @@ type Status struct { Error string Completed bool LookupHash string - wg sync.WaitGroup + wg *sync.WaitGroup } type StatusCallback struct { @@ -73,7 +73,11 @@ func (c *StatusCallback) InProgress(allocationID, remotePath string, op int, com s.LookupHash = lookupHash if completedBytes >= s.TotalBytes { s.Completed = true - s.wg.Done() + if s.wg != nil { + s.wg.Done() + s.wg = nil + } + } } @@ -83,7 +87,10 @@ func (c *StatusCallback) Error(allocationID string, remotePath string, op int, e s := c.getStatus(lookupHash) s.Error = err.Error() s.LookupHash = lookupHash - s.wg.Done() + if s.wg != nil { + s.wg.Done() + s.wg = nil + } } func (c *StatusCallback) Completed(allocationID, remotePath string, filename string, mimetype string, size int, op int) { @@ -93,7 +100,10 @@ func (c *StatusCallback) Completed(allocationID, remotePath string, filename str s.Completed = true s.LookupHash = lookupHash s.CompletedBytes = s.TotalBytes - s.wg.Done() + if s.wg != nil { + s.wg.Done() + s.wg = nil + } } func (c *StatusCallback) CommitMetaCompleted(request, response string, err error) { diff --git a/winsdk/storage.go b/winsdk/storage.go index e80de99f4..fd9a411d3 100644 --- a/winsdk/storage.go +++ b/winsdk/storage.go @@ -195,6 +195,11 @@ func GetFileMeta(allocationID, path *C.char) *C.char { // //export BulkUpload func BulkUpload(allocationID, files *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: ", r) + } + }() allocID := C.GoString(allocationID) workdir, _ := os.UserHomeDir() jsFiles := C.GoString(files) diff --git a/winsdk/stream.go b/winsdk/stream.go index d4c5b2000..bad529daf 100644 --- a/winsdk/stream.go +++ b/winsdk/stream.go @@ -16,6 +16,7 @@ import ( "path/filepath" "strconv" "strings" + "sync" "github.com/0chain/gosdk/zboxcore/sdk" lru "github.com/hashicorp/golang-lru/v2" @@ -219,6 +220,7 @@ func downloadBlocks(remotePath string, f *sdk.ConsolidatedFileMeta, ra httpRange // if os.IsNotExist(err) { statusBar := NewStatusBar(statusDownload, key) status := statusBar.getStatus(key) + status.wg = &sync.WaitGroup{} status.wg.Add(1) log.Info("win: download blocks to ", mf) err = alloc.DownloadFileByBlock(mf, remotePath, startBlock, endBlock, numBlocks, false, statusBar, true) diff --git a/zboxcore/sdk/chunk_upload_vars.go b/zboxcore/sdk/chunk_upload_vars.go new file mode 100644 index 000000000..5a3095822 --- /dev/null +++ b/zboxcore/sdk/chunk_upload_vars.go @@ -0,0 +1,10 @@ +//go:build !windows +// +build !windows + +package sdk + +import "syscall" + +var ( + sysProcAttr = &syscall.SysProcAttr{} +) diff --git a/zboxcore/sdk/chunk_upload_vars_windows.go b/zboxcore/sdk/chunk_upload_vars_windows.go new file mode 100644 index 000000000..4b0d2113b --- /dev/null +++ b/zboxcore/sdk/chunk_upload_vars_windows.go @@ -0,0 +1,10 @@ +//go:build windows +// +build windows + +package sdk + +import "syscall" + +var ( + sysProcAttr = &syscall.SysProcAttr{HideWindow: true} +) diff --git a/zboxcore/sdk/chunked_upload.go b/zboxcore/sdk/chunked_upload.go index e093e5b4d..042de5862 100644 --- a/zboxcore/sdk/chunked_upload.go +++ b/zboxcore/sdk/chunked_upload.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "net/http" + "os" "path/filepath" "strings" "sync" @@ -36,6 +37,7 @@ const ( ) var ( + CmdFFmpeg = "ffmpeg" // DefaultHashFunc default hash method for stream merkle tree DefaultHashFunc = func(left, right string) string { return coreEncryption.Hash(left + right) @@ -101,12 +103,15 @@ func CreateChunkedUpload( } if webStreaming { - newFileReader, newFileMeta, err := TranscodeWebStreaming(fileReader, fileMeta) + newFileReader, newFileMeta, f, err := TranscodeWebStreaming(workdir, fileReader, fileMeta) + defer os.Remove(f) + if err != nil { return nil, thrown.New("upload_failed", err.Error()) } fileMeta = *newFileMeta fileReader = newFileReader + } err := ValidateRemoteFileName(fileMeta.RemoteName) @@ -194,7 +199,7 @@ func CreateChunkedUpload( su.workdir = filepath.Join(workdir, ".zcn") //create upload folder to save progress - err = sys.Files.MkdirAll(filepath.Join(su.workdir, "upload"), 0744) + err = sys.Files.MkdirAll(filepath.Join(su.workdir, "upload"), 0766) if err != nil { return nil, err } diff --git a/zboxcore/sdk/chunked_upload_web_streaming.go b/zboxcore/sdk/chunked_upload_web_streaming.go index cc4eac65a..7b4694c60 100644 --- a/zboxcore/sdk/chunked_upload_web_streaming.go +++ b/zboxcore/sdk/chunked_upload_web_streaming.go @@ -4,8 +4,10 @@ import ( "bufio" "bytes" "io" + "os" "os/exec" "path" + "path/filepath" "strings" thrown "github.com/0chain/errors" @@ -13,41 +15,68 @@ import ( ) // Converting the video file to fmp4 format for web streaming -func TranscodeWebStreaming(fileReader io.Reader, fileMeta FileMeta) (io.Reader, *FileMeta, error) { - var stdOut bytes.Buffer +func TranscodeWebStreaming(workdir string, fileReader io.Reader, fileMeta FileMeta) (io.Reader, *FileMeta, string, error) { var stdErr bytes.Buffer - args := []string{"-i", fileMeta.Path, "-g", "30", "-f", "mp4", "-movflags", "frag_keyframe+empty_moov", "pipe:1"} - cmdFfmpeg := exec.Command("ffmpeg", args...) + outDir := filepath.Join(workdir, ".zcn", "transcode") + // create ./zcn/transcode folder if it doesn't exists + os.MkdirAll(outDir, 0766) //nolint: errcheck + fileName := filepath.Join(outDir, fileMeta.RemoteName) - cmdFfmpeg.Stdout = bufio.NewWriter(&stdOut) - cmdFfmpeg.Stderr = bufio.NewWriter(&stdErr) + // w, err := os.Create(fileName) + // if err != nil { + // return nil, nil, "", err + // } - err := cmdFfmpeg.Run() + logger.Logger.Info("transcode: start ", fileName) + + args := []string{"-i", fileMeta.Path, "-f", "mp4", "-movflags", "frag_keyframe+empty_moov+default_base_moof", fileName, "-y"} + cmd := exec.Command(CmdFFmpeg, args...) + cmd.Stderr = bufio.NewWriter(&stdErr) + // cmd.Stdout = w + cmd.SysProcAttr = sysProcAttr + err := cmd.Run() + + defer func() { + // w.Close() + err = cmd.Process.Kill() + if err != nil { + logger.Logger.Error(err) + } + }() + + if err != nil { + logger.Logger.Error(err, stdErr.String()) + return nil, nil, "", thrown.New("Transcoding Failed: ", err.Error()) + } + + // open file reader with readonly + r, err := os.Open(fileName) if err != nil { - logger.Logger.Error(err) - return nil, nil, thrown.New("Transcoding Failed: ", err.Error()) + return nil, nil, fileName, err } - trascodedBufSlice := stdOut.Bytes() - transcodedFileReader := bytes.NewReader(trascodedBufSlice) + logger.Logger.Info("transcode: done ", fileName) - remoteName, remotePath := getRemoteNameAndRemotePath(fileMeta.RemoteName, fileMeta.RemotePath) + fi, err := r.Stat() + if err != nil { + return nil, nil, fileName, err + } - transcodedFileMeta := &FileMeta{ - MimeType: "video/fmp4", + fm := &FileMeta{ + MimeType: "video/mp4", Path: fileMeta.Path, ThumbnailPath: fileMeta.ThumbnailPath, ActualHash: fileMeta.ActualHash, - ActualSize: int64(len(trascodedBufSlice)), + ActualSize: fi.Size(), ActualThumbnailSize: fileMeta.ActualThumbnailSize, ActualThumbnailHash: fileMeta.ActualThumbnailHash, - RemoteName: remoteName, - RemotePath: remotePath, + RemoteName: fileMeta.RemoteName, + RemotePath: fileMeta.RemotePath, } - return transcodedFileReader, transcodedFileMeta, nil + return r, fm, fileName, nil } func getRemoteNameAndRemotePath(remoteName string, remotePath string) (string, string) { From a0aa9f77cfdc4cc5ecb90406b9f1bb45c2918c35 Mon Sep 17 00:00:00 2001 From: peterlimg <54137706+peterlimg@users.noreply.github.com> Date: Tue, 3 Oct 2023 00:43:15 +1100 Subject: [PATCH 047/134] Fix web streaming - wasm (#1237) * Do not send GET http request with body * Use downloadBlocks to download in player_file * Call ListDir to get file meta * Format * Download 100 blocks each time by default * Fix downloadBlocks Track the downloaded bytes and trunk the padding 0 bytes * Update downloadBlocks to download blocks concurretly Use the same download method with downloadFileByBlocks * Add ActualFileSize in PlayListFile * Update wasm_exec.js to go 1.21.0 * Update version * Replace alloc.DownloadBlocks with DownloadBlocksToFileHandler --- core/version/version.go | 2 +- wasmsdk/blobber.go | 68 ++++++++++------------------ wasmsdk/demo/index.html | 11 +++-- wasmsdk/demo/player.js | 23 +++++++++- wasmsdk/player_file.go | 83 ++++++++++++++++------------------- wasmsdk/player_stream.go | 21 ++++++++- zboxcore/sdk/networkworker.go | 3 +- zboxcore/sdk/playlist.go | 17 +++---- zboxcore/zboxutil/http.go | 14 +++++- 9 files changed, 134 insertions(+), 108 deletions(-) diff --git a/core/version/version.go b/core/version/version.go index aa525ac10..6ffbf40a9 100644 --- a/core/version/version.go +++ b/core/version/version.go @@ -2,5 +2,5 @@ //====== THIS IS AUTOGENERATED FILE. DO NOT MODIFY ======== package version -const VERSIONSTR = "v1.10.0-62-g0fba09a8" +const VERSIONSTR = "v1.10.0-70-g7f7e89b4" diff --git a/wasmsdk/blobber.go b/wasmsdk/blobber.go index e9bf9a647..9de0de825 100644 --- a/wasmsdk/blobber.go +++ b/wasmsdk/blobber.go @@ -7,8 +7,8 @@ import ( "bytes" "encoding/json" "errors" + "fmt" "path" - "path/filepath" "strings" "sync" "syscall/js" @@ -776,66 +776,44 @@ func upload(allocationID, remotePath string, fileBytes, thumbnailBytes []byte, w } // download download file blocks -func downloadBlocks(allocationID, remotePath, authTicket, lookupHash string, numBlocks int, startBlockNumber, endBlockNumber int64, callbackFuncName string, isFinal bool) ([]byte, error) { - +func downloadBlocks(alloc *sdk.Allocation, remotePath, authTicket, lookupHash string, startBlock, endBlock int64) ([]byte, error) { if len(remotePath) == 0 && len(authTicket) == 0 { return nil, RequiredArg("remotePath/authTicket") } - wg := &sync.WaitGroup{} - statusBar := &StatusBar{wg: wg} - if callbackFuncName != "" { - callback := js.Global().Get(callbackFuncName) - statusBar.callback = func(totalBytes, completedBytes int, filename, objURL, err string) { - callback.Invoke(totalBytes, completedBytes, filename, objURL, err) - } - } - wg.Add(1) - - fileName := strings.Replace(path.Base(remotePath), "/", "-", -1) - localPath := filepath.Join(allocationID, fileName) - - fs, _ := sys.Files.Open(localPath) - mf, _ := fs.(*sys.MemFile) - var ( - err error - downloader sdk.Downloader + wg = &sync.WaitGroup{} + statusBar = &StatusBar{wg: wg} ) - if allocObj == nil { - downloader, err = sdk.CreateDownloader(allocationID, localPath, remotePath, - sdk.WithAuthticket(authTicket, lookupHash), - sdk.WithBlocks(startBlockNumber, endBlockNumber, numBlocks), - sdk.WithFileHandler(mf)) + fileName := strings.Replace(path.Base(remotePath), "/", "-", -1) + localPath := alloc.ID + "-" + fmt.Sprintf("%v-%s", startBlock, fileName) - } else { - downloader, err = sdk.CreateDownloader(allocationID, localPath, remotePath, - sdk.WithAuthticket(authTicket, lookupHash), - sdk.WithBlocks(startBlockNumber, endBlockNumber, numBlocks), - sdk.WithAllocation(allocObj), - sdk.WithFileHandler(mf)) + fs, err := sys.Files.Open(localPath) + if err != nil { + return nil, fmt.Errorf("could not open local file: %v", err) } - if err != nil { - PrintError(err.Error()) - return nil, err + mf, _ := fs.(*sys.MemFile) + if mf == nil { + return nil, fmt.Errorf("invalid memfile") } defer sys.Files.Remove(localPath) //nolint - err = downloader.Start(statusBar, isFinal) - - if err == nil { - wg.Wait() - } else { - PrintError("Download failed.", err.Error()) + wg.Add(1) + err = alloc.DownloadByBlocksToFileHandler( + mf, + remotePath, + startBlock, + endBlock, + 10, + false, + statusBar, true) + if err != nil { return nil, err } - if !statusBar.success { - return nil, errors.New("Download failed: unknown error") - } - + wg.Wait() return mf.Buffer.Bytes(), nil } diff --git a/wasmsdk/demo/index.html b/wasmsdk/demo/index.html index 80d30d7cc..e31f93a24 100644 --- a/wasmsdk/demo/index.html +++ b/wasmsdk/demo/index.html @@ -3,7 +3,7 @@ - + @@ -36,13 +36,13 @@

please download zcn.wasm from https://github.com/0chain/gosdk/releases/lates
Wallet
+ value="632d7e04fb8ff9cebe36caa20050458811d5eb3d3bdeb6a3877116a6c9d3ad68" />

+ value="1a82efcc1afa64468ba6d090da6ae4995e1c2c5fb3a107b01d5f67fe1f66bc08" />

+ value="aeb6a6c2bd30a9cd9323a46d887bfc9cf7996d0d2158a55453d7b16a99ace7182e998dd30c0d34c3093796f7075aaa97f3e25589c278971634cba3f2303b3216" />

+ value="visit acquire month friend twice guide hard myself differ video style shaft situate general valve dice brick carbon replace powder indicate hello orient search" />
@@ -154,7 +154,6 @@

please download zcn.wasm from https://github.com/0chain/gosdk/releases/lates

- + \ No newline at end of file diff --git a/wasmsdk/proxy.go b/wasmsdk/proxy.go index 9024bff8f..1b298f53f 100644 --- a/wasmsdk/proxy.go +++ b/wasmsdk/proxy.go @@ -242,6 +242,11 @@ func main() { "createJwtSession": createJwtSession, "createJwtToken": createJwtToken, "refreshJwtToken": refreshJwtToken, + + //split key + "splitKeys": splitKeys, + "setWalletInfo": setWalletInfo, + "setAuthUrl": setAuthUrl, }) fmt.Println("__wasm_initialized__ = true;") diff --git a/wasmsdk/transaction_base.go b/wasmsdk/transaction_base.go new file mode 100644 index 000000000..04f63d512 --- /dev/null +++ b/wasmsdk/transaction_base.go @@ -0,0 +1,25 @@ +package main + +import "github.com/0chain/gosdk/core/zcncrypto" + +type localConfig struct { + chain ChainConfig + wallet zcncrypto.Wallet + authUrl string + isConfigured bool + isValidWallet bool + isSplitWallet bool +} + +type ChainConfig struct { + ChainID string `json:"chain_id,omitempty"` + BlockWorker string `json:"block_worker"` + Miners []string `json:"miners"` + Sharders []string `json:"sharders"` + SignatureScheme string `json:"signature_scheme"` + MinSubmit int `json:"min_submit"` + MinConfirmation int `json:"min_confirmation"` + ConfirmationChainLength int `json:"confirmation_chain_length"` + EthNode string `json:"eth_node"` + SharderConsensous int `json:"sharder_consensous"` +} \ No newline at end of file diff --git a/wasmsdk/wallet_base.go b/wasmsdk/wallet_base.go new file mode 100644 index 000000000..c7138f9f7 --- /dev/null +++ b/wasmsdk/wallet_base.go @@ -0,0 +1,78 @@ +package main + +import ( + "encoding/json" + "strings" + "github.com/0chain/errors" + "github.com/0chain/gosdk/core/zcncrypto" +) + +var _config localConfig +// var logging logger.Logger + +const ( + StatusSuccess int = 0 + StatusNetworkError int = 1 + // TODO: Change to specific error + StatusError int = 2 + StatusRejectedByUser int = 3 + StatusInvalidSignature int = 4 + StatusAuthError int = 5 + StatusAuthVerifyFailed int = 6 + StatusAuthTimeout int = 7 + StatusUnknown int = -1 +) + + +// Split keys from the primary master key +func splitKeys(privateKey string, numSplits int) (string, error) { + if _config.chain.SignatureScheme != "bls0chain" { + return "", errors.New("", "signature key doesn't support split key") + } + sigScheme := zcncrypto.NewSignatureScheme(_config.chain.SignatureScheme) + err := sigScheme.SetPrivateKey(privateKey) + if err != nil { + return "", errors.Wrap(err, "set private key failed") + } + w, err := sigScheme.SplitKeys(numSplits) + if err != nil { + return "", errors.Wrap(err, "split key failed.") + } + wStr, err := w.Marshal() + if err != nil { + return "", errors.Wrap(err, "wallet encoding failed.") + } + return wStr, nil +} + + +// SetWalletInfo should be set before any transaction or client specific APIs +// splitKeyWallet parameter is valid only if SignatureScheme is "BLS0Chain" +// +// # Inputs +// - jsonWallet: json format of wallet +// - splitKeyWallet: if wallet keys is split +func setWalletInfo(jsonWallet string, splitKeyWallet bool) error { + err := json.Unmarshal([]byte(jsonWallet), &_config.wallet) + if err == nil { + if _config.chain.SignatureScheme == "bls0chain" { + _config.isSplitWallet = splitKeyWallet + } + _config.isValidWallet = true + } + return err +} + +// SetAuthUrl will be called by app to set zauth URL to SDK. +// # Inputs +// - url: the url of zAuth server +func setAuthUrl(url string) error { + if !_config.isSplitWallet { + return errors.New("", "wallet type is not split key") + } + if url == "" { + return errors.New("", "invalid auth url") + } + _config.authUrl = strings.TrimRight(url, "/") + return nil +} \ No newline at end of file From edf92cbe8678006518ba85d53f8db82f453639bd Mon Sep 17 00:00:00 2001 From: Ash-KODES Date: Sat, 14 Oct 2023 19:25:17 +0530 Subject: [PATCH 056/134] chnaging go version for cdn --- wasmsdk/demo/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wasmsdk/demo/index.html b/wasmsdk/demo/index.html index f26a8a352..262c998d8 100644 --- a/wasmsdk/demo/index.html +++ b/wasmsdk/demo/index.html @@ -3,7 +3,7 @@ - + From 84f3793319d203482d21b0bd377ef857ebd39290 Mon Sep 17 00:00:00 2001 From: Ash-KODES Date: Sun, 15 Oct 2023 01:26:55 +0530 Subject: [PATCH 057/134] bumped version --- core/version/version.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/version/version.go b/core/version/version.go index 6ffbf40a9..ace6a9e1b 100644 --- a/core/version/version.go +++ b/core/version/version.go @@ -2,5 +2,5 @@ //====== THIS IS AUTOGENERATED FILE. DO NOT MODIFY ======== package version -const VERSIONSTR = "v1.10.0-70-g7f7e89b4" +const VERSIONSTR = "v1.10.0-65-gedf92cbe" From 778787a8a60ea72b951dc14c22d0ec1b5f4ea6ee Mon Sep 17 00:00:00 2001 From: Ash-KODES Date: Sun, 15 Oct 2023 15:05:48 +0530 Subject: [PATCH 058/134] minor refactoring --- wasmsdk/demo/index.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/wasmsdk/demo/index.html b/wasmsdk/demo/index.html index 262c998d8..ade50ed5d 100644 --- a/wasmsdk/demo/index.html +++ b/wasmsdk/demo/index.html @@ -881,7 +881,7 @@

please download zcn.wasm from https://github.com/0chain/gosdk/releases/lates try { const jsonWalletString = JSON.stringify(jsonWallet); const wallet = await goWasm.sdk.setWalletInfo(jsonWalletString, splitKeyWallet) - txtOutput.innerHTML = "Wallet Info is Set"; + txtOutput.innerHTML = "wallet info is set"; } catch (e) { alert(e) } @@ -891,7 +891,7 @@

please download zcn.wasm from https://github.com/0chain/gosdk/releases/lates const url = "Testing" try { const authURL = await goWasm.sdk.setAuthUrl(url) - txtOutput.innerHTML = "auth url set"; + txtOutput.innerHTML = "auth url is set"; } catch (e) { alert(e) } From 32cdf30a9c56789095cad2fe826f5d22899cd566 Mon Sep 17 00:00:00 2001 From: Ash-KODES Date: Sun, 15 Oct 2023 23:36:56 +0530 Subject: [PATCH 059/134] bumping wasm_exec.js version --- wasmsdk/demo/index.html | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/wasmsdk/demo/index.html b/wasmsdk/demo/index.html index ade50ed5d..c2cb61f3a 100644 --- a/wasmsdk/demo/index.html +++ b/wasmsdk/demo/index.html @@ -3,7 +3,7 @@ - + @@ -854,9 +854,9 @@

please download zcn.wasm from https://github.com/0chain/gosdk/releases/lates } }) - onClick('btnSplitKeys', async () => { + onClick('btnSplitKeys', async () => { const privateKey = "41729ed8d82f782646d2d30b9719acfd236842b9b6e47fee12b7bdbd05b35122" - const numSplits = 1 + const numSplits = 2 try { const wStr = await goWasm.sdk.splitKeys(privateKey, numSplits) txtOutput.innerHTML = wStr; From 4113b9a6c81a7fc112b66dcbb0f943242e1db1d7 Mon Sep 17 00:00:00 2001 From: Ash-KODES Date: Mon, 16 Oct 2023 14:36:46 +0530 Subject: [PATCH 060/134] Refactoring unnecessary structs --- wasmsdk/demo/main.go | 1 + wasmsdk/transaction_base.go | 25 -------------- wasmsdk/wallet_base.go | 69 ++++++------------------------------- 3 files changed, 11 insertions(+), 84 deletions(-) delete mode 100644 wasmsdk/transaction_base.go diff --git a/wasmsdk/demo/main.go b/wasmsdk/demo/main.go index 762b553cc..ad0cab057 100644 --- a/wasmsdk/demo/main.go +++ b/wasmsdk/demo/main.go @@ -14,6 +14,7 @@ import ( func main() { zcncore.InitSignatureScheme("bls0chain") + ctx, cf := context.WithCancel(context.Background()) router := bunrouter.New() diff --git a/wasmsdk/transaction_base.go b/wasmsdk/transaction_base.go deleted file mode 100644 index 04f63d512..000000000 --- a/wasmsdk/transaction_base.go +++ /dev/null @@ -1,25 +0,0 @@ -package main - -import "github.com/0chain/gosdk/core/zcncrypto" - -type localConfig struct { - chain ChainConfig - wallet zcncrypto.Wallet - authUrl string - isConfigured bool - isValidWallet bool - isSplitWallet bool -} - -type ChainConfig struct { - ChainID string `json:"chain_id,omitempty"` - BlockWorker string `json:"block_worker"` - Miners []string `json:"miners"` - Sharders []string `json:"sharders"` - SignatureScheme string `json:"signature_scheme"` - MinSubmit int `json:"min_submit"` - MinConfirmation int `json:"min_confirmation"` - ConfirmationChainLength int `json:"confirmation_chain_length"` - EthNode string `json:"eth_node"` - SharderConsensous int `json:"sharder_consensous"` -} \ No newline at end of file diff --git a/wasmsdk/wallet_base.go b/wasmsdk/wallet_base.go index c7138f9f7..0281757cf 100644 --- a/wasmsdk/wallet_base.go +++ b/wasmsdk/wallet_base.go @@ -1,65 +1,22 @@ package main import ( - "encoding/json" - "strings" - "github.com/0chain/errors" - "github.com/0chain/gosdk/core/zcncrypto" + "github.com/0chain/gosdk/zcncore" ) -var _config localConfig -// var logging logger.Logger - -const ( - StatusSuccess int = 0 - StatusNetworkError int = 1 - // TODO: Change to specific error - StatusError int = 2 - StatusRejectedByUser int = 3 - StatusInvalidSignature int = 4 - StatusAuthError int = 5 - StatusAuthVerifyFailed int = 6 - StatusAuthTimeout int = 7 - StatusUnknown int = -1 -) - - // Split keys from the primary master key func splitKeys(privateKey string, numSplits int) (string, error) { - if _config.chain.SignatureScheme != "bls0chain" { - return "", errors.New("", "signature key doesn't support split key") - } - sigScheme := zcncrypto.NewSignatureScheme(_config.chain.SignatureScheme) - err := sigScheme.SetPrivateKey(privateKey) - if err != nil { - return "", errors.Wrap(err, "set private key failed") - } - w, err := sigScheme.SplitKeys(numSplits) - if err != nil { - return "", errors.Wrap(err, "split key failed.") - } - wStr, err := w.Marshal() - if err != nil { - return "", errors.Wrap(err, "wallet encoding failed.") - } - return wStr, nil + wStr, err := zcncore.SplitKeys(privateKey, numSplits) + return wStr, err } - // SetWalletInfo should be set before any transaction or client specific APIs // splitKeyWallet parameter is valid only if SignatureScheme is "BLS0Chain" -// -// # Inputs -// - jsonWallet: json format of wallet -// - splitKeyWallet: if wallet keys is split +// # Inputs +// - jsonWallet: json format of wallet +// - splitKeyWallet: if wallet keys is split func setWalletInfo(jsonWallet string, splitKeyWallet bool) error { - err := json.Unmarshal([]byte(jsonWallet), &_config.wallet) - if err == nil { - if _config.chain.SignatureScheme == "bls0chain" { - _config.isSplitWallet = splitKeyWallet - } - _config.isValidWallet = true - } + err := zcncore.SetWalletInfo(jsonWallet, splitKeyWallet) return err } @@ -67,12 +24,6 @@ func setWalletInfo(jsonWallet string, splitKeyWallet bool) error { // # Inputs // - url: the url of zAuth server func setAuthUrl(url string) error { - if !_config.isSplitWallet { - return errors.New("", "wallet type is not split key") - } - if url == "" { - return errors.New("", "invalid auth url") - } - _config.authUrl = strings.TrimRight(url, "/") - return nil -} \ No newline at end of file + err := zcncore.SetAuthUrl(url) + return err +} From 0f61a49368d5a42eb90f88bd0bb3db6568234fcb Mon Sep 17 00:00:00 2001 From: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Date: Mon, 16 Oct 2023 16:06:14 +0530 Subject: [PATCH 061/134] create new conID (#1256) --- zboxcore/sdk/allocation.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 73cc23e14..34f6b4100 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -833,6 +833,7 @@ func (a *Allocation) DoMultiOperation(operations []OperationRequest) error { for ; i < len(operations); i++ { if ops > MultiOpBatchSize { // max batch size reached, commit + connectionID = zboxutil.NewConnectionId() break } op := operations[i] @@ -841,6 +842,7 @@ func (a *Allocation) DoMultiOperation(operations []OperationRequest) error { if _, ok := previousPaths[remotePath]; ok { // conflict found, commit + connectionID = zboxutil.NewConnectionId() break } From acc4fcd55ab597f547c422eb3ed1655d71395109 Mon Sep 17 00:00:00 2001 From: Ash-KODES Date: Tue, 17 Oct 2023 18:35:56 +0530 Subject: [PATCH 062/134] debugging consoles added --- wasmsdk/demo/index.html | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/wasmsdk/demo/index.html b/wasmsdk/demo/index.html index c2cb61f3a..c00658fb9 100644 --- a/wasmsdk/demo/index.html +++ b/wasmsdk/demo/index.html @@ -856,10 +856,11 @@

please download zcn.wasm from https://github.com/0chain/gosdk/releases/lates onClick('btnSplitKeys', async () => { const privateKey = "41729ed8d82f782646d2d30b9719acfd236842b9b6e47fee12b7bdbd05b35122" - const numSplits = 2 + const numSplits = 1 try { const wStr = await goWasm.sdk.splitKeys(privateKey, numSplits) txtOutput.innerHTML = wStr; + console.log("splitKeys", wStr); } catch (e) { alert(e) } @@ -891,7 +892,7 @@

please download zcn.wasm from https://github.com/0chain/gosdk/releases/lates const url = "Testing" try { const authURL = await goWasm.sdk.setAuthUrl(url) - txtOutput.innerHTML = "auth url is set"; + txtOutput.innerHTML = authURL; } catch (e) { alert(e) } From 0c75fadfc119cc3e89a3f1b1fce916f7f0c28eb0 Mon Sep 17 00:00:00 2001 From: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Date: Wed, 18 Oct 2023 15:20:16 +0530 Subject: [PATCH 063/134] fix statusbar update (#1257) --- zboxcore/sdk/multi_operation_worker.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/zboxcore/sdk/multi_operation_worker.go b/zboxcore/sdk/multi_operation_worker.go index 2df937d39..6bbc27541 100644 --- a/zboxcore/sdk/multi_operation_worker.go +++ b/zboxcore/sdk/multi_operation_worker.go @@ -304,10 +304,10 @@ func (mo *MultiOperation) Process() error { op.Error(mo.allocationObj, mo.getConsensus(), err) } return err - } - - for _, op := range mo.operations { - op.Completed(mo.allocationObj) + } else { + for _, op := range mo.operations { + op.Completed(mo.allocationObj) + } } return nil From 61af2ef39494beeafcf25a5a4471500b6a764497 Mon Sep 17 00:00:00 2001 From: Ash-KODES Date: Wed, 18 Oct 2023 18:45:56 +0530 Subject: [PATCH 064/134] lint fixes --- wasmsdk/wallet_base.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/wasmsdk/wallet_base.go b/wasmsdk/wallet_base.go index 0281757cf..37fafbb34 100644 --- a/wasmsdk/wallet_base.go +++ b/wasmsdk/wallet_base.go @@ -5,6 +5,7 @@ import ( ) // Split keys from the primary master key +//lint:ignore func splitKeys(privateKey string, numSplits int) (string, error) { wStr, err := zcncore.SplitKeys(privateKey, numSplits) return wStr, err @@ -15,6 +16,7 @@ func splitKeys(privateKey string, numSplits int) (string, error) { // # Inputs // - jsonWallet: json format of wallet // - splitKeyWallet: if wallet keys is split +//lint:ignore func setWalletInfo(jsonWallet string, splitKeyWallet bool) error { err := zcncore.SetWalletInfo(jsonWallet, splitKeyWallet) return err @@ -23,6 +25,7 @@ func setWalletInfo(jsonWallet string, splitKeyWallet bool) error { // SetAuthUrl will be called by app to set zauth URL to SDK. // # Inputs // - url: the url of zAuth server +//lint:ignore func setAuthUrl(url string) error { err := zcncore.SetAuthUrl(url) return err From 5fb102a08e33f654705fcb22a313dfad349dd89f Mon Sep 17 00:00:00 2001 From: Ash-KODES Date: Wed, 18 Oct 2023 19:02:42 +0530 Subject: [PATCH 065/134] lint ignore --- wasmsdk/wallet_base.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/wasmsdk/wallet_base.go b/wasmsdk/wallet_base.go index 37fafbb34..cb8baff29 100644 --- a/wasmsdk/wallet_base.go +++ b/wasmsdk/wallet_base.go @@ -5,6 +5,7 @@ import ( ) // Split keys from the primary master key + //lint:ignore func splitKeys(privateKey string, numSplits int) (string, error) { wStr, err := zcncore.SplitKeys(privateKey, numSplits) @@ -16,6 +17,7 @@ func splitKeys(privateKey string, numSplits int) (string, error) { // # Inputs // - jsonWallet: json format of wallet // - splitKeyWallet: if wallet keys is split + //lint:ignore func setWalletInfo(jsonWallet string, splitKeyWallet bool) error { err := zcncore.SetWalletInfo(jsonWallet, splitKeyWallet) @@ -25,6 +27,7 @@ func setWalletInfo(jsonWallet string, splitKeyWallet bool) error { // SetAuthUrl will be called by app to set zauth URL to SDK. // # Inputs // - url: the url of zAuth server + //lint:ignore func setAuthUrl(url string) error { err := zcncore.SetAuthUrl(url) From b73828cdcffeb9624c7713cd9a462e962723aab2 Mon Sep 17 00:00:00 2001 From: Ash-KODES Date: Wed, 18 Oct 2023 19:39:58 +0530 Subject: [PATCH 066/134] nolint: unused added --- wasmsdk/wallet_base.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/wasmsdk/wallet_base.go b/wasmsdk/wallet_base.go index cb8baff29..94c16fc56 100644 --- a/wasmsdk/wallet_base.go +++ b/wasmsdk/wallet_base.go @@ -6,7 +6,7 @@ import ( // Split keys from the primary master key -//lint:ignore +//nolint: unused func splitKeys(privateKey string, numSplits int) (string, error) { wStr, err := zcncore.SplitKeys(privateKey, numSplits) return wStr, err @@ -18,7 +18,7 @@ func splitKeys(privateKey string, numSplits int) (string, error) { // - jsonWallet: json format of wallet // - splitKeyWallet: if wallet keys is split -//lint:ignore +//nolint: unused func setWalletInfo(jsonWallet string, splitKeyWallet bool) error { err := zcncore.SetWalletInfo(jsonWallet, splitKeyWallet) return err @@ -28,7 +28,7 @@ func setWalletInfo(jsonWallet string, splitKeyWallet bool) error { // # Inputs // - url: the url of zAuth server -//lint:ignore +//nolint: unused func setAuthUrl(url string) error { err := zcncore.SetAuthUrl(url) return err From f58eb31ab2d2b6293b0bd19a05585b65e2bc11cb Mon Sep 17 00:00:00 2001 From: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Date: Sat, 21 Oct 2023 01:34:38 +0530 Subject: [PATCH 067/134] use httpdo for create connection (#1259) --- zboxcore/sdk/multi_operation_worker.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/zboxcore/sdk/multi_operation_worker.go b/zboxcore/sdk/multi_operation_worker.go index 6bbc27541..8ef41c7de 100644 --- a/zboxcore/sdk/multi_operation_worker.go +++ b/zboxcore/sdk/multi_operation_worker.go @@ -91,8 +91,10 @@ func (mo *MultiOperation) createConnectionObj(blobberIdx int) (err error) { httpreq.Header.Add("Content-Type", formWriter.FormDataContentType()) ctx, cncl := context.WithTimeout(mo.ctx, DefaultCreateConnectionTimeOut) defer cncl() - resp, err = zboxutil.Client.Do(httpreq.WithContext(ctx)) - + err = zboxutil.HttpDo(ctx, cncl, httpreq, func(r *http.Response, err error) error { + resp = r + return err + }) if err != nil { logger.Logger.Error("Create Connection: ", err) return From 937ae61bc0c81aeba6b354284b6ed399ab55940c Mon Sep 17 00:00:00 2001 From: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Date: Wed, 25 Oct 2023 17:32:12 +0530 Subject: [PATCH 068/134] Add create dir in repair (#1262) * fix delete dir err in cb * add way to create dir in repair --- zboxcore/sdk/allocation.go | 39 ++++++++++++++++++++++++++++++++++++ zboxcore/sdk/dirworker.go | 19 ------------------ zboxcore/sdk/repairworker.go | 15 ++++++++++++++ 3 files changed, 54 insertions(+), 19 deletions(-) diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 34f6b4100..252538f17 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -13,6 +13,7 @@ import ( "net/http" "net/url" "os" + "path" "path/filepath" "strconv" "strings" @@ -1616,6 +1617,44 @@ func (a *Allocation) deleteFile(path string, threshConsensus, fullConsensus int, return err } +func (a *Allocation) createDir(remotePath string, threshConsensus, fullConsensus int, mask zboxutil.Uint128) error { + if !a.isInitialized() { + return notInitialized + } + + if remotePath == "" { + return errors.New("invalid_name", "Invalid name for dir") + } + + if !path.IsAbs(remotePath) { + return errors.New("invalid_path", "Path is not absolute") + } + + remotePath = zboxutil.RemoteClean(remotePath) + timestamp := int64(common.Now()) + req := DirRequest{ + allocationObj: a, + allocationID: a.ID, + allocationTx: a.Tx, + blobbers: a.Blobbers, + mu: &sync.Mutex{}, + dirMask: mask, + connectionID: zboxutil.NewConnectionId(), + remotePath: remotePath, + wg: &sync.WaitGroup{}, + timestamp: timestamp, + Consensus: Consensus{ + RWMutex: &sync.RWMutex{}, + consensusThresh: threshConsensus, + fullconsensus: fullConsensus, + }, + } + req.ctx, req.ctxCncl = context.WithCancel(a.ctx) + + err := req.ProcessDir(a) + return err +} + func (a *Allocation) GetAuthTicketForShare( path, filename, referenceType, refereeClientID string) (string, error) { diff --git a/zboxcore/sdk/dirworker.go b/zboxcore/sdk/dirworker.go index c19ba468e..6ec68becd 100644 --- a/zboxcore/sdk/dirworker.go +++ b/zboxcore/sdk/dirworker.go @@ -96,25 +96,6 @@ func (req *DirRequest) ProcessDir(a *Allocation) error { } defer writeMarkerMU.Unlock(req.ctx, req.dirMask, a.Blobbers, time.Minute, req.connectionID) //nolint: errcheck - //Check if the allocation is to be repaired or rolled back - status, err := req.allocationObj.CheckAllocStatus() - l.Logger.Info("Allocation status: ", status) - if err != nil { - l.Logger.Error("Error checking allocation status: ", err) - return fmt.Errorf("directory creation failed: %s", err.Error()) - } - - if status == Repair { - l.Logger.Info("Repairing allocation") - //TODO: Need status callback to call repair allocation - // err = req.allocationObj.RepairAlloc() - // if err != nil { - // return err - // } - } - if status != Commit { - return ErrRetryOperation - } return req.commitRequest(existingDirCount) } diff --git a/zboxcore/sdk/repairworker.go b/zboxcore/sdk/repairworker.go index ea999d34c..57c279db2 100644 --- a/zboxcore/sdk/repairworker.go +++ b/zboxcore/sdk/repairworker.go @@ -7,6 +7,7 @@ import ( "github.com/0chain/gosdk/core/sys" "github.com/0chain/gosdk/zboxcore/fileref" l "github.com/0chain/gosdk/zboxcore/logger" + "github.com/0chain/gosdk/zboxcore/zboxutil" "go.uber.org/zap" ) @@ -88,6 +89,20 @@ func (r *RepairRequest) iterateDir(a *Allocation, dir *ListResult) { err := a.deleteFile(dir.Path, 0, consensus, dir.deleteMask) if err != nil { l.Logger.Error("repair_file_failed", zap.Error(err)) + if r.statusCB != nil { + r.statusCB.Error(a.ID, dir.Path, OpRepair, err) + } + return + } + r.filesRepaired++ + } else if consensus < len(a.Blobbers) { + createMask := dir.deleteMask.Not().And(zboxutil.NewUint128(1).Lsh(uint64(len(a.Blobbers))).Sub64(1)) + err := a.createDir(dir.Path, 0, createMask.CountOnes(), createMask) + if err != nil { + l.Logger.Error("repair_file_failed", zap.Error(err)) + if r.statusCB != nil { + r.statusCB.Error(a.ID, dir.Path, OpRepair, err) + } return } r.filesRepaired++ From 3ae631df852dfa35a9195624958569f9610e8dac Mon Sep 17 00:00:00 2001 From: Manohar Reddy Date: Thu, 26 Oct 2023 20:57:06 +0200 Subject: [PATCH 069/134] add desc for transaction data (#1263) --- wasmsdk/sdk.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/wasmsdk/sdk.go b/wasmsdk/sdk.go index 7eeccda23..e3daac0f1 100644 --- a/wasmsdk/sdk.go +++ b/wasmsdk/sdk.go @@ -124,7 +124,7 @@ func makeSCRestAPICall(scAddress, relativePath, paramsJson string) (string, erro return string(b), err } -func send(to_client_id string, tokens uint64, fee uint64) (string, error) { +func send(toClientID string, tokens uint64, fee uint64, desc string) (string, error) { wg := &sync.WaitGroup{} cb := &transactionCallback{wg: wg} txn, err := zcncore.NewTransaction(cb, fee, 0) @@ -133,7 +133,7 @@ func send(to_client_id string, tokens uint64, fee uint64) (string, error) { } wg.Add(1) - err = txn.Send(to_client_id, tokens, "") + err = txn.Send(toClientID, tokens, desc) if err == nil { wg.Wait() } else { From b15f9736c8133a9417db60ed4a105b3b39ccc1d5 Mon Sep 17 00:00:00 2001 From: Yaroslav Svitlytskyi <53532703+YarikRevich@users.noreply.github.com> Date: Thu, 26 Oct 2023 22:51:11 +0200 Subject: [PATCH 070/134] Feature: provide audit zcnswap and refactor if needed (#1205) * feature: modifies zcnswap to be consitent with zcnbridge * fix: fixed bugs * fix: removed dead code * feature: extended key store logic * fix: fixed bugs * fix: fixed conflicts * fix: removed dead code * fix: fixed bugs * Fix/remove path (#1221) * feature: added more test cases * fix: fixed existing test cases * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * feature: added more test cases * feature: added more test cases * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * feature: added mocks * fix: fixed bugs * fix: fixed mocks * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: made components internal * Add webstreaming to multiupload (#1190) * add webstreaming * fix typos * add webstreaming to wasm multiupload * fix typo * fix dup upload consensus (#1195) * Fix multiupload completed callback (#1172) * remove unnecessary print * fix delete and createdir * return major error * add webstreaming * fix typos * add webstreaming to wasm multiupload * fix typo * cleanup * fix completed callback * Feat/update methods in WinSDK (#1198) * delete dir in repair (#1196) * delete dir in repair * replace ioutil * fix unit test * fix list worker test * fix rename dir error * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * Add NFT Config contract (#1212) * Silent the zcnbridge http request when --silent (#1207) * Change the return type of downloadBlocks to []byte in wasm (#1218) * change the order of exchanges to get the ZCN prices (#1216) * Deprecate non multi-operation functions (#1214) * remove CreateDir, Rename, Copy, Move * use docker build wasm * use @v4 version of git action * Revert "use @v4 version of git action" This reverts commit fbb93f25a6ca63d6e205eac418d031bba428eb29. * Updated self hosted macos runner (#1219) * Updated self hosted macos runner * fixed runner name build-sdks.yml * remove path header, fix ws tag --------- Co-authored-by: YarikRevich Co-authored-by: Yaroslav Svitlytskyi <53532703+YarikRevich@users.noreply.github.com> Co-authored-by: Dinmukhammed Kambarov <52813950+din-mukhammed@users.noreply.github.com> Co-authored-by: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Co-authored-by: Lz Co-authored-by: Yaroslav Svitlytskyi Co-authored-by: peterlimg <54137706+peterlimg@users.noreply.github.com> Co-authored-by: Kishan Dhakan <42718091+Kishan-Dhakan@users.noreply.github.com> Co-authored-by: Manohar Reddy Co-authored-by: shahnawaz-creator <117025384+shahnawaz-creator@users.noreply.github.com> Co-authored-by: din-mukhammed * Revert "Fix/remove path (#1221)" (#1222) This reverts commit 464260aa3c2be34fdc0aca58582b27247528333b. * remove path header, fix ws tag (#1223) * remove path header, fix ws tag * fixed broken build --------- Co-authored-by: din-mukhammed * Updated self hosted macos runner (#1219) * Updated self hosted macos runner * fixed runner name build-sdks.yml (cherry picked from commit 1c9f143fe842e6c88fec1a6bc5fa0ced2ca84682) * fix * updated wasm binary build fix. * feature: added test case for swap logic * fix: resolved dependency conflicts * fix: fixed bugs * feature: added zcn eth rate fetch logic * Update blobber.go * Update authorizers_query.go * feature: replaced confusing param naming * fix: updated bridge initialization in wasm bridge integration * fix: replaced value amount with correct value * fix: wrong test case values * feature: switch to the usage of zcn token smart contract * fix: fixed bridge tests --------- Co-authored-by: Yaroslav Svitlytskyi Co-authored-by: Yury Co-authored-by: Dinmukhammed Kambarov <52813950+din-mukhammed@users.noreply.github.com> Co-authored-by: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Co-authored-by: Lz Co-authored-by: peterlimg <54137706+peterlimg@users.noreply.github.com> Co-authored-by: Kishan Dhakan <42718091+Kishan-Dhakan@users.noreply.github.com> Co-authored-by: Manohar Reddy Co-authored-by: shahnawaz-creator <117025384+shahnawaz-creator@users.noreply.github.com> Co-authored-by: din-mukhammed Co-authored-by: shahnawaz-creator --- go.mod | 4 - go.sum | 14 - wasmsdk/bridge.go | 4 +- wasmsdk/proxy.go | 4 +- wasmsdk/swap.go | 26 - zcnbridge/bridge.go | 334 +- zcnbridge/bridge_helper.go | 9 + zcnbridge/bridge_test.go | 125 +- zcnbridge/config.go | 26 +- zcnbridge/ethereum/bancor/bancor.go | 3757 +++++++++++++++++++ zcnbridge/ethereum/bind.sh | 7 - zcnbridge/ethereum/erc20/Context.sol | 24 - zcnbridge/ethereum/erc20/ERC20.sol | 356 -- zcnbridge/ethereum/erc20/IERC20.sol | 82 - zcnbridge/ethereum/erc20/IERC20Metadata.sol | 28 - zcnbridge/ethereum/erc20/erc20.go | 2319 ------------ zcnbridge/ethereum/token/token.go | 1336 +++++++ zcnbridge/keystore.go | 19 +- zcncore/mswallet_base.go | 6 +- zcnswap/config/config.go | 69 - zcnswap/contracts/IERC20.sol | 14 - zcnswap/contracts/IQuoter.sol | 55 - zcnswap/contracts/ISwapRouter.sol | 79 - zcnswap/contracts/bancor.go | 445 --- zcnswap/contracts/erc20.go | 2319 ------------ zcnswap/contracts/erc20/Context.sol | 24 - zcnswap/contracts/erc20/ERC20.sol | 356 -- zcnswap/contracts/erc20/IERC20.sol | 82 - zcnswap/contracts/erc20/IERC20Metadata.sol | 28 - zcnswap/handler.go | 85 - zcnswap/swapfactory/bancor/bancor.abi | 1 - zcnswap/swapfactory/bancor/service.go | 236 -- zcnswap/swapfactory/erc20/allowance.go | 49 - zcnswap/swapfactory/erc20/erc20.abi | 222 -- zcnswap/swapfactory/erc20/service.go | 78 - zcnswap/swapfactory/models.go | 122 - zcnswap/utils/ethconvert.go | 56 - zcnswap/utils/ethutils.go | 169 - zcnswap/utils/ethutils_test.go | 16 - zcnswap/utils/units.go | 29 - znft/example/go.sum | 6 - 41 files changed, 5494 insertions(+), 7526 deletions(-) delete mode 100644 wasmsdk/swap.go create mode 100755 zcnbridge/ethereum/bancor/bancor.go delete mode 100755 zcnbridge/ethereum/bind.sh delete mode 100644 zcnbridge/ethereum/erc20/Context.sol delete mode 100644 zcnbridge/ethereum/erc20/ERC20.sol delete mode 100644 zcnbridge/ethereum/erc20/IERC20.sol delete mode 100644 zcnbridge/ethereum/erc20/IERC20Metadata.sol delete mode 100644 zcnbridge/ethereum/erc20/erc20.go create mode 100644 zcnbridge/ethereum/token/token.go delete mode 100644 zcnswap/config/config.go delete mode 100755 zcnswap/contracts/IERC20.sol delete mode 100755 zcnswap/contracts/IQuoter.sol delete mode 100755 zcnswap/contracts/ISwapRouter.sol delete mode 100755 zcnswap/contracts/bancor.go delete mode 100755 zcnswap/contracts/erc20.go delete mode 100755 zcnswap/contracts/erc20/Context.sol delete mode 100755 zcnswap/contracts/erc20/ERC20.sol delete mode 100755 zcnswap/contracts/erc20/IERC20.sol delete mode 100755 zcnswap/contracts/erc20/IERC20Metadata.sol delete mode 100644 zcnswap/handler.go delete mode 100755 zcnswap/swapfactory/bancor/bancor.abi delete mode 100755 zcnswap/swapfactory/bancor/service.go delete mode 100755 zcnswap/swapfactory/erc20/allowance.go delete mode 100755 zcnswap/swapfactory/erc20/erc20.abi delete mode 100755 zcnswap/swapfactory/erc20/service.go delete mode 100755 zcnswap/swapfactory/models.go delete mode 100755 zcnswap/utils/ethconvert.go delete mode 100755 zcnswap/utils/ethutils.go delete mode 100755 zcnswap/utils/ethutils_test.go delete mode 100755 zcnswap/utils/units.go diff --git a/go.mod b/go.mod index 17e2787bd..f6a739113 100644 --- a/go.mod +++ b/go.mod @@ -19,7 +19,6 @@ require ( github.com/herumi/bls-go-binary v1.31.0 github.com/influxdata/influxdb v1.8.3 github.com/klauspost/reedsolomon v1.11.7 - github.com/labstack/echo v3.3.10+incompatible github.com/lithammer/shortuuid/v3 v3.0.7 github.com/machinebox/graphql v0.2.2 github.com/magma/augmented-networks/accounting/protos v0.1.1 @@ -81,7 +80,6 @@ require ( github.com/huin/goupnp v1.0.3 // indirect github.com/jackpal/go-nat-pmp v1.0.2 // indirect github.com/kr/pretty v0.3.1 // indirect - github.com/labstack/gommon v0.4.0 // indirect github.com/magiconair/properties v1.8.7 // indirect github.com/matryer/is v1.4.1 // indirect github.com/mattn/go-colorable v0.1.13 // indirect @@ -111,8 +109,6 @@ require ( github.com/tklauser/go-sysconf v0.3.11 // indirect github.com/tklauser/numcpus v0.6.0 // indirect github.com/urfave/cli/v2 v2.17.2-0.20221006022127-8f469abc00aa // indirect - github.com/valyala/bytebufferpool v1.0.0 // indirect - github.com/valyala/fasttemplate v1.2.2 // indirect github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect go.dedis.ch/fixbuf v1.0.3 // indirect go.opencensus.io v0.24.0 // indirect diff --git a/go.sum b/go.sum index 22bda131f..a98bbbde2 100644 --- a/go.sum +++ b/go.sum @@ -356,10 +356,6 @@ 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/labstack/echo v3.3.10+incompatible h1:pGRcYk231ExFAyoAjAfD85kQzRJCRI8bbnE7CX5OEgg= -github.com/labstack/echo v3.3.10+incompatible/go.mod h1:0INS7j/VjnFxD4E2wkz67b8cVwCLbBmJyDaka6Cmk1s= -github.com/labstack/gommon v0.4.0 h1:y7cvthEAEbU0yHOf4axH8ZG2NH8knB9iNSoTO8dyIk8= -github.com/labstack/gommon v0.4.0/go.mod h1:uW6kP17uPlLJsD3ijUYn3/M5bAxtlZhMI6m3MFxTMTM= github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lithammer/shortuuid/v3 v3.0.7 h1:trX0KTHy4Pbwo/6ia8fscyHoGA+mf1jWbPJVuvyJQQ8= github.com/lithammer/shortuuid/v3 v3.0.7/go.mod h1:vMk8ke37EmiewwolSO1NLW8vP4ZaKlRuDIi8tWWmAts= @@ -373,11 +369,9 @@ github.com/magma/augmented-networks/accounting/protos v0.1.1/go.mod h1:Hpfg8aAxl github.com/matryer/is v1.4.1 h1:55ehd8zaGABKLXQUe2awZ99BD/PTc2ls+KV/dXphgEQ= github.com/matryer/is v1.4.1/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= -github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= -github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng= github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= @@ -531,11 +525,6 @@ github.com/uptrace/bunrouter v1.0.20 h1:jNvYNcJxF+lSYBQAaQjnE6I11Zs0m+3M5Ek7fq/T github.com/uptrace/bunrouter v1.0.20/go.mod h1:TwT7Bc0ztF2Z2q/ZzMuSVkcb/Ig/d3MQeP2cxn3e1hI= github.com/urfave/cli/v2 v2.17.2-0.20221006022127-8f469abc00aa h1:5SqCsI/2Qya2bCzK15ozrqo2sZxkh0FHynJZOTVoV6Q= github.com/urfave/cli/v2 v2.17.2-0.20221006022127-8f469abc00aa/go.mod h1:1CNUng3PtjQMtRzJO4FMXBQvkGtuYRxxiR9xMa7jMwI= -github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= -github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= -github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= -github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo= -github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= github.com/willf/bitset v1.1.3/go.mod h1:RjeCKbqT1RxIR/KWY6phxZiaY1IyutSBfGjNPySAYV4= github.com/xlab/treeprint v0.0.0-20180616005107-d6fb6747feb6/go.mod h1:ce1O1j6UtZfjr22oyGxGLbauSBp2YVXpARAosm7dHBg= github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= @@ -745,9 +734,6 @@ golang.org/x/sys v0.0.0-20210225134936-a50acf3fe073/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210324051608-47abb6519492/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211103235746-7861aae1554b/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/wasmsdk/bridge.go b/wasmsdk/bridge.go index 730a16c3c..a06e4ddce 100644 --- a/wasmsdk/bridge.go +++ b/wasmsdk/bridge.go @@ -26,8 +26,7 @@ func initBridge( gasLimit uint64, value int64, consensusThreshold float64) error { - wallet := zcncore.GetWalletRaw() - if len(wallet.ClientID) == 0 { + if len(zcncore.GetWalletRaw().ClientID) == 0 { return errors.New("wallet_error", "wallet is not set") } @@ -49,6 +48,7 @@ func initBridge( "", gasLimit, consensusThreshold, + zcnbridge.BancorAPIURL, ethereumClient, transactionProvider, keyStore, diff --git a/wasmsdk/proxy.go b/wasmsdk/proxy.go index 1b298f53f..24486694d 100644 --- a/wasmsdk/proxy.go +++ b/wasmsdk/proxy.go @@ -224,9 +224,7 @@ func main() { "executeSmartContract": executeSmartContract, "faucet": faucet, - //swap - "setSwapWallets": setSwapWallets, - "swapToken": swapToken, + // bridge "initBridge": initBridge, "burnZCN": burnZCN, "mintZCN": mintZCN, diff --git a/wasmsdk/swap.go b/wasmsdk/swap.go deleted file mode 100644 index a5bd4f944..000000000 --- a/wasmsdk/swap.go +++ /dev/null @@ -1,26 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package main - -import ( - "fmt" - - "github.com/0chain/gosdk/zcnswap" - "github.com/0chain/gosdk/zcnswap/config" -) - -func setSwapWallets(usdcTokenAddress, bancorAddress, zcnTokenAddress, ethWalletMnemonic string) { - config.Configuration = config.SwapConfig{ - UsdcTokenAddress: usdcTokenAddress, - BancorAddress: bancorAddress, - ZcnTokenAddress: zcnTokenAddress, - WalletMnemonic: ethWalletMnemonic, - } - - fmt.Println("[swap]wallets are initialized") -} - -func swapToken(swapAmount int64, tokenSource string) (string, error) { - return zcnswap.Swap(swapAmount, tokenSource) -} diff --git a/zcnbridge/bridge.go b/zcnbridge/bridge.go index b4a47358b..00d18bf5b 100644 --- a/zcnbridge/bridge.go +++ b/zcnbridge/bridge.go @@ -3,19 +3,24 @@ package zcnbridge import ( "context" "encoding/hex" + "encoding/json" "fmt" + "github.com/0chain/common/core/currency" + "github.com/0chain/gosdk/zcnbridge/ethereum/bancor" + "github.com/0chain/gosdk/zcnbridge/ethereum/token" + h "github.com/0chain/gosdk/zcnbridge/http" + hdw "github.com/0chain/gosdk/zcncore/ethhdwallet" + "github.com/spf13/viper" + "io" "math/big" "os" + "strconv" "time" - hdw "github.com/0chain/gosdk/zcncore/ethhdwallet" - "github.com/spf13/viper" - "github.com/0chain/gosdk/core/logger" "github.com/0chain/gosdk/zcnbridge/ethereum" "github.com/0chain/gosdk/zcnbridge/ethereum/authorizers" - binding "github.com/0chain/gosdk/zcnbridge/ethereum/bridge" - "github.com/0chain/gosdk/zcnbridge/ethereum/erc20" + "github.com/0chain/gosdk/zcnbridge/ethereum/bridge" "github.com/0chain/gosdk/zcnbridge/ethereum/nftconfig" "github.com/0chain/gosdk/zcnbridge/log" "github.com/0chain/gosdk/zcncore" @@ -33,10 +38,6 @@ import ( "go.uber.org/zap" ) -type ( - Wei int64 -) - var Logger logger.Logger var defaultLogLevel = logger.DEBUG @@ -70,6 +71,7 @@ func (b *BridgeClient) CreateSignedTransactionFromKeyStore(client EthereumClient signer := accounts.Account{ Address: signerAddress, } + signerAcc, err := b.keyStore.Find(signer) if err != nil { Logger.Fatal(errors.Wrapf(err, "signer: %s", signerAddress.Hex())) @@ -107,48 +109,6 @@ func (b *BridgeClient) CreateSignedTransactionFromKeyStore(client EthereumClient return opts } -func (b *BridgeClient) prepareAuthorizers(ctx context.Context, method string, params ...interface{}) (*authorizers.Authorizers, *bind.TransactOpts, error) { - // To (contract) - contractAddress := common.HexToAddress(b.AuthorizersAddress) - - // Get ABI of the contract - abi, err := authorizers.AuthorizersMetaData.GetAbi() - if err != nil { - return nil, nil, errors.Wrap(err, "failed to get ABI") - } - - // Pack the method argument - pack, err := abi.Pack(method, params...) - if err != nil { - return nil, nil, errors.Wrap(err, "failed to pack arguments") - } - - from := common.HexToAddress(b.EthereumAddress) - - // Gas limits in units - gasLimitUnits, err := b.ethereumClient.EstimateGas(ctx, eth.CallMsg{ - To: &contractAddress, - From: from, - Data: pack, - }) - if err != nil { - return nil, nil, errors.Wrap(err, "failed to estimate gas") - } - - // Update gas limits + 10% - gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() - - transactOpts := b.CreateSignedTransactionFromKeyStore(b.ethereumClient, gasLimitUnits) - - // Authorizers instance - authorizersInstance, err := authorizers.NewAuthorizers(contractAddress, b.ethereumClient) - if err != nil { - return nil, nil, errors.Wrap(err, "failed to create authorizers instance") - } - - return authorizersInstance, transactOpts, nil -} - // AddEthereumAuthorizer Adds authorizer to Ethereum bridge. Only contract deployer can call this method func (b *BridgeClient) AddEthereumAuthorizer(ctx context.Context, address common.Address) (*types.Transaction, error) { instance, transactOpts, err := b.prepareAuthorizers(ctx, "addAuthorizers", address) @@ -367,17 +327,17 @@ func (b *BridgeClient) NFTConfigGetAddress(ctx context.Context, key string) (str } // IncreaseBurnerAllowance Increases allowance for bridge contract address to transfer -// WZCN tokens on behalf of the token owner to the Burn TokenPool +// ERC-20 tokens on behalf of the token owner to the Burn TokenPool // During the burn the script transfers amount from token owner to the bridge burn token pool // Example: owner wants to burn some amount. // The contract will transfer some amount from owner address to the pool. // So the owner must call IncreaseAllowance of the WZCN token with 2 parameters: // spender address which is the bridge contract and amount to be burned (transferred) -// ERC20 signature: "increaseAllowance(address,uint256)" +// Token signature: "increaseApproval(address,uint256)" // //nolint:funlen -func (b *BridgeClient) IncreaseBurnerAllowance(ctx context.Context, amountWei Wei) (*types.Transaction, error) { - if amountWei <= 0 { +func (b *BridgeClient) IncreaseBurnerAllowance(ctx context.Context, allowanceAmount uint64) (*types.Transaction, error) { + if allowanceAmount <= 0 { return nil, errors.New("amount must be greater than zero") } @@ -385,60 +345,36 @@ func (b *BridgeClient) IncreaseBurnerAllowance(ctx context.Context, amountWei We spenderAddress := common.HexToAddress(b.BridgeAddress) // 2. Data Parameter (amount) - amount := big.NewInt(int64(amountWei)) + amount := big.NewInt(int64(allowanceAmount)) tokenAddress := common.HexToAddress(b.TokenAddress) - fromAddress := common.HexToAddress(b.EthereumAddress) - - abi, err := erc20.ERC20MetaData.GetAbi() - if err != nil { - return nil, errors.Wrap(err, "failed to get erc20 abi") - } - pack, err := abi.Pack("increaseAllowance", spenderAddress, amount) + tokenInstance, transactOpts, err := b.prepareToken(ctx, "increaseApproval", tokenAddress, spenderAddress, amount) if err != nil { - return nil, errors.Wrap(err, "failed to pack arguments") - } - - gasLimitUnits, err := b.ethereumClient.EstimateGas(ctx, eth.CallMsg{ - To: &tokenAddress, - From: fromAddress, - Data: pack, - }) - if err != nil { - return nil, errors.Wrap(err, "failed to estimate gas limit") - } - - gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() - - transactOpts := b.CreateSignedTransactionFromKeyStore(b.ethereumClient, gasLimitUnits) - - wzcnTokenInstance, err := erc20.NewERC20(tokenAddress, b.ethereumClient) - if err != nil { - return nil, errors.Wrap(err, "failed to initialize WZCN-ERC20 instance") + return nil, errors.Wrap(err, "failed to prepare token") } Logger.Info( - "Starting IncreaseAllowance", + "Starting IncreaseApproval", zap.String("token", tokenAddress.String()), zap.String("spender", spenderAddress.String()), zap.Int64("amount", amount.Int64()), ) - tran, err := wzcnTokenInstance.IncreaseAllowance(transactOpts, spenderAddress, amount) + tran, err := tokenInstance.IncreaseApproval(transactOpts, spenderAddress, amount) if err != nil { Logger.Error( - "IncreaseAllowance FAILED", + "IncreaseApproval FAILED", zap.String("token", tokenAddress.String()), zap.String("spender", spenderAddress.String()), zap.Int64("amount", amount.Int64()), zap.Error(err)) - return nil, errors.Wrapf(err, "failed to send `IncreaseAllowance` transaction") + return nil, errors.Wrapf(err, "failed to send `IncreaseApproval` transaction") } Logger.Info( - "Posted IncreaseAllowance", + "Posted IncreaseApproval", zap.String("hash", tran.Hash().String()), zap.String("token", tokenAddress.String()), zap.String("spender", spenderAddress.String()), @@ -448,17 +384,20 @@ func (b *BridgeClient) IncreaseBurnerAllowance(ctx context.Context, amountWei We return tran, nil } -// GetBalance returns balance of the current client -func (b *BridgeClient) GetBalance() (*big.Int, error) { - tokenAddress := common.HexToAddress(b.TokenAddress) - fromAddress := common.HexToAddress(b.EthereumAddress) +// GetTokenBalance returns balance of the current client for the token address +func (b *BridgeClient) GetTokenBalance() (*big.Int, error) { + // 1. Token address parameter + of := common.HexToAddress(b.TokenAddress) - wzcnTokenInstance, err := erc20.NewERC20(tokenAddress, b.ethereumClient) + // 2. User's Ethereum wallet address parameter + from := common.HexToAddress(b.EthereumAddress) + + tokenInstance, err := token.NewToken(of, b.ethereumClient) if err != nil { - return nil, errors.Wrap(err, "failed to initialize WZCN-ERC20 instance") + return nil, errors.Wrap(err, "failed to initialize token instance") } - wei, err := wzcnTokenInstance.BalanceOf(&bind.CallOpts{}, fromAddress) + wei, err := tokenInstance.BalanceOf(&bind.CallOpts{}, from) if err != nil { return nil, errors.Wrapf(err, "failed to call `BalanceOf` for %s", b.EthereumAddress) } @@ -502,8 +441,8 @@ func (b *BridgeClient) GetUserNonceMinted(ctx context.Context, rawEthereumAddres contractAddress := common.HexToAddress(b.BridgeAddress) - var bridgeInstance *binding.Bridge - bridgeInstance, err := binding.NewBridge(contractAddress, b.ethereumClient) + var bridgeInstance *bridge.Bridge + bridgeInstance, err := bridge.NewBridge(contractAddress, b.ethereumClient) if err != nil { return nil, errors.Wrap(err, "failed to create bridge instance") } @@ -697,12 +636,209 @@ func (b *BridgeClient) BurnZCN(ctx context.Context, amount, txnfee uint64) (tran return trx, nil } -func (b *BridgeClient) prepareBridge(ctx context.Context, ethereumAddress, method string, params ...interface{}) (*binding.Bridge, *bind.TransactOpts, error) { +// FetchZCNToETHRate retrieves latest ZCN to ETH rate using Bancor API +func (b *BridgeClient) FetchZCNToETHRate() (*big.Float, error) { + client = h.CleanClient() + + resp, err := client.Get(fmt.Sprintf("%s/tokens?dlt_id=%s", b.BancorAPIURL, b.TokenAddress)) + if err != nil { + return nil, err + } + + var body []byte + body, err = io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + var bancorTokenDetails *BancorTokenDetails + err = json.Unmarshal(body, &bancorTokenDetails) + if err != nil { + return nil, err + } + + var zcnEthRateFloat float64 + zcnEthRateFloat, err = strconv.ParseFloat(bancorTokenDetails.Data.Rate.ETH, 64) + if err != nil { + return nil, err + } + + return big.NewFloat(zcnEthRateFloat), nil +} + +// Swap provides opportunity to perform token swap operation. +func (b *BridgeClient) Swap(ctx context.Context, amountSwap uint64, deadlinePeriod time.Time) (*types.Transaction, error) { + // 1. Swap amount parameter. + amount := big.NewInt(int64(amountSwap)) + + // 2. User's Ethereum wallet address. + beneficiary := common.HexToAddress(b.EthereumAddress) + + // 3. Trade deadline + deadline := big.NewInt(deadlinePeriod.Unix()) + + amountSwapZCN, err := currency.Coin(amountSwap).ToZCN() + if err != nil { + return nil, errors.Wrap(err, "failed to convert current token balance to ZCN") + } + + var zcnEthRate *big.Float + zcnEthRate, err = b.FetchZCNToETHRate() + if err != nil { + return nil, errors.Wrap(err, "failed to retrieve ZCN to ETH rate using Bancor API") + } + + zcnEthRateFloat, _ := zcnEthRate.Float64() + + // 4. Max trade token amount + maxAmount := big.NewInt(int64(amountSwapZCN * zcnEthRateFloat * 1.5 * 1e18)) + + // 5. Source token address parameter + from := common.HexToAddress(SourceTokenAddress) + + // 6. Target token address parameter + to := common.HexToAddress(b.TokenAddress) + + bancorInstance, transactOpts, err := b.prepareBancor(ctx, maxAmount, "tradeByTargetAmount", from, to, amount, maxAmount, deadline, beneficiary) + if err != nil { + return nil, errors.Wrap(err, "failed to prepare bancor") + } + + Logger.Info( + "Starting Swap", + zap.Int64("amount", amount.Int64()), + zap.String("sourceToken", SourceTokenAddress), + ) + + tran, err := bancorInstance.TradeByTargetAmount(transactOpts, from, to, amount, maxAmount, deadline, beneficiary) + if err != nil { + return nil, errors.Wrap(err, "failed to execute ConvertByPath transaction") + } + + return tran, nil +} + +func (b *BridgeClient) prepareBancor(ctx context.Context, value *big.Int, method string, params ...interface{}) (*bancor.Bancor, *bind.TransactOpts, error) { + // 1. Bancor network smart contract address + contractAddress := common.HexToAddress(BancorNetworkAddress) + + abi, err := bancor.BancorMetaData.GetAbi() + if err != nil { + return nil, nil, errors.Wrap(err, "failed to get bancor abi") + } + + pack, err := abi.Pack(method, params...) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to pack arguments") + } + + from := common.HexToAddress(b.EthereumAddress) + + gasLimitUnits, err := b.ethereumClient.EstimateGas(ctx, eth.CallMsg{ + To: &contractAddress, + From: from, + Data: pack, + Value: value, + }) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to estimate gas limit") + } + + gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() + + transactOpts := b.CreateSignedTransactionFromKeyStore(b.ethereumClient, gasLimitUnits) + transactOpts.Value = value + + bancorInstance, err := bancor.NewBancor(contractAddress, b.ethereumClient) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to initialize bancor instance") + } + + return bancorInstance, transactOpts, nil +} + +func (b *BridgeClient) prepareToken(ctx context.Context, method string, tokenAddress common.Address, params ...interface{}) (*token.Token, *bind.TransactOpts, error) { + abi, err := token.TokenMetaData.GetAbi() + if err != nil { + return nil, nil, errors.Wrap(err, "failed to get token abi") + } + + pack, err := abi.Pack(method, params...) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to pack arguments") + } + + from := common.HexToAddress(b.EthereumAddress) + + gasLimitUnits, err := b.ethereumClient.EstimateGas(ctx, eth.CallMsg{ + To: &tokenAddress, + From: from, + Data: pack, + }) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to estimate gas limit") + } + + gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() + + transactOpts := b.CreateSignedTransactionFromKeyStore(b.ethereumClient, gasLimitUnits) + + tokenInstance, err := token.NewToken(tokenAddress, b.ethereumClient) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to initialize token instance") + } + + return tokenInstance, transactOpts, nil +} + +func (b *BridgeClient) prepareAuthorizers(ctx context.Context, method string, params ...interface{}) (*authorizers.Authorizers, *bind.TransactOpts, error) { + // To (contract) + contractAddress := common.HexToAddress(b.AuthorizersAddress) + + // Get ABI of the contract + abi, err := authorizers.AuthorizersMetaData.GetAbi() + if err != nil { + return nil, nil, errors.Wrap(err, "failed to get ABI") + } + + // Pack the method argument + pack, err := abi.Pack(method, params...) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to pack arguments") + } + + from := common.HexToAddress(b.EthereumAddress) + + // Gas limits in units + gasLimitUnits, err := b.ethereumClient.EstimateGas(ctx, eth.CallMsg{ + To: &contractAddress, + From: from, + Data: pack, + }) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to estimate gas") + } + + // Update gas limits + 10% + gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() + + transactOpts := b.CreateSignedTransactionFromKeyStore(b.ethereumClient, gasLimitUnits) + + // Authorizers instance + authorizersInstance, err := authorizers.NewAuthorizers(contractAddress, b.ethereumClient) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to create authorizers instance") + } + + return authorizersInstance, transactOpts, nil +} + +func (b *BridgeClient) prepareBridge(ctx context.Context, ethereumAddress, method string, params ...interface{}) (*bridge.Bridge, *bind.TransactOpts, error) { // To (contract) contractAddress := common.HexToAddress(b.BridgeAddress) //Get ABI of the contract - abi, err := binding.BridgeMetaData.GetAbi() + abi, err := bridge.BridgeMetaData.GetAbi() if err != nil { return nil, nil, errors.Wrap(err, "failed to get ABI") } @@ -731,7 +867,7 @@ func (b *BridgeClient) prepareBridge(ctx context.Context, ethereumAddress, metho transactOpts := b.CreateSignedTransactionFromKeyStore(b.ethereumClient, gasLimitUnits) // BridgeClient instance - bridgeInstance, err := binding.NewBridge(contractAddress, b.ethereumClient) + bridgeInstance, err := bridge.NewBridge(contractAddress, b.ethereumClient) if err != nil { return nil, nil, errors.Wrap(err, "failed to create bridge instance") } diff --git a/zcnbridge/bridge_helper.go b/zcnbridge/bridge_helper.go index ffa7c25be..d68b5a0b1 100644 --- a/zcnbridge/bridge_helper.go +++ b/zcnbridge/bridge_helper.go @@ -10,6 +10,15 @@ import ( "github.com/pkg/errors" ) +// BancorTokenDetails describes Bancor ZCN token pool details +type BancorTokenDetails struct { + Data struct { + Rate struct { + ETH string `json:"eth"` + } + } `json:"data"` +} + func GetTransactionStatus(hash string) (int, error) { _, err := zcncore.GetEthClient() if err != nil { diff --git a/zcnbridge/bridge_test.go b/zcnbridge/bridge_test.go index 873390e43..3890c777d 100644 --- a/zcnbridge/bridge_test.go +++ b/zcnbridge/bridge_test.go @@ -3,11 +3,19 @@ package zcnbridge import ( "context" "encoding/json" + "fmt" + "github.com/0chain/common/core/currency" + "github.com/0chain/gosdk/zcnbridge/ethereum/bancor" + "github.com/0chain/gosdk/zcnbridge/ethereum/token" "log" "math/big" + "net/http" + "net/http/httptest" "os" + "os/signal" "path" "strconv" + "syscall" "testing" "time" @@ -15,7 +23,6 @@ import ( "github.com/0chain/gosdk/zcnbridge/ethereum" "github.com/0chain/gosdk/zcnbridge/ethereum/authorizers" binding "github.com/0chain/gosdk/zcnbridge/ethereum/bridge" - "github.com/0chain/gosdk/zcnbridge/ethereum/erc20" bridgemocks "github.com/0chain/gosdk/zcnbridge/mocks" "github.com/0chain/gosdk/zcnbridge/transaction" transactionmocks "github.com/0chain/gosdk/zcnbridge/transaction/mocks" @@ -38,11 +45,13 @@ const ( authorizerDelegatedAddress = "0xa149B58b7e1390D152383BB03dBc79B390F648e2" bridgeAddress = "0x7bbbEa24ac1751317D7669f05558632c4A9113D7" - tokenAddress = "0x2ec8F26ccC678c9faF0Df20208aEE3AF776160CD" + tokenAddress = "0xb9EF770B6A5e12E45983C5D80545258aA38F3B78" authorizersAddress = "0xEAe8229c0E457efBA1A1769e7F8c20110fF68E61" + sourceAddress = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE" + zcnTxnID = "b26abeb31fcee5d2e75b26717722938a06fa5ce4a5b5e68ddad68357432caace" - amount = 1e10 + amount = 1 txnFee = 1 nonce = 1 @@ -208,7 +217,7 @@ func getEthereumClient(t mock.TestingT) *bridgemocks.EthereumClient { return bridgemocks.NewEthereumClient(ðereumClientMock{t}) } -func getBridgeClient(ethereumClient EthereumClient, transactionProvider transaction.TransactionProvider, keyStore KeyStore) *BridgeClient { +func getBridgeClient(bancorAPIURL string, ethereumClient EthereumClient, transactionProvider transaction.TransactionProvider, keyStore KeyStore) *BridgeClient { cfg := viper.New() tempConfigFile, err := os.CreateTemp(".", "config.yaml") @@ -216,7 +225,12 @@ func getBridgeClient(ethereumClient EthereumClient, transactionProvider transact log.Fatalln(err) } - defer os.Remove(tempConfigFile.Name()) + defer func(name string) { + err := os.Remove(name) + if err != nil { + log.Fatalln(err) + } + }(tempConfigFile.Name()) cfg.SetConfigFile(tempConfigFile.Name()) @@ -236,6 +250,7 @@ func getBridgeClient(ethereumClient EthereumClient, transactionProvider transact cfg.GetString("bridge.password"), cfg.GetUint64("bridge.gas_limit"), cfg.GetFloat64("bridge.consensus_threshold"), + bancorAPIURL, ethereumClient, transactionProvider, keyStore, @@ -288,20 +303,54 @@ func prepareKeyStoreGeneralMockCalls(keyStore *bridgemocks.KeyStore) { keyStore.On("GetEthereumKeyStore").Return(ks) } +func prepareBancorMockServer() string { + ts := httptest.NewServer( + http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, err := fmt.Fprintln(w, `{"data":{"dltId":"0xb9EF770B6A5e12E45983C5D80545258aA38F3B78","symbol":"ZCN","decimals":10,"rate":{"bnt":"0.175290404525335519","usd":"0.100266","eur":"0.094499","eth":"1"},"rate24hAgo":{"bnt":"0.175290404525335519","usd":"0.100266","eur":"0.094499","eth":"0.000064086171894462"}},"timestamp":{"ethereum":{"block":18333798,"timestamp":1697107211}}}`) + if err != nil { + log.Fatalln(err) + } + })) + + sigs := make(chan os.Signal, 1) + + signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) + + go func() { + load := time.NewTicker(time.Millisecond * 500) + + for range load.C { + select { + case <-sigs: + load.Stop() + + ts.Close() + + close(sigs) + default: + } + } + }() + + return ts.URL +} + func Test_ZCNBridge(t *testing.T) { ethereumClient := getEthereumClient(t) prepareEthereumClientGeneralMockCalls(ðereumClient.Mock) - transaction := getTransaction(t) - prepareTransactionGeneralMockCalls(&transaction.Mock) + tx := getTransaction(t) + prepareTransactionGeneralMockCalls(&tx.Mock) transactionProvider := getTransactionProvider(t) - prepareTransactionProviderGeneralMockCalls(&transactionProvider.Mock, transaction) + prepareTransactionProviderGeneralMockCalls(&transactionProvider.Mock, tx) keyStore := getKeyStore(t) prepareKeyStoreGeneralMockCalls(keyStore) - bridgeClient := getBridgeClient(ethereumClient, transactionProvider, keyStore) + bancorMockServerURL := prepareBancorMockServer() + + bridgeClient := getBridgeClient(bancorMockServerURL, ethereumClient, transactionProvider, keyStore) t.Run("should update authorizer config.", func(t *testing.T) { source := &authorizerNodeSource{ @@ -401,7 +450,7 @@ func Test_ZCNBridge(t *testing.T) { _, err := bridgeClient.MintZCN(context.Background(), payload) require.NoError(t, err) - require.True(t, transaction.AssertCalled( + require.True(t, tx.AssertCalled( t, "ExecuteSmartContract", context.Background(), @@ -416,7 +465,7 @@ func Test_ZCNBridge(t *testing.T) { _, err := bridgeClient.BurnZCN(context.Background(), amount, txnFee) require.NoError(t, err) - require.True(t, transaction.AssertCalled( + require.True(t, tx.AssertCalled( t, "ExecuteSmartContract", context.Background(), @@ -488,10 +537,10 @@ func Test_ZCNBridge(t *testing.T) { to := common.HexToAddress(tokenAddress) fromAddress := common.HexToAddress(ethereumAddress) - abi, err := erc20.ERC20MetaData.GetAbi() + abi, err := token.TokenMetaData.GetAbi() require.NoError(t, err) - pack, err := abi.Pack("increaseAllowance", spenderAddress, big.NewInt(amount)) + pack, err := abi.Pack("increaseApproval", spenderAddress, big.NewInt(amount)) require.NoError(t, err) require.True(t, ethereumClient.AssertCalled( @@ -506,6 +555,56 @@ func Test_ZCNBridge(t *testing.T) { )) }) + t.Run("should check configuration used by Swap", func(t *testing.T) { + // 1. Predefined deadline period + deadlinePeriod := time.Date(2009, 11, 17, 20, 34, 58, 651387237, time.UTC) + + _, err := bridgeClient.Swap(context.Background(), amount, deadlinePeriod) + require.NoError(t, err) + + // 1. Trade deadline + deadline := big.NewInt(deadlinePeriod.Unix()) + + // 2. Swap amount parameter + amount := big.NewInt(amount) + + // 3. User's Ethereum wallet address. + beneficiary := common.HexToAddress(ethereumAddress) + + // 4. Source token address parameter + from := common.HexToAddress(sourceAddress) + + // 5. Target token address parameter + to := common.HexToAddress(tokenAddress) + + amountZCN, err := currency.Coin(amount.Int64()).ToZCN() + require.NoError(t, err) + + // 6. Max trade token amount + maxAmount := big.NewInt(int64(amountZCN * 1.5 * 1e18)) + + // 7. Bancor network smart contract address + contractAddress := common.HexToAddress(BancorNetworkAddress) + + abi, err := bancor.BancorMetaData.GetAbi() + require.NoError(t, err) + + pack, err := abi.Pack("tradeByTargetAmount", from, to, amount, maxAmount, deadline, beneficiary) + require.NoError(t, err) + + require.True(t, ethereumClient.AssertCalled( + t, + "EstimateGas", + context.Background(), + eth.CallMsg{ + To: &contractAddress, + From: beneficiary, + Data: pack, + Value: maxAmount, + }, + )) + }) + t.Run("should check configuration used by CreateSignedTransactionFromKeyStore", func(t *testing.T) { bridgeClient.CreateSignedTransactionFromKeyStore(ethereumClient, 400000) diff --git a/zcnbridge/config.go b/zcnbridge/config.go index 8696bf3bf..5ce608971 100644 --- a/zcnbridge/config.go +++ b/zcnbridge/config.go @@ -3,12 +3,12 @@ package zcnbridge import ( "context" "fmt" + "github.com/ethereum/go-ethereum/accounts/abi/bind" "math/big" "path" "github.com/0chain/gosdk/zcnbridge/log" "github.com/0chain/gosdk/zcnbridge/transaction" - "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/viper" @@ -20,6 +20,13 @@ const ( EthereumWalletStorageDir = "wallets" ) +const ( + BancorNetworkAddress = "0xeEF417e1D5CC832e619ae18D2F140De2999dD4fB" + SourceTokenAddress = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE" +) + +const BancorAPIURL = "https://api-v3.bancor.network" + type BridgeSDKConfig struct { LogLevel *string LogPath *string @@ -47,12 +54,25 @@ type BridgeClient struct { EthereumAddress, Password string + BancorAPIURL string + ConsensusThreshold float64 GasLimit uint64 } // NewBridgeClient creates BridgeClient with the given parameters. -func NewBridgeClient(bridgeAddress, tokenAddress, authorizersAddress, ethereumAddress, password string, gasLimit uint64, consensusThreshold float64, ethereumClient EthereumClient, transactionProvider transaction.TransactionProvider, keyStore KeyStore) *BridgeClient { +func NewBridgeClient( + bridgeAddress, + tokenAddress, + authorizersAddress, + ethereumAddress, + password string, + gasLimit uint64, + consensusThreshold float64, + bancorAPIURL string, + ethereumClient EthereumClient, + transactionProvider transaction.TransactionProvider, + keyStore KeyStore) *BridgeClient { return &BridgeClient{ BridgeAddress: bridgeAddress, TokenAddress: tokenAddress, @@ -61,6 +81,7 @@ func NewBridgeClient(bridgeAddress, tokenAddress, authorizersAddress, ethereumAd Password: password, GasLimit: gasLimit, ConsensusThreshold: consensusThreshold, + BancorAPIURL: bancorAPIURL, ethereumClient: ethereumClient, transactionProvider: transactionProvider, keyStore: keyStore, @@ -118,6 +139,7 @@ func SetupBridgeClientSDK(cfg *BridgeSDKConfig) *BridgeClient { chainCfg.GetString("bridge.password"), chainCfg.GetUint64("bridge.gas_limit"), chainCfg.GetFloat64("bridge.consensus_threshold"), + BancorAPIURL, ethereumClient, transactionProvider, keyStore, diff --git a/zcnbridge/ethereum/bancor/bancor.go b/zcnbridge/ethereum/bancor/bancor.go new file mode 100755 index 000000000..75372aa43 --- /dev/null +++ b/zcnbridge/ethereum/bancor/bancor.go @@ -0,0 +1,3757 @@ +// Code generated - DO NOT EDIT. +// This file is a generated binding and any manual changes will be lost. + +package bancor + +import ( + "errors" + "math/big" + "strings" + + ethereum "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/event" +) + +// Reference imports to suppress errors if they are not otherwise used. +var ( + _ = errors.New + _ = big.NewInt + _ = strings.NewReader + _ = ethereum.NotFound + _ = bind.Bind + _ = common.Big1 + _ = types.BloomLookup + _ = event.NewSubscription + _ = abi.ConvertType +) + +// BancorMetaData contains all meta data concerning the Bancor contract. +var BancorMetaData = &bind.MetaData{ + ABI: "[{\"inputs\":[{\"internalType\":\"contractITokenGovernance\",\"name\":\"initBNTGovernance\",\"type\":\"address\"},{\"internalType\":\"contractITokenGovernance\",\"name\":\"initVBNTGovernance\",\"type\":\"address\"},{\"internalType\":\"contractINetworkSettings\",\"name\":\"initNetworkSettings\",\"type\":\"address\"},{\"internalType\":\"contractIMasterVault\",\"name\":\"initMasterVault\",\"type\":\"address\"},{\"internalType\":\"contractIExternalProtectionVault\",\"name\":\"initExternalProtectionVault\",\"type\":\"address\"},{\"internalType\":\"contractIPoolToken\",\"name\":\"initBNTPoolToken\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"bancorArbitrage\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"carbonPOL\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"inputs\":[],\"name\":\"AccessDenied\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"AlreadyExists\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"AlreadyInitialized\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"DeadlineExpired\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"DepositingDisabled\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"DoesNotExist\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InsufficientFlashLoanReturn\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidAddress\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidFee\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidPool\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidToken\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"NativeTokenAmountMismatch\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"NotEmpty\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"NotWhitelisted\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"NotWhitelistedForPOL\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"Overflow\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"PoolNotInSurplus\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"ZeroValue\",\"type\":\"error\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"contractToken\",\"name\":\"token\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"borrower\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"feeAmount\",\"type\":\"uint256\"}],\"name\":\"FlashLoanCompleted\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"contextId\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"contractToken\",\"name\":\"token\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"provider\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"availableAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"originalAmount\",\"type\":\"uint256\"}],\"name\":\"FundsMigrated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"caller\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"NetworkFeesWithdrawn\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint32\",\"name\":\"oldRewardsPPM\",\"type\":\"uint32\"},{\"indexed\":false,\"internalType\":\"uint32\",\"name\":\"newRewardsPPM\",\"type\":\"uint32\"}],\"name\":\"POLRewardsPPMUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"caller\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"polTokenAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"userReward\",\"type\":\"uint256\"}],\"name\":\"POLWithdrawn\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"Paused\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"contractToken\",\"name\":\"pool\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"contractIPoolCollection\",\"name\":\"poolCollection\",\"type\":\"address\"}],\"name\":\"PoolAdded\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"uint16\",\"name\":\"poolType\",\"type\":\"uint16\"},{\"indexed\":true,\"internalType\":\"contractIPoolCollection\",\"name\":\"poolCollection\",\"type\":\"address\"}],\"name\":\"PoolCollectionAdded\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"uint16\",\"name\":\"poolType\",\"type\":\"uint16\"},{\"indexed\":true,\"internalType\":\"contractIPoolCollection\",\"name\":\"poolCollection\",\"type\":\"address\"}],\"name\":\"PoolCollectionRemoved\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"contractToken\",\"name\":\"pool\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"contractIPoolCollection\",\"name\":\"poolCollection\",\"type\":\"address\"}],\"name\":\"PoolCreated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"contractToken\",\"name\":\"pool\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"contractIPoolCollection\",\"name\":\"poolCollection\",\"type\":\"address\"}],\"name\":\"PoolRemoved\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"previousAdminRole\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"newAdminRole\",\"type\":\"bytes32\"}],\"name\":\"RoleAdminChanged\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"}],\"name\":\"RoleGranted\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"}],\"name\":\"RoleRevoked\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"contextId\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"contractToken\",\"name\":\"sourceToken\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"contractToken\",\"name\":\"targetToken\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"sourceAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"targetAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"bntAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"targetFeeAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"bntFeeAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"trader\",\"type\":\"address\"}],\"name\":\"TokensTraded\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"Unpaused\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"DEFAULT_ADMIN_ROLE\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"id\",\"type\":\"uint256\"}],\"name\":\"cancelWithdrawal\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"pool\",\"type\":\"address\"}],\"name\":\"collectionByPool\",\"outputs\":[{\"internalType\":\"contractIPoolCollection\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken[]\",\"name\":\"tokens\",\"type\":\"address[]\"},{\"internalType\":\"contractIPoolCollection\",\"name\":\"poolCollection\",\"type\":\"address\"}],\"name\":\"createPools\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"pool\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenAmount\",\"type\":\"uint256\"}],\"name\":\"deposit\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"provider\",\"type\":\"address\"},{\"internalType\":\"contractToken\",\"name\":\"pool\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenAmount\",\"type\":\"uint256\"}],\"name\":\"depositFor\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"depositingEnabled\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bool\",\"name\":\"status\",\"type\":\"bool\"}],\"name\":\"enableDepositing\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"internalType\":\"contractIFlashLoanRecipient\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"flashLoan\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"}],\"name\":\"getRoleAdmin\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"uint256\",\"name\":\"index\",\"type\":\"uint256\"}],\"name\":\"getRoleMember\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"}],\"name\":\"getRoleMemberCount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"grantRole\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"hasRole\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractIPoolToken\",\"name\":\"poolToken\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"poolTokenAmount\",\"type\":\"uint256\"}],\"name\":\"initWithdrawal\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractIBNTPool\",\"name\":\"initBNTPool\",\"type\":\"address\"},{\"internalType\":\"contractIPendingWithdrawals\",\"name\":\"initPendingWithdrawals\",\"type\":\"address\"},{\"internalType\":\"contractIPoolMigrator\",\"name\":\"initPoolMigrator\",\"type\":\"address\"}],\"name\":\"initialize\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"liquidityPools\",\"outputs\":[{\"internalType\":\"contractToken[]\",\"name\":\"\",\"type\":\"address[]\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"provider\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"availableAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"originalAmount\",\"type\":\"uint256\"}],\"name\":\"migrateLiquidity\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken[]\",\"name\":\"pools\",\"type\":\"address[]\"},{\"internalType\":\"contractIPoolCollection\",\"name\":\"newPoolCollection\",\"type\":\"address\"}],\"name\":\"migratePools\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"pause\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"paused\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"pendingNetworkFeeAmount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"polRewardsPPM\",\"outputs\":[{\"internalType\":\"uint32\",\"name\":\"\",\"type\":\"uint32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"poolCollections\",\"outputs\":[{\"internalType\":\"contractIPoolCollection[]\",\"name\":\"\",\"type\":\"address[]\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"postUpgrade\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractIPoolCollection\",\"name\":\"newPoolCollection\",\"type\":\"address\"}],\"name\":\"registerPoolCollection\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"renounceRole\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"resume\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"revokeRole\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"roleAdmin\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"roleEmergencyStopper\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"roleMigrationManager\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"roleNetworkFeeManager\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint32\",\"name\":\"newRewardsPPM\",\"type\":\"uint32\"}],\"name\":\"setPOLRewardsPPM\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes4\",\"name\":\"interfaceId\",\"type\":\"bytes4\"}],\"name\":\"supportsInterface\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"sourceToken\",\"type\":\"address\"},{\"internalType\":\"contractToken\",\"name\":\"targetToken\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"sourceAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"minReturnAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"beneficiary\",\"type\":\"address\"}],\"name\":\"tradeBySourceAmount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"sourceToken\",\"type\":\"address\"},{\"internalType\":\"contractToken\",\"name\":\"targetToken\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"sourceAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"minReturnAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"beneficiary\",\"type\":\"address\"}],\"name\":\"tradeBySourceAmountArb\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"sourceToken\",\"type\":\"address\"},{\"internalType\":\"contractToken\",\"name\":\"targetToken\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"targetAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"maxSourceAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"beneficiary\",\"type\":\"address\"}],\"name\":\"tradeByTargetAmount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"sourceToken\",\"type\":\"address\"},{\"internalType\":\"contractToken\",\"name\":\"targetToken\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"targetAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"maxSourceAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"beneficiary\",\"type\":\"address\"}],\"name\":\"tradeByTargetAmountArb\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractIPoolCollection\",\"name\":\"poolCollection\",\"type\":\"address\"}],\"name\":\"unregisterPoolCollection\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"version\",\"outputs\":[{\"internalType\":\"uint16\",\"name\":\"\",\"type\":\"uint16\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"id\",\"type\":\"uint256\"}],\"name\":\"withdraw\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"}],\"name\":\"withdrawNetworkFees\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"pool\",\"type\":\"address\"}],\"name\":\"withdrawPOL\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"stateMutability\":\"payable\",\"type\":\"receive\"}]", +} + +// BancorABI is the input ABI used to generate the binding from. +// Deprecated: Use BancorMetaData.ABI instead. +var BancorABI = BancorMetaData.ABI + +// Bancor is an auto generated Go binding around an Ethereum contract. +type Bancor struct { + BancorCaller // Read-only binding to the contract + BancorTransactor // Write-only binding to the contract + BancorFilterer // Log filterer for contract events +} + +// BancorCaller is an auto generated read-only Go binding around an Ethereum contract. +type BancorCaller struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// BancorTransactor is an auto generated write-only Go binding around an Ethereum contract. +type BancorTransactor struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// BancorFilterer is an auto generated log filtering Go binding around an Ethereum contract events. +type BancorFilterer struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// BancorSession is an auto generated Go binding around an Ethereum contract, +// with pre-set call and transact options. +type BancorSession struct { + Contract *Bancor // Generic contract binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// BancorCallerSession is an auto generated read-only Go binding around an Ethereum contract, +// with pre-set call options. +type BancorCallerSession struct { + Contract *BancorCaller // Generic contract caller binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session +} + +// BancorTransactorSession is an auto generated write-only Go binding around an Ethereum contract, +// with pre-set transact options. +type BancorTransactorSession struct { + Contract *BancorTransactor // Generic contract transactor binding to set the session for + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// BancorRaw is an auto generated low-level Go binding around an Ethereum contract. +type BancorRaw struct { + Contract *Bancor // Generic contract binding to access the raw methods on +} + +// BancorCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. +type BancorCallerRaw struct { + Contract *BancorCaller // Generic read-only contract binding to access the raw methods on +} + +// BancorTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. +type BancorTransactorRaw struct { + Contract *BancorTransactor // Generic write-only contract binding to access the raw methods on +} + +// NewBancor creates a new instance of Bancor, bound to a specific deployed contract. +func NewBancor(address common.Address, backend bind.ContractBackend) (*Bancor, error) { + contract, err := bindBancor(address, backend, backend, backend) + if err != nil { + return nil, err + } + return &Bancor{BancorCaller: BancorCaller{contract: contract}, BancorTransactor: BancorTransactor{contract: contract}, BancorFilterer: BancorFilterer{contract: contract}}, nil +} + +// NewBancorCaller creates a new read-only instance of Bancor, bound to a specific deployed contract. +func NewBancorCaller(address common.Address, caller bind.ContractCaller) (*BancorCaller, error) { + contract, err := bindBancor(address, caller, nil, nil) + if err != nil { + return nil, err + } + return &BancorCaller{contract: contract}, nil +} + +// NewBancorTransactor creates a new write-only instance of Bancor, bound to a specific deployed contract. +func NewBancorTransactor(address common.Address, transactor bind.ContractTransactor) (*BancorTransactor, error) { + contract, err := bindBancor(address, nil, transactor, nil) + if err != nil { + return nil, err + } + return &BancorTransactor{contract: contract}, nil +} + +// NewBancorFilterer creates a new log filterer instance of Bancor, bound to a specific deployed contract. +func NewBancorFilterer(address common.Address, filterer bind.ContractFilterer) (*BancorFilterer, error) { + contract, err := bindBancor(address, nil, nil, filterer) + if err != nil { + return nil, err + } + return &BancorFilterer{contract: contract}, nil +} + +// bindBancor binds a generic wrapper to an already deployed contract. +func bindBancor(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { + parsed, err := BancorMetaData.GetAbi() + if err != nil { + return nil, err + } + return bind.NewBoundContract(address, *parsed, caller, transactor, filterer), nil +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_Bancor *BancorRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _Bancor.Contract.BancorCaller.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_Bancor *BancorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Bancor.Contract.BancorTransactor.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_Bancor *BancorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _Bancor.Contract.BancorTransactor.contract.Transact(opts, method, params...) +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_Bancor *BancorCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _Bancor.Contract.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_Bancor *BancorTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Bancor.Contract.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_Bancor *BancorTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _Bancor.Contract.contract.Transact(opts, method, params...) +} + +// DEFAULTADMINROLE is a free data retrieval call binding the contract method 0xa217fddf. +// +// Solidity: function DEFAULT_ADMIN_ROLE() view returns(bytes32) +func (_Bancor *BancorCaller) DEFAULTADMINROLE(opts *bind.CallOpts) ([32]byte, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "DEFAULT_ADMIN_ROLE") + + if err != nil { + return *new([32]byte), err + } + + out0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte) + + return out0, err + +} + +// DEFAULTADMINROLE is a free data retrieval call binding the contract method 0xa217fddf. +// +// Solidity: function DEFAULT_ADMIN_ROLE() view returns(bytes32) +func (_Bancor *BancorSession) DEFAULTADMINROLE() ([32]byte, error) { + return _Bancor.Contract.DEFAULTADMINROLE(&_Bancor.CallOpts) +} + +// DEFAULTADMINROLE is a free data retrieval call binding the contract method 0xa217fddf. +// +// Solidity: function DEFAULT_ADMIN_ROLE() view returns(bytes32) +func (_Bancor *BancorCallerSession) DEFAULTADMINROLE() ([32]byte, error) { + return _Bancor.Contract.DEFAULTADMINROLE(&_Bancor.CallOpts) +} + +// CollectionByPool is a free data retrieval call binding the contract method 0x9bca0e70. +// +// Solidity: function collectionByPool(address pool) view returns(address) +func (_Bancor *BancorCaller) CollectionByPool(opts *bind.CallOpts, pool common.Address) (common.Address, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "collectionByPool", pool) + + if err != nil { + return *new(common.Address), err + } + + out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) + + return out0, err + +} + +// CollectionByPool is a free data retrieval call binding the contract method 0x9bca0e70. +// +// Solidity: function collectionByPool(address pool) view returns(address) +func (_Bancor *BancorSession) CollectionByPool(pool common.Address) (common.Address, error) { + return _Bancor.Contract.CollectionByPool(&_Bancor.CallOpts, pool) +} + +// CollectionByPool is a free data retrieval call binding the contract method 0x9bca0e70. +// +// Solidity: function collectionByPool(address pool) view returns(address) +func (_Bancor *BancorCallerSession) CollectionByPool(pool common.Address) (common.Address, error) { + return _Bancor.Contract.CollectionByPool(&_Bancor.CallOpts, pool) +} + +// DepositingEnabled is a free data retrieval call binding the contract method 0x71f43f9a. +// +// Solidity: function depositingEnabled() view returns(bool) +func (_Bancor *BancorCaller) DepositingEnabled(opts *bind.CallOpts) (bool, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "depositingEnabled") + + if err != nil { + return *new(bool), err + } + + out0 := *abi.ConvertType(out[0], new(bool)).(*bool) + + return out0, err + +} + +// DepositingEnabled is a free data retrieval call binding the contract method 0x71f43f9a. +// +// Solidity: function depositingEnabled() view returns(bool) +func (_Bancor *BancorSession) DepositingEnabled() (bool, error) { + return _Bancor.Contract.DepositingEnabled(&_Bancor.CallOpts) +} + +// DepositingEnabled is a free data retrieval call binding the contract method 0x71f43f9a. +// +// Solidity: function depositingEnabled() view returns(bool) +func (_Bancor *BancorCallerSession) DepositingEnabled() (bool, error) { + return _Bancor.Contract.DepositingEnabled(&_Bancor.CallOpts) +} + +// GetRoleAdmin is a free data retrieval call binding the contract method 0x248a9ca3. +// +// Solidity: function getRoleAdmin(bytes32 role) view returns(bytes32) +func (_Bancor *BancorCaller) GetRoleAdmin(opts *bind.CallOpts, role [32]byte) ([32]byte, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "getRoleAdmin", role) + + if err != nil { + return *new([32]byte), err + } + + out0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte) + + return out0, err + +} + +// GetRoleAdmin is a free data retrieval call binding the contract method 0x248a9ca3. +// +// Solidity: function getRoleAdmin(bytes32 role) view returns(bytes32) +func (_Bancor *BancorSession) GetRoleAdmin(role [32]byte) ([32]byte, error) { + return _Bancor.Contract.GetRoleAdmin(&_Bancor.CallOpts, role) +} + +// GetRoleAdmin is a free data retrieval call binding the contract method 0x248a9ca3. +// +// Solidity: function getRoleAdmin(bytes32 role) view returns(bytes32) +func (_Bancor *BancorCallerSession) GetRoleAdmin(role [32]byte) ([32]byte, error) { + return _Bancor.Contract.GetRoleAdmin(&_Bancor.CallOpts, role) +} + +// GetRoleMember is a free data retrieval call binding the contract method 0x9010d07c. +// +// Solidity: function getRoleMember(bytes32 role, uint256 index) view returns(address) +func (_Bancor *BancorCaller) GetRoleMember(opts *bind.CallOpts, role [32]byte, index *big.Int) (common.Address, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "getRoleMember", role, index) + + if err != nil { + return *new(common.Address), err + } + + out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) + + return out0, err + +} + +// GetRoleMember is a free data retrieval call binding the contract method 0x9010d07c. +// +// Solidity: function getRoleMember(bytes32 role, uint256 index) view returns(address) +func (_Bancor *BancorSession) GetRoleMember(role [32]byte, index *big.Int) (common.Address, error) { + return _Bancor.Contract.GetRoleMember(&_Bancor.CallOpts, role, index) +} + +// GetRoleMember is a free data retrieval call binding the contract method 0x9010d07c. +// +// Solidity: function getRoleMember(bytes32 role, uint256 index) view returns(address) +func (_Bancor *BancorCallerSession) GetRoleMember(role [32]byte, index *big.Int) (common.Address, error) { + return _Bancor.Contract.GetRoleMember(&_Bancor.CallOpts, role, index) +} + +// GetRoleMemberCount is a free data retrieval call binding the contract method 0xca15c873. +// +// Solidity: function getRoleMemberCount(bytes32 role) view returns(uint256) +func (_Bancor *BancorCaller) GetRoleMemberCount(opts *bind.CallOpts, role [32]byte) (*big.Int, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "getRoleMemberCount", role) + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// GetRoleMemberCount is a free data retrieval call binding the contract method 0xca15c873. +// +// Solidity: function getRoleMemberCount(bytes32 role) view returns(uint256) +func (_Bancor *BancorSession) GetRoleMemberCount(role [32]byte) (*big.Int, error) { + return _Bancor.Contract.GetRoleMemberCount(&_Bancor.CallOpts, role) +} + +// GetRoleMemberCount is a free data retrieval call binding the contract method 0xca15c873. +// +// Solidity: function getRoleMemberCount(bytes32 role) view returns(uint256) +func (_Bancor *BancorCallerSession) GetRoleMemberCount(role [32]byte) (*big.Int, error) { + return _Bancor.Contract.GetRoleMemberCount(&_Bancor.CallOpts, role) +} + +// HasRole is a free data retrieval call binding the contract method 0x91d14854. +// +// Solidity: function hasRole(bytes32 role, address account) view returns(bool) +func (_Bancor *BancorCaller) HasRole(opts *bind.CallOpts, role [32]byte, account common.Address) (bool, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "hasRole", role, account) + + if err != nil { + return *new(bool), err + } + + out0 := *abi.ConvertType(out[0], new(bool)).(*bool) + + return out0, err + +} + +// HasRole is a free data retrieval call binding the contract method 0x91d14854. +// +// Solidity: function hasRole(bytes32 role, address account) view returns(bool) +func (_Bancor *BancorSession) HasRole(role [32]byte, account common.Address) (bool, error) { + return _Bancor.Contract.HasRole(&_Bancor.CallOpts, role, account) +} + +// HasRole is a free data retrieval call binding the contract method 0x91d14854. +// +// Solidity: function hasRole(bytes32 role, address account) view returns(bool) +func (_Bancor *BancorCallerSession) HasRole(role [32]byte, account common.Address) (bool, error) { + return _Bancor.Contract.HasRole(&_Bancor.CallOpts, role, account) +} + +// LiquidityPools is a free data retrieval call binding the contract method 0xd6efd7c3. +// +// Solidity: function liquidityPools() view returns(address[]) +func (_Bancor *BancorCaller) LiquidityPools(opts *bind.CallOpts) ([]common.Address, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "liquidityPools") + + if err != nil { + return *new([]common.Address), err + } + + out0 := *abi.ConvertType(out[0], new([]common.Address)).(*[]common.Address) + + return out0, err + +} + +// LiquidityPools is a free data retrieval call binding the contract method 0xd6efd7c3. +// +// Solidity: function liquidityPools() view returns(address[]) +func (_Bancor *BancorSession) LiquidityPools() ([]common.Address, error) { + return _Bancor.Contract.LiquidityPools(&_Bancor.CallOpts) +} + +// LiquidityPools is a free data retrieval call binding the contract method 0xd6efd7c3. +// +// Solidity: function liquidityPools() view returns(address[]) +func (_Bancor *BancorCallerSession) LiquidityPools() ([]common.Address, error) { + return _Bancor.Contract.LiquidityPools(&_Bancor.CallOpts) +} + +// Paused is a free data retrieval call binding the contract method 0x5c975abb. +// +// Solidity: function paused() view returns(bool) +func (_Bancor *BancorCaller) Paused(opts *bind.CallOpts) (bool, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "paused") + + if err != nil { + return *new(bool), err + } + + out0 := *abi.ConvertType(out[0], new(bool)).(*bool) + + return out0, err + +} + +// Paused is a free data retrieval call binding the contract method 0x5c975abb. +// +// Solidity: function paused() view returns(bool) +func (_Bancor *BancorSession) Paused() (bool, error) { + return _Bancor.Contract.Paused(&_Bancor.CallOpts) +} + +// Paused is a free data retrieval call binding the contract method 0x5c975abb. +// +// Solidity: function paused() view returns(bool) +func (_Bancor *BancorCallerSession) Paused() (bool, error) { + return _Bancor.Contract.Paused(&_Bancor.CallOpts) +} + +// PendingNetworkFeeAmount is a free data retrieval call binding the contract method 0x7bf6a425. +// +// Solidity: function pendingNetworkFeeAmount() view returns(uint256) +func (_Bancor *BancorCaller) PendingNetworkFeeAmount(opts *bind.CallOpts) (*big.Int, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "pendingNetworkFeeAmount") + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// PendingNetworkFeeAmount is a free data retrieval call binding the contract method 0x7bf6a425. +// +// Solidity: function pendingNetworkFeeAmount() view returns(uint256) +func (_Bancor *BancorSession) PendingNetworkFeeAmount() (*big.Int, error) { + return _Bancor.Contract.PendingNetworkFeeAmount(&_Bancor.CallOpts) +} + +// PendingNetworkFeeAmount is a free data retrieval call binding the contract method 0x7bf6a425. +// +// Solidity: function pendingNetworkFeeAmount() view returns(uint256) +func (_Bancor *BancorCallerSession) PendingNetworkFeeAmount() (*big.Int, error) { + return _Bancor.Contract.PendingNetworkFeeAmount(&_Bancor.CallOpts) +} + +// PolRewardsPPM is a free data retrieval call binding the contract method 0x1329db29. +// +// Solidity: function polRewardsPPM() view returns(uint32) +func (_Bancor *BancorCaller) PolRewardsPPM(opts *bind.CallOpts) (uint32, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "polRewardsPPM") + + if err != nil { + return *new(uint32), err + } + + out0 := *abi.ConvertType(out[0], new(uint32)).(*uint32) + + return out0, err + +} + +// PolRewardsPPM is a free data retrieval call binding the contract method 0x1329db29. +// +// Solidity: function polRewardsPPM() view returns(uint32) +func (_Bancor *BancorSession) PolRewardsPPM() (uint32, error) { + return _Bancor.Contract.PolRewardsPPM(&_Bancor.CallOpts) +} + +// PolRewardsPPM is a free data retrieval call binding the contract method 0x1329db29. +// +// Solidity: function polRewardsPPM() view returns(uint32) +func (_Bancor *BancorCallerSession) PolRewardsPPM() (uint32, error) { + return _Bancor.Contract.PolRewardsPPM(&_Bancor.CallOpts) +} + +// PoolCollections is a free data retrieval call binding the contract method 0x39fadf98. +// +// Solidity: function poolCollections() view returns(address[]) +func (_Bancor *BancorCaller) PoolCollections(opts *bind.CallOpts) ([]common.Address, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "poolCollections") + + if err != nil { + return *new([]common.Address), err + } + + out0 := *abi.ConvertType(out[0], new([]common.Address)).(*[]common.Address) + + return out0, err + +} + +// PoolCollections is a free data retrieval call binding the contract method 0x39fadf98. +// +// Solidity: function poolCollections() view returns(address[]) +func (_Bancor *BancorSession) PoolCollections() ([]common.Address, error) { + return _Bancor.Contract.PoolCollections(&_Bancor.CallOpts) +} + +// PoolCollections is a free data retrieval call binding the contract method 0x39fadf98. +// +// Solidity: function poolCollections() view returns(address[]) +func (_Bancor *BancorCallerSession) PoolCollections() ([]common.Address, error) { + return _Bancor.Contract.PoolCollections(&_Bancor.CallOpts) +} + +// RoleAdmin is a free data retrieval call binding the contract method 0x93867fb5. +// +// Solidity: function roleAdmin() pure returns(bytes32) +func (_Bancor *BancorCaller) RoleAdmin(opts *bind.CallOpts) ([32]byte, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "roleAdmin") + + if err != nil { + return *new([32]byte), err + } + + out0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte) + + return out0, err + +} + +// RoleAdmin is a free data retrieval call binding the contract method 0x93867fb5. +// +// Solidity: function roleAdmin() pure returns(bytes32) +func (_Bancor *BancorSession) RoleAdmin() ([32]byte, error) { + return _Bancor.Contract.RoleAdmin(&_Bancor.CallOpts) +} + +// RoleAdmin is a free data retrieval call binding the contract method 0x93867fb5. +// +// Solidity: function roleAdmin() pure returns(bytes32) +func (_Bancor *BancorCallerSession) RoleAdmin() ([32]byte, error) { + return _Bancor.Contract.RoleAdmin(&_Bancor.CallOpts) +} + +// RoleEmergencyStopper is a free data retrieval call binding the contract method 0x41f435b3. +// +// Solidity: function roleEmergencyStopper() pure returns(bytes32) +func (_Bancor *BancorCaller) RoleEmergencyStopper(opts *bind.CallOpts) ([32]byte, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "roleEmergencyStopper") + + if err != nil { + return *new([32]byte), err + } + + out0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte) + + return out0, err + +} + +// RoleEmergencyStopper is a free data retrieval call binding the contract method 0x41f435b3. +// +// Solidity: function roleEmergencyStopper() pure returns(bytes32) +func (_Bancor *BancorSession) RoleEmergencyStopper() ([32]byte, error) { + return _Bancor.Contract.RoleEmergencyStopper(&_Bancor.CallOpts) +} + +// RoleEmergencyStopper is a free data retrieval call binding the contract method 0x41f435b3. +// +// Solidity: function roleEmergencyStopper() pure returns(bytes32) +func (_Bancor *BancorCallerSession) RoleEmergencyStopper() ([32]byte, error) { + return _Bancor.Contract.RoleEmergencyStopper(&_Bancor.CallOpts) +} + +// RoleMigrationManager is a free data retrieval call binding the contract method 0xe6aac07e. +// +// Solidity: function roleMigrationManager() pure returns(bytes32) +func (_Bancor *BancorCaller) RoleMigrationManager(opts *bind.CallOpts) ([32]byte, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "roleMigrationManager") + + if err != nil { + return *new([32]byte), err + } + + out0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte) + + return out0, err + +} + +// RoleMigrationManager is a free data retrieval call binding the contract method 0xe6aac07e. +// +// Solidity: function roleMigrationManager() pure returns(bytes32) +func (_Bancor *BancorSession) RoleMigrationManager() ([32]byte, error) { + return _Bancor.Contract.RoleMigrationManager(&_Bancor.CallOpts) +} + +// RoleMigrationManager is a free data retrieval call binding the contract method 0xe6aac07e. +// +// Solidity: function roleMigrationManager() pure returns(bytes32) +func (_Bancor *BancorCallerSession) RoleMigrationManager() ([32]byte, error) { + return _Bancor.Contract.RoleMigrationManager(&_Bancor.CallOpts) +} + +// RoleNetworkFeeManager is a free data retrieval call binding the contract method 0xc8447487. +// +// Solidity: function roleNetworkFeeManager() pure returns(bytes32) +func (_Bancor *BancorCaller) RoleNetworkFeeManager(opts *bind.CallOpts) ([32]byte, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "roleNetworkFeeManager") + + if err != nil { + return *new([32]byte), err + } + + out0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte) + + return out0, err + +} + +// RoleNetworkFeeManager is a free data retrieval call binding the contract method 0xc8447487. +// +// Solidity: function roleNetworkFeeManager() pure returns(bytes32) +func (_Bancor *BancorSession) RoleNetworkFeeManager() ([32]byte, error) { + return _Bancor.Contract.RoleNetworkFeeManager(&_Bancor.CallOpts) +} + +// RoleNetworkFeeManager is a free data retrieval call binding the contract method 0xc8447487. +// +// Solidity: function roleNetworkFeeManager() pure returns(bytes32) +func (_Bancor *BancorCallerSession) RoleNetworkFeeManager() ([32]byte, error) { + return _Bancor.Contract.RoleNetworkFeeManager(&_Bancor.CallOpts) +} + +// SupportsInterface is a free data retrieval call binding the contract method 0x01ffc9a7. +// +// Solidity: function supportsInterface(bytes4 interfaceId) view returns(bool) +func (_Bancor *BancorCaller) SupportsInterface(opts *bind.CallOpts, interfaceId [4]byte) (bool, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "supportsInterface", interfaceId) + + if err != nil { + return *new(bool), err + } + + out0 := *abi.ConvertType(out[0], new(bool)).(*bool) + + return out0, err + +} + +// SupportsInterface is a free data retrieval call binding the contract method 0x01ffc9a7. +// +// Solidity: function supportsInterface(bytes4 interfaceId) view returns(bool) +func (_Bancor *BancorSession) SupportsInterface(interfaceId [4]byte) (bool, error) { + return _Bancor.Contract.SupportsInterface(&_Bancor.CallOpts, interfaceId) +} + +// SupportsInterface is a free data retrieval call binding the contract method 0x01ffc9a7. +// +// Solidity: function supportsInterface(bytes4 interfaceId) view returns(bool) +func (_Bancor *BancorCallerSession) SupportsInterface(interfaceId [4]byte) (bool, error) { + return _Bancor.Contract.SupportsInterface(&_Bancor.CallOpts, interfaceId) +} + +// Version is a free data retrieval call binding the contract method 0x54fd4d50. +// +// Solidity: function version() pure returns(uint16) +func (_Bancor *BancorCaller) Version(opts *bind.CallOpts) (uint16, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "version") + + if err != nil { + return *new(uint16), err + } + + out0 := *abi.ConvertType(out[0], new(uint16)).(*uint16) + + return out0, err + +} + +// Version is a free data retrieval call binding the contract method 0x54fd4d50. +// +// Solidity: function version() pure returns(uint16) +func (_Bancor *BancorSession) Version() (uint16, error) { + return _Bancor.Contract.Version(&_Bancor.CallOpts) +} + +// Version is a free data retrieval call binding the contract method 0x54fd4d50. +// +// Solidity: function version() pure returns(uint16) +func (_Bancor *BancorCallerSession) Version() (uint16, error) { + return _Bancor.Contract.Version(&_Bancor.CallOpts) +} + +// CancelWithdrawal is a paid mutator transaction binding the contract method 0x3efcfda4. +// +// Solidity: function cancelWithdrawal(uint256 id) returns(uint256) +func (_Bancor *BancorTransactor) CancelWithdrawal(opts *bind.TransactOpts, id *big.Int) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "cancelWithdrawal", id) +} + +// CancelWithdrawal is a paid mutator transaction binding the contract method 0x3efcfda4. +// +// Solidity: function cancelWithdrawal(uint256 id) returns(uint256) +func (_Bancor *BancorSession) CancelWithdrawal(id *big.Int) (*types.Transaction, error) { + return _Bancor.Contract.CancelWithdrawal(&_Bancor.TransactOpts, id) +} + +// CancelWithdrawal is a paid mutator transaction binding the contract method 0x3efcfda4. +// +// Solidity: function cancelWithdrawal(uint256 id) returns(uint256) +func (_Bancor *BancorTransactorSession) CancelWithdrawal(id *big.Int) (*types.Transaction, error) { + return _Bancor.Contract.CancelWithdrawal(&_Bancor.TransactOpts, id) +} + +// CreatePools is a paid mutator transaction binding the contract method 0x42659964. +// +// Solidity: function createPools(address[] tokens, address poolCollection) returns() +func (_Bancor *BancorTransactor) CreatePools(opts *bind.TransactOpts, tokens []common.Address, poolCollection common.Address) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "createPools", tokens, poolCollection) +} + +// CreatePools is a paid mutator transaction binding the contract method 0x42659964. +// +// Solidity: function createPools(address[] tokens, address poolCollection) returns() +func (_Bancor *BancorSession) CreatePools(tokens []common.Address, poolCollection common.Address) (*types.Transaction, error) { + return _Bancor.Contract.CreatePools(&_Bancor.TransactOpts, tokens, poolCollection) +} + +// CreatePools is a paid mutator transaction binding the contract method 0x42659964. +// +// Solidity: function createPools(address[] tokens, address poolCollection) returns() +func (_Bancor *BancorTransactorSession) CreatePools(tokens []common.Address, poolCollection common.Address) (*types.Transaction, error) { + return _Bancor.Contract.CreatePools(&_Bancor.TransactOpts, tokens, poolCollection) +} + +// Deposit is a paid mutator transaction binding the contract method 0x47e7ef24. +// +// Solidity: function deposit(address pool, uint256 tokenAmount) payable returns(uint256) +func (_Bancor *BancorTransactor) Deposit(opts *bind.TransactOpts, pool common.Address, tokenAmount *big.Int) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "deposit", pool, tokenAmount) +} + +// Deposit is a paid mutator transaction binding the contract method 0x47e7ef24. +// +// Solidity: function deposit(address pool, uint256 tokenAmount) payable returns(uint256) +func (_Bancor *BancorSession) Deposit(pool common.Address, tokenAmount *big.Int) (*types.Transaction, error) { + return _Bancor.Contract.Deposit(&_Bancor.TransactOpts, pool, tokenAmount) +} + +// Deposit is a paid mutator transaction binding the contract method 0x47e7ef24. +// +// Solidity: function deposit(address pool, uint256 tokenAmount) payable returns(uint256) +func (_Bancor *BancorTransactorSession) Deposit(pool common.Address, tokenAmount *big.Int) (*types.Transaction, error) { + return _Bancor.Contract.Deposit(&_Bancor.TransactOpts, pool, tokenAmount) +} + +// DepositFor is a paid mutator transaction binding the contract method 0xb3db428b. +// +// Solidity: function depositFor(address provider, address pool, uint256 tokenAmount) payable returns(uint256) +func (_Bancor *BancorTransactor) DepositFor(opts *bind.TransactOpts, provider common.Address, pool common.Address, tokenAmount *big.Int) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "depositFor", provider, pool, tokenAmount) +} + +// DepositFor is a paid mutator transaction binding the contract method 0xb3db428b. +// +// Solidity: function depositFor(address provider, address pool, uint256 tokenAmount) payable returns(uint256) +func (_Bancor *BancorSession) DepositFor(provider common.Address, pool common.Address, tokenAmount *big.Int) (*types.Transaction, error) { + return _Bancor.Contract.DepositFor(&_Bancor.TransactOpts, provider, pool, tokenAmount) +} + +// DepositFor is a paid mutator transaction binding the contract method 0xb3db428b. +// +// Solidity: function depositFor(address provider, address pool, uint256 tokenAmount) payable returns(uint256) +func (_Bancor *BancorTransactorSession) DepositFor(provider common.Address, pool common.Address, tokenAmount *big.Int) (*types.Transaction, error) { + return _Bancor.Contract.DepositFor(&_Bancor.TransactOpts, provider, pool, tokenAmount) +} + +// EnableDepositing is a paid mutator transaction binding the contract method 0x26e6b697. +// +// Solidity: function enableDepositing(bool status) returns() +func (_Bancor *BancorTransactor) EnableDepositing(opts *bind.TransactOpts, status bool) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "enableDepositing", status) +} + +// EnableDepositing is a paid mutator transaction binding the contract method 0x26e6b697. +// +// Solidity: function enableDepositing(bool status) returns() +func (_Bancor *BancorSession) EnableDepositing(status bool) (*types.Transaction, error) { + return _Bancor.Contract.EnableDepositing(&_Bancor.TransactOpts, status) +} + +// EnableDepositing is a paid mutator transaction binding the contract method 0x26e6b697. +// +// Solidity: function enableDepositing(bool status) returns() +func (_Bancor *BancorTransactorSession) EnableDepositing(status bool) (*types.Transaction, error) { + return _Bancor.Contract.EnableDepositing(&_Bancor.TransactOpts, status) +} + +// FlashLoan is a paid mutator transaction binding the contract method 0xadf51de1. +// +// Solidity: function flashLoan(address token, uint256 amount, address recipient, bytes data) returns() +func (_Bancor *BancorTransactor) FlashLoan(opts *bind.TransactOpts, token common.Address, amount *big.Int, recipient common.Address, data []byte) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "flashLoan", token, amount, recipient, data) +} + +// FlashLoan is a paid mutator transaction binding the contract method 0xadf51de1. +// +// Solidity: function flashLoan(address token, uint256 amount, address recipient, bytes data) returns() +func (_Bancor *BancorSession) FlashLoan(token common.Address, amount *big.Int, recipient common.Address, data []byte) (*types.Transaction, error) { + return _Bancor.Contract.FlashLoan(&_Bancor.TransactOpts, token, amount, recipient, data) +} + +// FlashLoan is a paid mutator transaction binding the contract method 0xadf51de1. +// +// Solidity: function flashLoan(address token, uint256 amount, address recipient, bytes data) returns() +func (_Bancor *BancorTransactorSession) FlashLoan(token common.Address, amount *big.Int, recipient common.Address, data []byte) (*types.Transaction, error) { + return _Bancor.Contract.FlashLoan(&_Bancor.TransactOpts, token, amount, recipient, data) +} + +// GrantRole is a paid mutator transaction binding the contract method 0x2f2ff15d. +// +// Solidity: function grantRole(bytes32 role, address account) returns() +func (_Bancor *BancorTransactor) GrantRole(opts *bind.TransactOpts, role [32]byte, account common.Address) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "grantRole", role, account) +} + +// GrantRole is a paid mutator transaction binding the contract method 0x2f2ff15d. +// +// Solidity: function grantRole(bytes32 role, address account) returns() +func (_Bancor *BancorSession) GrantRole(role [32]byte, account common.Address) (*types.Transaction, error) { + return _Bancor.Contract.GrantRole(&_Bancor.TransactOpts, role, account) +} + +// GrantRole is a paid mutator transaction binding the contract method 0x2f2ff15d. +// +// Solidity: function grantRole(bytes32 role, address account) returns() +func (_Bancor *BancorTransactorSession) GrantRole(role [32]byte, account common.Address) (*types.Transaction, error) { + return _Bancor.Contract.GrantRole(&_Bancor.TransactOpts, role, account) +} + +// InitWithdrawal is a paid mutator transaction binding the contract method 0x357a0333. +// +// Solidity: function initWithdrawal(address poolToken, uint256 poolTokenAmount) returns(uint256) +func (_Bancor *BancorTransactor) InitWithdrawal(opts *bind.TransactOpts, poolToken common.Address, poolTokenAmount *big.Int) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "initWithdrawal", poolToken, poolTokenAmount) +} + +// InitWithdrawal is a paid mutator transaction binding the contract method 0x357a0333. +// +// Solidity: function initWithdrawal(address poolToken, uint256 poolTokenAmount) returns(uint256) +func (_Bancor *BancorSession) InitWithdrawal(poolToken common.Address, poolTokenAmount *big.Int) (*types.Transaction, error) { + return _Bancor.Contract.InitWithdrawal(&_Bancor.TransactOpts, poolToken, poolTokenAmount) +} + +// InitWithdrawal is a paid mutator transaction binding the contract method 0x357a0333. +// +// Solidity: function initWithdrawal(address poolToken, uint256 poolTokenAmount) returns(uint256) +func (_Bancor *BancorTransactorSession) InitWithdrawal(poolToken common.Address, poolTokenAmount *big.Int) (*types.Transaction, error) { + return _Bancor.Contract.InitWithdrawal(&_Bancor.TransactOpts, poolToken, poolTokenAmount) +} + +// Initialize is a paid mutator transaction binding the contract method 0xc0c53b8b. +// +// Solidity: function initialize(address initBNTPool, address initPendingWithdrawals, address initPoolMigrator) returns() +func (_Bancor *BancorTransactor) Initialize(opts *bind.TransactOpts, initBNTPool common.Address, initPendingWithdrawals common.Address, initPoolMigrator common.Address) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "initialize", initBNTPool, initPendingWithdrawals, initPoolMigrator) +} + +// Initialize is a paid mutator transaction binding the contract method 0xc0c53b8b. +// +// Solidity: function initialize(address initBNTPool, address initPendingWithdrawals, address initPoolMigrator) returns() +func (_Bancor *BancorSession) Initialize(initBNTPool common.Address, initPendingWithdrawals common.Address, initPoolMigrator common.Address) (*types.Transaction, error) { + return _Bancor.Contract.Initialize(&_Bancor.TransactOpts, initBNTPool, initPendingWithdrawals, initPoolMigrator) +} + +// Initialize is a paid mutator transaction binding the contract method 0xc0c53b8b. +// +// Solidity: function initialize(address initBNTPool, address initPendingWithdrawals, address initPoolMigrator) returns() +func (_Bancor *BancorTransactorSession) Initialize(initBNTPool common.Address, initPendingWithdrawals common.Address, initPoolMigrator common.Address) (*types.Transaction, error) { + return _Bancor.Contract.Initialize(&_Bancor.TransactOpts, initBNTPool, initPendingWithdrawals, initPoolMigrator) +} + +// MigrateLiquidity is a paid mutator transaction binding the contract method 0x3d1c24e7. +// +// Solidity: function migrateLiquidity(address token, address provider, uint256 amount, uint256 availableAmount, uint256 originalAmount) payable returns() +func (_Bancor *BancorTransactor) MigrateLiquidity(opts *bind.TransactOpts, token common.Address, provider common.Address, amount *big.Int, availableAmount *big.Int, originalAmount *big.Int) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "migrateLiquidity", token, provider, amount, availableAmount, originalAmount) +} + +// MigrateLiquidity is a paid mutator transaction binding the contract method 0x3d1c24e7. +// +// Solidity: function migrateLiquidity(address token, address provider, uint256 amount, uint256 availableAmount, uint256 originalAmount) payable returns() +func (_Bancor *BancorSession) MigrateLiquidity(token common.Address, provider common.Address, amount *big.Int, availableAmount *big.Int, originalAmount *big.Int) (*types.Transaction, error) { + return _Bancor.Contract.MigrateLiquidity(&_Bancor.TransactOpts, token, provider, amount, availableAmount, originalAmount) +} + +// MigrateLiquidity is a paid mutator transaction binding the contract method 0x3d1c24e7. +// +// Solidity: function migrateLiquidity(address token, address provider, uint256 amount, uint256 availableAmount, uint256 originalAmount) payable returns() +func (_Bancor *BancorTransactorSession) MigrateLiquidity(token common.Address, provider common.Address, amount *big.Int, availableAmount *big.Int, originalAmount *big.Int) (*types.Transaction, error) { + return _Bancor.Contract.MigrateLiquidity(&_Bancor.TransactOpts, token, provider, amount, availableAmount, originalAmount) +} + +// MigratePools is a paid mutator transaction binding the contract method 0xc109ba13. +// +// Solidity: function migratePools(address[] pools, address newPoolCollection) returns() +func (_Bancor *BancorTransactor) MigratePools(opts *bind.TransactOpts, pools []common.Address, newPoolCollection common.Address) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "migratePools", pools, newPoolCollection) +} + +// MigratePools is a paid mutator transaction binding the contract method 0xc109ba13. +// +// Solidity: function migratePools(address[] pools, address newPoolCollection) returns() +func (_Bancor *BancorSession) MigratePools(pools []common.Address, newPoolCollection common.Address) (*types.Transaction, error) { + return _Bancor.Contract.MigratePools(&_Bancor.TransactOpts, pools, newPoolCollection) +} + +// MigratePools is a paid mutator transaction binding the contract method 0xc109ba13. +// +// Solidity: function migratePools(address[] pools, address newPoolCollection) returns() +func (_Bancor *BancorTransactorSession) MigratePools(pools []common.Address, newPoolCollection common.Address) (*types.Transaction, error) { + return _Bancor.Contract.MigratePools(&_Bancor.TransactOpts, pools, newPoolCollection) +} + +// Pause is a paid mutator transaction binding the contract method 0x8456cb59. +// +// Solidity: function pause() returns() +func (_Bancor *BancorTransactor) Pause(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "pause") +} + +// Pause is a paid mutator transaction binding the contract method 0x8456cb59. +// +// Solidity: function pause() returns() +func (_Bancor *BancorSession) Pause() (*types.Transaction, error) { + return _Bancor.Contract.Pause(&_Bancor.TransactOpts) +} + +// Pause is a paid mutator transaction binding the contract method 0x8456cb59. +// +// Solidity: function pause() returns() +func (_Bancor *BancorTransactorSession) Pause() (*types.Transaction, error) { + return _Bancor.Contract.Pause(&_Bancor.TransactOpts) +} + +// PostUpgrade is a paid mutator transaction binding the contract method 0x8cd2403d. +// +// Solidity: function postUpgrade(bytes data) returns() +func (_Bancor *BancorTransactor) PostUpgrade(opts *bind.TransactOpts, data []byte) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "postUpgrade", data) +} + +// PostUpgrade is a paid mutator transaction binding the contract method 0x8cd2403d. +// +// Solidity: function postUpgrade(bytes data) returns() +func (_Bancor *BancorSession) PostUpgrade(data []byte) (*types.Transaction, error) { + return _Bancor.Contract.PostUpgrade(&_Bancor.TransactOpts, data) +} + +// PostUpgrade is a paid mutator transaction binding the contract method 0x8cd2403d. +// +// Solidity: function postUpgrade(bytes data) returns() +func (_Bancor *BancorTransactorSession) PostUpgrade(data []byte) (*types.Transaction, error) { + return _Bancor.Contract.PostUpgrade(&_Bancor.TransactOpts, data) +} + +// RegisterPoolCollection is a paid mutator transaction binding the contract method 0xa8bf9046. +// +// Solidity: function registerPoolCollection(address newPoolCollection) returns() +func (_Bancor *BancorTransactor) RegisterPoolCollection(opts *bind.TransactOpts, newPoolCollection common.Address) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "registerPoolCollection", newPoolCollection) +} + +// RegisterPoolCollection is a paid mutator transaction binding the contract method 0xa8bf9046. +// +// Solidity: function registerPoolCollection(address newPoolCollection) returns() +func (_Bancor *BancorSession) RegisterPoolCollection(newPoolCollection common.Address) (*types.Transaction, error) { + return _Bancor.Contract.RegisterPoolCollection(&_Bancor.TransactOpts, newPoolCollection) +} + +// RegisterPoolCollection is a paid mutator transaction binding the contract method 0xa8bf9046. +// +// Solidity: function registerPoolCollection(address newPoolCollection) returns() +func (_Bancor *BancorTransactorSession) RegisterPoolCollection(newPoolCollection common.Address) (*types.Transaction, error) { + return _Bancor.Contract.RegisterPoolCollection(&_Bancor.TransactOpts, newPoolCollection) +} + +// RenounceRole is a paid mutator transaction binding the contract method 0x36568abe. +// +// Solidity: function renounceRole(bytes32 role, address account) returns() +func (_Bancor *BancorTransactor) RenounceRole(opts *bind.TransactOpts, role [32]byte, account common.Address) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "renounceRole", role, account) +} + +// RenounceRole is a paid mutator transaction binding the contract method 0x36568abe. +// +// Solidity: function renounceRole(bytes32 role, address account) returns() +func (_Bancor *BancorSession) RenounceRole(role [32]byte, account common.Address) (*types.Transaction, error) { + return _Bancor.Contract.RenounceRole(&_Bancor.TransactOpts, role, account) +} + +// RenounceRole is a paid mutator transaction binding the contract method 0x36568abe. +// +// Solidity: function renounceRole(bytes32 role, address account) returns() +func (_Bancor *BancorTransactorSession) RenounceRole(role [32]byte, account common.Address) (*types.Transaction, error) { + return _Bancor.Contract.RenounceRole(&_Bancor.TransactOpts, role, account) +} + +// Resume is a paid mutator transaction binding the contract method 0x046f7da2. +// +// Solidity: function resume() returns() +func (_Bancor *BancorTransactor) Resume(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "resume") +} + +// Resume is a paid mutator transaction binding the contract method 0x046f7da2. +// +// Solidity: function resume() returns() +func (_Bancor *BancorSession) Resume() (*types.Transaction, error) { + return _Bancor.Contract.Resume(&_Bancor.TransactOpts) +} + +// Resume is a paid mutator transaction binding the contract method 0x046f7da2. +// +// Solidity: function resume() returns() +func (_Bancor *BancorTransactorSession) Resume() (*types.Transaction, error) { + return _Bancor.Contract.Resume(&_Bancor.TransactOpts) +} + +// RevokeRole is a paid mutator transaction binding the contract method 0xd547741f. +// +// Solidity: function revokeRole(bytes32 role, address account) returns() +func (_Bancor *BancorTransactor) RevokeRole(opts *bind.TransactOpts, role [32]byte, account common.Address) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "revokeRole", role, account) +} + +// RevokeRole is a paid mutator transaction binding the contract method 0xd547741f. +// +// Solidity: function revokeRole(bytes32 role, address account) returns() +func (_Bancor *BancorSession) RevokeRole(role [32]byte, account common.Address) (*types.Transaction, error) { + return _Bancor.Contract.RevokeRole(&_Bancor.TransactOpts, role, account) +} + +// RevokeRole is a paid mutator transaction binding the contract method 0xd547741f. +// +// Solidity: function revokeRole(bytes32 role, address account) returns() +func (_Bancor *BancorTransactorSession) RevokeRole(role [32]byte, account common.Address) (*types.Transaction, error) { + return _Bancor.Contract.RevokeRole(&_Bancor.TransactOpts, role, account) +} + +// SetPOLRewardsPPM is a paid mutator transaction binding the contract method 0x53300772. +// +// Solidity: function setPOLRewardsPPM(uint32 newRewardsPPM) returns() +func (_Bancor *BancorTransactor) SetPOLRewardsPPM(opts *bind.TransactOpts, newRewardsPPM uint32) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "setPOLRewardsPPM", newRewardsPPM) +} + +// SetPOLRewardsPPM is a paid mutator transaction binding the contract method 0x53300772. +// +// Solidity: function setPOLRewardsPPM(uint32 newRewardsPPM) returns() +func (_Bancor *BancorSession) SetPOLRewardsPPM(newRewardsPPM uint32) (*types.Transaction, error) { + return _Bancor.Contract.SetPOLRewardsPPM(&_Bancor.TransactOpts, newRewardsPPM) +} + +// SetPOLRewardsPPM is a paid mutator transaction binding the contract method 0x53300772. +// +// Solidity: function setPOLRewardsPPM(uint32 newRewardsPPM) returns() +func (_Bancor *BancorTransactorSession) SetPOLRewardsPPM(newRewardsPPM uint32) (*types.Transaction, error) { + return _Bancor.Contract.SetPOLRewardsPPM(&_Bancor.TransactOpts, newRewardsPPM) +} + +// TradeBySourceAmount is a paid mutator transaction binding the contract method 0xd3a4acd3. +// +// Solidity: function tradeBySourceAmount(address sourceToken, address targetToken, uint256 sourceAmount, uint256 minReturnAmount, uint256 deadline, address beneficiary) payable returns(uint256) +func (_Bancor *BancorTransactor) TradeBySourceAmount(opts *bind.TransactOpts, sourceToken common.Address, targetToken common.Address, sourceAmount *big.Int, minReturnAmount *big.Int, deadline *big.Int, beneficiary common.Address) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "tradeBySourceAmount", sourceToken, targetToken, sourceAmount, minReturnAmount, deadline, beneficiary) +} + +// TradeBySourceAmount is a paid mutator transaction binding the contract method 0xd3a4acd3. +// +// Solidity: function tradeBySourceAmount(address sourceToken, address targetToken, uint256 sourceAmount, uint256 minReturnAmount, uint256 deadline, address beneficiary) payable returns(uint256) +func (_Bancor *BancorSession) TradeBySourceAmount(sourceToken common.Address, targetToken common.Address, sourceAmount *big.Int, minReturnAmount *big.Int, deadline *big.Int, beneficiary common.Address) (*types.Transaction, error) { + return _Bancor.Contract.TradeBySourceAmount(&_Bancor.TransactOpts, sourceToken, targetToken, sourceAmount, minReturnAmount, deadline, beneficiary) +} + +// TradeBySourceAmount is a paid mutator transaction binding the contract method 0xd3a4acd3. +// +// Solidity: function tradeBySourceAmount(address sourceToken, address targetToken, uint256 sourceAmount, uint256 minReturnAmount, uint256 deadline, address beneficiary) payable returns(uint256) +func (_Bancor *BancorTransactorSession) TradeBySourceAmount(sourceToken common.Address, targetToken common.Address, sourceAmount *big.Int, minReturnAmount *big.Int, deadline *big.Int, beneficiary common.Address) (*types.Transaction, error) { + return _Bancor.Contract.TradeBySourceAmount(&_Bancor.TransactOpts, sourceToken, targetToken, sourceAmount, minReturnAmount, deadline, beneficiary) +} + +// TradeBySourceAmountArb is a paid mutator transaction binding the contract method 0xd895feee. +// +// Solidity: function tradeBySourceAmountArb(address sourceToken, address targetToken, uint256 sourceAmount, uint256 minReturnAmount, uint256 deadline, address beneficiary) payable returns(uint256) +func (_Bancor *BancorTransactor) TradeBySourceAmountArb(opts *bind.TransactOpts, sourceToken common.Address, targetToken common.Address, sourceAmount *big.Int, minReturnAmount *big.Int, deadline *big.Int, beneficiary common.Address) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "tradeBySourceAmountArb", sourceToken, targetToken, sourceAmount, minReturnAmount, deadline, beneficiary) +} + +// TradeBySourceAmountArb is a paid mutator transaction binding the contract method 0xd895feee. +// +// Solidity: function tradeBySourceAmountArb(address sourceToken, address targetToken, uint256 sourceAmount, uint256 minReturnAmount, uint256 deadline, address beneficiary) payable returns(uint256) +func (_Bancor *BancorSession) TradeBySourceAmountArb(sourceToken common.Address, targetToken common.Address, sourceAmount *big.Int, minReturnAmount *big.Int, deadline *big.Int, beneficiary common.Address) (*types.Transaction, error) { + return _Bancor.Contract.TradeBySourceAmountArb(&_Bancor.TransactOpts, sourceToken, targetToken, sourceAmount, minReturnAmount, deadline, beneficiary) +} + +// TradeBySourceAmountArb is a paid mutator transaction binding the contract method 0xd895feee. +// +// Solidity: function tradeBySourceAmountArb(address sourceToken, address targetToken, uint256 sourceAmount, uint256 minReturnAmount, uint256 deadline, address beneficiary) payable returns(uint256) +func (_Bancor *BancorTransactorSession) TradeBySourceAmountArb(sourceToken common.Address, targetToken common.Address, sourceAmount *big.Int, minReturnAmount *big.Int, deadline *big.Int, beneficiary common.Address) (*types.Transaction, error) { + return _Bancor.Contract.TradeBySourceAmountArb(&_Bancor.TransactOpts, sourceToken, targetToken, sourceAmount, minReturnAmount, deadline, beneficiary) +} + +// TradeByTargetAmount is a paid mutator transaction binding the contract method 0x45d6602c. +// +// Solidity: function tradeByTargetAmount(address sourceToken, address targetToken, uint256 targetAmount, uint256 maxSourceAmount, uint256 deadline, address beneficiary) payable returns(uint256) +func (_Bancor *BancorTransactor) TradeByTargetAmount(opts *bind.TransactOpts, sourceToken common.Address, targetToken common.Address, targetAmount *big.Int, maxSourceAmount *big.Int, deadline *big.Int, beneficiary common.Address) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "tradeByTargetAmount", sourceToken, targetToken, targetAmount, maxSourceAmount, deadline, beneficiary) +} + +// TradeByTargetAmount is a paid mutator transaction binding the contract method 0x45d6602c. +// +// Solidity: function tradeByTargetAmount(address sourceToken, address targetToken, uint256 targetAmount, uint256 maxSourceAmount, uint256 deadline, address beneficiary) payable returns(uint256) +func (_Bancor *BancorSession) TradeByTargetAmount(sourceToken common.Address, targetToken common.Address, targetAmount *big.Int, maxSourceAmount *big.Int, deadline *big.Int, beneficiary common.Address) (*types.Transaction, error) { + return _Bancor.Contract.TradeByTargetAmount(&_Bancor.TransactOpts, sourceToken, targetToken, targetAmount, maxSourceAmount, deadline, beneficiary) +} + +// TradeByTargetAmount is a paid mutator transaction binding the contract method 0x45d6602c. +// +// Solidity: function tradeByTargetAmount(address sourceToken, address targetToken, uint256 targetAmount, uint256 maxSourceAmount, uint256 deadline, address beneficiary) payable returns(uint256) +func (_Bancor *BancorTransactorSession) TradeByTargetAmount(sourceToken common.Address, targetToken common.Address, targetAmount *big.Int, maxSourceAmount *big.Int, deadline *big.Int, beneficiary common.Address) (*types.Transaction, error) { + return _Bancor.Contract.TradeByTargetAmount(&_Bancor.TransactOpts, sourceToken, targetToken, targetAmount, maxSourceAmount, deadline, beneficiary) +} + +// TradeByTargetAmountArb is a paid mutator transaction binding the contract method 0xd0d14581. +// +// Solidity: function tradeByTargetAmountArb(address sourceToken, address targetToken, uint256 targetAmount, uint256 maxSourceAmount, uint256 deadline, address beneficiary) payable returns(uint256) +func (_Bancor *BancorTransactor) TradeByTargetAmountArb(opts *bind.TransactOpts, sourceToken common.Address, targetToken common.Address, targetAmount *big.Int, maxSourceAmount *big.Int, deadline *big.Int, beneficiary common.Address) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "tradeByTargetAmountArb", sourceToken, targetToken, targetAmount, maxSourceAmount, deadline, beneficiary) +} + +// TradeByTargetAmountArb is a paid mutator transaction binding the contract method 0xd0d14581. +// +// Solidity: function tradeByTargetAmountArb(address sourceToken, address targetToken, uint256 targetAmount, uint256 maxSourceAmount, uint256 deadline, address beneficiary) payable returns(uint256) +func (_Bancor *BancorSession) TradeByTargetAmountArb(sourceToken common.Address, targetToken common.Address, targetAmount *big.Int, maxSourceAmount *big.Int, deadline *big.Int, beneficiary common.Address) (*types.Transaction, error) { + return _Bancor.Contract.TradeByTargetAmountArb(&_Bancor.TransactOpts, sourceToken, targetToken, targetAmount, maxSourceAmount, deadline, beneficiary) +} + +// TradeByTargetAmountArb is a paid mutator transaction binding the contract method 0xd0d14581. +// +// Solidity: function tradeByTargetAmountArb(address sourceToken, address targetToken, uint256 targetAmount, uint256 maxSourceAmount, uint256 deadline, address beneficiary) payable returns(uint256) +func (_Bancor *BancorTransactorSession) TradeByTargetAmountArb(sourceToken common.Address, targetToken common.Address, targetAmount *big.Int, maxSourceAmount *big.Int, deadline *big.Int, beneficiary common.Address) (*types.Transaction, error) { + return _Bancor.Contract.TradeByTargetAmountArb(&_Bancor.TransactOpts, sourceToken, targetToken, targetAmount, maxSourceAmount, deadline, beneficiary) +} + +// UnregisterPoolCollection is a paid mutator transaction binding the contract method 0x230df83a. +// +// Solidity: function unregisterPoolCollection(address poolCollection) returns() +func (_Bancor *BancorTransactor) UnregisterPoolCollection(opts *bind.TransactOpts, poolCollection common.Address) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "unregisterPoolCollection", poolCollection) +} + +// UnregisterPoolCollection is a paid mutator transaction binding the contract method 0x230df83a. +// +// Solidity: function unregisterPoolCollection(address poolCollection) returns() +func (_Bancor *BancorSession) UnregisterPoolCollection(poolCollection common.Address) (*types.Transaction, error) { + return _Bancor.Contract.UnregisterPoolCollection(&_Bancor.TransactOpts, poolCollection) +} + +// UnregisterPoolCollection is a paid mutator transaction binding the contract method 0x230df83a. +// +// Solidity: function unregisterPoolCollection(address poolCollection) returns() +func (_Bancor *BancorTransactorSession) UnregisterPoolCollection(poolCollection common.Address) (*types.Transaction, error) { + return _Bancor.Contract.UnregisterPoolCollection(&_Bancor.TransactOpts, poolCollection) +} + +// Withdraw is a paid mutator transaction binding the contract method 0x2e1a7d4d. +// +// Solidity: function withdraw(uint256 id) returns(uint256) +func (_Bancor *BancorTransactor) Withdraw(opts *bind.TransactOpts, id *big.Int) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "withdraw", id) +} + +// Withdraw is a paid mutator transaction binding the contract method 0x2e1a7d4d. +// +// Solidity: function withdraw(uint256 id) returns(uint256) +func (_Bancor *BancorSession) Withdraw(id *big.Int) (*types.Transaction, error) { + return _Bancor.Contract.Withdraw(&_Bancor.TransactOpts, id) +} + +// Withdraw is a paid mutator transaction binding the contract method 0x2e1a7d4d. +// +// Solidity: function withdraw(uint256 id) returns(uint256) +func (_Bancor *BancorTransactorSession) Withdraw(id *big.Int) (*types.Transaction, error) { + return _Bancor.Contract.Withdraw(&_Bancor.TransactOpts, id) +} + +// WithdrawNetworkFees is a paid mutator transaction binding the contract method 0x3cd11924. +// +// Solidity: function withdrawNetworkFees(address recipient) returns(uint256) +func (_Bancor *BancorTransactor) WithdrawNetworkFees(opts *bind.TransactOpts, recipient common.Address) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "withdrawNetworkFees", recipient) +} + +// WithdrawNetworkFees is a paid mutator transaction binding the contract method 0x3cd11924. +// +// Solidity: function withdrawNetworkFees(address recipient) returns(uint256) +func (_Bancor *BancorSession) WithdrawNetworkFees(recipient common.Address) (*types.Transaction, error) { + return _Bancor.Contract.WithdrawNetworkFees(&_Bancor.TransactOpts, recipient) +} + +// WithdrawNetworkFees is a paid mutator transaction binding the contract method 0x3cd11924. +// +// Solidity: function withdrawNetworkFees(address recipient) returns(uint256) +func (_Bancor *BancorTransactorSession) WithdrawNetworkFees(recipient common.Address) (*types.Transaction, error) { + return _Bancor.Contract.WithdrawNetworkFees(&_Bancor.TransactOpts, recipient) +} + +// WithdrawPOL is a paid mutator transaction binding the contract method 0x8ffcca07. +// +// Solidity: function withdrawPOL(address pool) returns(uint256) +func (_Bancor *BancorTransactor) WithdrawPOL(opts *bind.TransactOpts, pool common.Address) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "withdrawPOL", pool) +} + +// WithdrawPOL is a paid mutator transaction binding the contract method 0x8ffcca07. +// +// Solidity: function withdrawPOL(address pool) returns(uint256) +func (_Bancor *BancorSession) WithdrawPOL(pool common.Address) (*types.Transaction, error) { + return _Bancor.Contract.WithdrawPOL(&_Bancor.TransactOpts, pool) +} + +// WithdrawPOL is a paid mutator transaction binding the contract method 0x8ffcca07. +// +// Solidity: function withdrawPOL(address pool) returns(uint256) +func (_Bancor *BancorTransactorSession) WithdrawPOL(pool common.Address) (*types.Transaction, error) { + return _Bancor.Contract.WithdrawPOL(&_Bancor.TransactOpts, pool) +} + +// Receive is a paid mutator transaction binding the contract receive function. +// +// Solidity: receive() payable returns() +func (_Bancor *BancorTransactor) Receive(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Bancor.contract.RawTransact(opts, nil) // calldata is disallowed for receive function +} + +// Receive is a paid mutator transaction binding the contract receive function. +// +// Solidity: receive() payable returns() +func (_Bancor *BancorSession) Receive() (*types.Transaction, error) { + return _Bancor.Contract.Receive(&_Bancor.TransactOpts) +} + +// Receive is a paid mutator transaction binding the contract receive function. +// +// Solidity: receive() payable returns() +func (_Bancor *BancorTransactorSession) Receive() (*types.Transaction, error) { + return _Bancor.Contract.Receive(&_Bancor.TransactOpts) +} + +// BancorFlashLoanCompletedIterator is returned from FilterFlashLoanCompleted and is used to iterate over the raw logs and unpacked data for FlashLoanCompleted events raised by the Bancor contract. +type BancorFlashLoanCompletedIterator struct { + Event *BancorFlashLoanCompleted // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorFlashLoanCompletedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorFlashLoanCompleted) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorFlashLoanCompleted) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorFlashLoanCompletedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorFlashLoanCompletedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorFlashLoanCompleted represents a FlashLoanCompleted event raised by the Bancor contract. +type BancorFlashLoanCompleted struct { + Token common.Address + Borrower common.Address + Amount *big.Int + FeeAmount *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterFlashLoanCompleted is a free log retrieval operation binding the contract event 0x0da3485ef1bb570df7bb888887eae5aa01d81b83cd8ccc80c0ea0922a677ecef. +// +// Solidity: event FlashLoanCompleted(address indexed token, address indexed borrower, uint256 amount, uint256 feeAmount) +func (_Bancor *BancorFilterer) FilterFlashLoanCompleted(opts *bind.FilterOpts, token []common.Address, borrower []common.Address) (*BancorFlashLoanCompletedIterator, error) { + + var tokenRule []interface{} + for _, tokenItem := range token { + tokenRule = append(tokenRule, tokenItem) + } + var borrowerRule []interface{} + for _, borrowerItem := range borrower { + borrowerRule = append(borrowerRule, borrowerItem) + } + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "FlashLoanCompleted", tokenRule, borrowerRule) + if err != nil { + return nil, err + } + return &BancorFlashLoanCompletedIterator{contract: _Bancor.contract, event: "FlashLoanCompleted", logs: logs, sub: sub}, nil +} + +// WatchFlashLoanCompleted is a free log subscription operation binding the contract event 0x0da3485ef1bb570df7bb888887eae5aa01d81b83cd8ccc80c0ea0922a677ecef. +// +// Solidity: event FlashLoanCompleted(address indexed token, address indexed borrower, uint256 amount, uint256 feeAmount) +func (_Bancor *BancorFilterer) WatchFlashLoanCompleted(opts *bind.WatchOpts, sink chan<- *BancorFlashLoanCompleted, token []common.Address, borrower []common.Address) (event.Subscription, error) { + + var tokenRule []interface{} + for _, tokenItem := range token { + tokenRule = append(tokenRule, tokenItem) + } + var borrowerRule []interface{} + for _, borrowerItem := range borrower { + borrowerRule = append(borrowerRule, borrowerItem) + } + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "FlashLoanCompleted", tokenRule, borrowerRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorFlashLoanCompleted) + if err := _Bancor.contract.UnpackLog(event, "FlashLoanCompleted", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseFlashLoanCompleted is a log parse operation binding the contract event 0x0da3485ef1bb570df7bb888887eae5aa01d81b83cd8ccc80c0ea0922a677ecef. +// +// Solidity: event FlashLoanCompleted(address indexed token, address indexed borrower, uint256 amount, uint256 feeAmount) +func (_Bancor *BancorFilterer) ParseFlashLoanCompleted(log types.Log) (*BancorFlashLoanCompleted, error) { + event := new(BancorFlashLoanCompleted) + if err := _Bancor.contract.UnpackLog(event, "FlashLoanCompleted", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorFundsMigratedIterator is returned from FilterFundsMigrated and is used to iterate over the raw logs and unpacked data for FundsMigrated events raised by the Bancor contract. +type BancorFundsMigratedIterator struct { + Event *BancorFundsMigrated // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorFundsMigratedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorFundsMigrated) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorFundsMigrated) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorFundsMigratedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorFundsMigratedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorFundsMigrated represents a FundsMigrated event raised by the Bancor contract. +type BancorFundsMigrated struct { + ContextId [32]byte + Token common.Address + Provider common.Address + Amount *big.Int + AvailableAmount *big.Int + OriginalAmount *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterFundsMigrated is a free log retrieval operation binding the contract event 0x102bce4e43a6a8cf0306fde6154221c1f5460f64ba63b92b156bce998ef0db56. +// +// Solidity: event FundsMigrated(bytes32 indexed contextId, address indexed token, address indexed provider, uint256 amount, uint256 availableAmount, uint256 originalAmount) +func (_Bancor *BancorFilterer) FilterFundsMigrated(opts *bind.FilterOpts, contextId [][32]byte, token []common.Address, provider []common.Address) (*BancorFundsMigratedIterator, error) { + + var contextIdRule []interface{} + for _, contextIdItem := range contextId { + contextIdRule = append(contextIdRule, contextIdItem) + } + var tokenRule []interface{} + for _, tokenItem := range token { + tokenRule = append(tokenRule, tokenItem) + } + var providerRule []interface{} + for _, providerItem := range provider { + providerRule = append(providerRule, providerItem) + } + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "FundsMigrated", contextIdRule, tokenRule, providerRule) + if err != nil { + return nil, err + } + return &BancorFundsMigratedIterator{contract: _Bancor.contract, event: "FundsMigrated", logs: logs, sub: sub}, nil +} + +// WatchFundsMigrated is a free log subscription operation binding the contract event 0x102bce4e43a6a8cf0306fde6154221c1f5460f64ba63b92b156bce998ef0db56. +// +// Solidity: event FundsMigrated(bytes32 indexed contextId, address indexed token, address indexed provider, uint256 amount, uint256 availableAmount, uint256 originalAmount) +func (_Bancor *BancorFilterer) WatchFundsMigrated(opts *bind.WatchOpts, sink chan<- *BancorFundsMigrated, contextId [][32]byte, token []common.Address, provider []common.Address) (event.Subscription, error) { + + var contextIdRule []interface{} + for _, contextIdItem := range contextId { + contextIdRule = append(contextIdRule, contextIdItem) + } + var tokenRule []interface{} + for _, tokenItem := range token { + tokenRule = append(tokenRule, tokenItem) + } + var providerRule []interface{} + for _, providerItem := range provider { + providerRule = append(providerRule, providerItem) + } + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "FundsMigrated", contextIdRule, tokenRule, providerRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorFundsMigrated) + if err := _Bancor.contract.UnpackLog(event, "FundsMigrated", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseFundsMigrated is a log parse operation binding the contract event 0x102bce4e43a6a8cf0306fde6154221c1f5460f64ba63b92b156bce998ef0db56. +// +// Solidity: event FundsMigrated(bytes32 indexed contextId, address indexed token, address indexed provider, uint256 amount, uint256 availableAmount, uint256 originalAmount) +func (_Bancor *BancorFilterer) ParseFundsMigrated(log types.Log) (*BancorFundsMigrated, error) { + event := new(BancorFundsMigrated) + if err := _Bancor.contract.UnpackLog(event, "FundsMigrated", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorNetworkFeesWithdrawnIterator is returned from FilterNetworkFeesWithdrawn and is used to iterate over the raw logs and unpacked data for NetworkFeesWithdrawn events raised by the Bancor contract. +type BancorNetworkFeesWithdrawnIterator struct { + Event *BancorNetworkFeesWithdrawn // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorNetworkFeesWithdrawnIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorNetworkFeesWithdrawn) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorNetworkFeesWithdrawn) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorNetworkFeesWithdrawnIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorNetworkFeesWithdrawnIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorNetworkFeesWithdrawn represents a NetworkFeesWithdrawn event raised by the Bancor contract. +type BancorNetworkFeesWithdrawn struct { + Caller common.Address + Recipient common.Address + Amount *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterNetworkFeesWithdrawn is a free log retrieval operation binding the contract event 0x328c9cc28e75030423307e732b07659ae452a620281f3e54e838000a7f467538. +// +// Solidity: event NetworkFeesWithdrawn(address indexed caller, address indexed recipient, uint256 amount) +func (_Bancor *BancorFilterer) FilterNetworkFeesWithdrawn(opts *bind.FilterOpts, caller []common.Address, recipient []common.Address) (*BancorNetworkFeesWithdrawnIterator, error) { + + var callerRule []interface{} + for _, callerItem := range caller { + callerRule = append(callerRule, callerItem) + } + var recipientRule []interface{} + for _, recipientItem := range recipient { + recipientRule = append(recipientRule, recipientItem) + } + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "NetworkFeesWithdrawn", callerRule, recipientRule) + if err != nil { + return nil, err + } + return &BancorNetworkFeesWithdrawnIterator{contract: _Bancor.contract, event: "NetworkFeesWithdrawn", logs: logs, sub: sub}, nil +} + +// WatchNetworkFeesWithdrawn is a free log subscription operation binding the contract event 0x328c9cc28e75030423307e732b07659ae452a620281f3e54e838000a7f467538. +// +// Solidity: event NetworkFeesWithdrawn(address indexed caller, address indexed recipient, uint256 amount) +func (_Bancor *BancorFilterer) WatchNetworkFeesWithdrawn(opts *bind.WatchOpts, sink chan<- *BancorNetworkFeesWithdrawn, caller []common.Address, recipient []common.Address) (event.Subscription, error) { + + var callerRule []interface{} + for _, callerItem := range caller { + callerRule = append(callerRule, callerItem) + } + var recipientRule []interface{} + for _, recipientItem := range recipient { + recipientRule = append(recipientRule, recipientItem) + } + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "NetworkFeesWithdrawn", callerRule, recipientRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorNetworkFeesWithdrawn) + if err := _Bancor.contract.UnpackLog(event, "NetworkFeesWithdrawn", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseNetworkFeesWithdrawn is a log parse operation binding the contract event 0x328c9cc28e75030423307e732b07659ae452a620281f3e54e838000a7f467538. +// +// Solidity: event NetworkFeesWithdrawn(address indexed caller, address indexed recipient, uint256 amount) +func (_Bancor *BancorFilterer) ParseNetworkFeesWithdrawn(log types.Log) (*BancorNetworkFeesWithdrawn, error) { + event := new(BancorNetworkFeesWithdrawn) + if err := _Bancor.contract.UnpackLog(event, "NetworkFeesWithdrawn", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorPOLRewardsPPMUpdatedIterator is returned from FilterPOLRewardsPPMUpdated and is used to iterate over the raw logs and unpacked data for POLRewardsPPMUpdated events raised by the Bancor contract. +type BancorPOLRewardsPPMUpdatedIterator struct { + Event *BancorPOLRewardsPPMUpdated // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorPOLRewardsPPMUpdatedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorPOLRewardsPPMUpdated) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorPOLRewardsPPMUpdated) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorPOLRewardsPPMUpdatedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorPOLRewardsPPMUpdatedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorPOLRewardsPPMUpdated represents a POLRewardsPPMUpdated event raised by the Bancor contract. +type BancorPOLRewardsPPMUpdated struct { + OldRewardsPPM uint32 + NewRewardsPPM uint32 + Raw types.Log // Blockchain specific contextual infos +} + +// FilterPOLRewardsPPMUpdated is a free log retrieval operation binding the contract event 0xa159b13d7eac36d9a65034b4fd6ace1d9cb070d063dc950c564a266f4d091802. +// +// Solidity: event POLRewardsPPMUpdated(uint32 oldRewardsPPM, uint32 newRewardsPPM) +func (_Bancor *BancorFilterer) FilterPOLRewardsPPMUpdated(opts *bind.FilterOpts) (*BancorPOLRewardsPPMUpdatedIterator, error) { + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "POLRewardsPPMUpdated") + if err != nil { + return nil, err + } + return &BancorPOLRewardsPPMUpdatedIterator{contract: _Bancor.contract, event: "POLRewardsPPMUpdated", logs: logs, sub: sub}, nil +} + +// WatchPOLRewardsPPMUpdated is a free log subscription operation binding the contract event 0xa159b13d7eac36d9a65034b4fd6ace1d9cb070d063dc950c564a266f4d091802. +// +// Solidity: event POLRewardsPPMUpdated(uint32 oldRewardsPPM, uint32 newRewardsPPM) +func (_Bancor *BancorFilterer) WatchPOLRewardsPPMUpdated(opts *bind.WatchOpts, sink chan<- *BancorPOLRewardsPPMUpdated) (event.Subscription, error) { + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "POLRewardsPPMUpdated") + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorPOLRewardsPPMUpdated) + if err := _Bancor.contract.UnpackLog(event, "POLRewardsPPMUpdated", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParsePOLRewardsPPMUpdated is a log parse operation binding the contract event 0xa159b13d7eac36d9a65034b4fd6ace1d9cb070d063dc950c564a266f4d091802. +// +// Solidity: event POLRewardsPPMUpdated(uint32 oldRewardsPPM, uint32 newRewardsPPM) +func (_Bancor *BancorFilterer) ParsePOLRewardsPPMUpdated(log types.Log) (*BancorPOLRewardsPPMUpdated, error) { + event := new(BancorPOLRewardsPPMUpdated) + if err := _Bancor.contract.UnpackLog(event, "POLRewardsPPMUpdated", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorPOLWithdrawnIterator is returned from FilterPOLWithdrawn and is used to iterate over the raw logs and unpacked data for POLWithdrawn events raised by the Bancor contract. +type BancorPOLWithdrawnIterator struct { + Event *BancorPOLWithdrawn // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorPOLWithdrawnIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorPOLWithdrawn) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorPOLWithdrawn) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorPOLWithdrawnIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorPOLWithdrawnIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorPOLWithdrawn represents a POLWithdrawn event raised by the Bancor contract. +type BancorPOLWithdrawn struct { + Caller common.Address + Token common.Address + PolTokenAmount *big.Int + UserReward *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterPOLWithdrawn is a free log retrieval operation binding the contract event 0x5ad7a2184454b6259cd118e4041a953dc9d6498302bbe528e4f967bed9197129. +// +// Solidity: event POLWithdrawn(address indexed caller, address indexed token, uint256 polTokenAmount, uint256 userReward) +func (_Bancor *BancorFilterer) FilterPOLWithdrawn(opts *bind.FilterOpts, caller []common.Address, token []common.Address) (*BancorPOLWithdrawnIterator, error) { + + var callerRule []interface{} + for _, callerItem := range caller { + callerRule = append(callerRule, callerItem) + } + var tokenRule []interface{} + for _, tokenItem := range token { + tokenRule = append(tokenRule, tokenItem) + } + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "POLWithdrawn", callerRule, tokenRule) + if err != nil { + return nil, err + } + return &BancorPOLWithdrawnIterator{contract: _Bancor.contract, event: "POLWithdrawn", logs: logs, sub: sub}, nil +} + +// WatchPOLWithdrawn is a free log subscription operation binding the contract event 0x5ad7a2184454b6259cd118e4041a953dc9d6498302bbe528e4f967bed9197129. +// +// Solidity: event POLWithdrawn(address indexed caller, address indexed token, uint256 polTokenAmount, uint256 userReward) +func (_Bancor *BancorFilterer) WatchPOLWithdrawn(opts *bind.WatchOpts, sink chan<- *BancorPOLWithdrawn, caller []common.Address, token []common.Address) (event.Subscription, error) { + + var callerRule []interface{} + for _, callerItem := range caller { + callerRule = append(callerRule, callerItem) + } + var tokenRule []interface{} + for _, tokenItem := range token { + tokenRule = append(tokenRule, tokenItem) + } + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "POLWithdrawn", callerRule, tokenRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorPOLWithdrawn) + if err := _Bancor.contract.UnpackLog(event, "POLWithdrawn", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParsePOLWithdrawn is a log parse operation binding the contract event 0x5ad7a2184454b6259cd118e4041a953dc9d6498302bbe528e4f967bed9197129. +// +// Solidity: event POLWithdrawn(address indexed caller, address indexed token, uint256 polTokenAmount, uint256 userReward) +func (_Bancor *BancorFilterer) ParsePOLWithdrawn(log types.Log) (*BancorPOLWithdrawn, error) { + event := new(BancorPOLWithdrawn) + if err := _Bancor.contract.UnpackLog(event, "POLWithdrawn", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorPausedIterator is returned from FilterPaused and is used to iterate over the raw logs and unpacked data for Paused events raised by the Bancor contract. +type BancorPausedIterator struct { + Event *BancorPaused // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorPausedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorPaused) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorPaused) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorPausedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorPausedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorPaused represents a Paused event raised by the Bancor contract. +type BancorPaused struct { + Account common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterPaused is a free log retrieval operation binding the contract event 0x62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258. +// +// Solidity: event Paused(address account) +func (_Bancor *BancorFilterer) FilterPaused(opts *bind.FilterOpts) (*BancorPausedIterator, error) { + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "Paused") + if err != nil { + return nil, err + } + return &BancorPausedIterator{contract: _Bancor.contract, event: "Paused", logs: logs, sub: sub}, nil +} + +// WatchPaused is a free log subscription operation binding the contract event 0x62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258. +// +// Solidity: event Paused(address account) +func (_Bancor *BancorFilterer) WatchPaused(opts *bind.WatchOpts, sink chan<- *BancorPaused) (event.Subscription, error) { + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "Paused") + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorPaused) + if err := _Bancor.contract.UnpackLog(event, "Paused", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParsePaused is a log parse operation binding the contract event 0x62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258. +// +// Solidity: event Paused(address account) +func (_Bancor *BancorFilterer) ParsePaused(log types.Log) (*BancorPaused, error) { + event := new(BancorPaused) + if err := _Bancor.contract.UnpackLog(event, "Paused", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorPoolAddedIterator is returned from FilterPoolAdded and is used to iterate over the raw logs and unpacked data for PoolAdded events raised by the Bancor contract. +type BancorPoolAddedIterator struct { + Event *BancorPoolAdded // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorPoolAddedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorPoolAdded) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorPoolAdded) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorPoolAddedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorPoolAddedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorPoolAdded represents a PoolAdded event raised by the Bancor contract. +type BancorPoolAdded struct { + Pool common.Address + PoolCollection common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterPoolAdded is a free log retrieval operation binding the contract event 0x95f865c2808f8b2a85eea2611db7843150ee7835ef1403f9755918a97d76933c. +// +// Solidity: event PoolAdded(address indexed pool, address indexed poolCollection) +func (_Bancor *BancorFilterer) FilterPoolAdded(opts *bind.FilterOpts, pool []common.Address, poolCollection []common.Address) (*BancorPoolAddedIterator, error) { + + var poolRule []interface{} + for _, poolItem := range pool { + poolRule = append(poolRule, poolItem) + } + var poolCollectionRule []interface{} + for _, poolCollectionItem := range poolCollection { + poolCollectionRule = append(poolCollectionRule, poolCollectionItem) + } + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "PoolAdded", poolRule, poolCollectionRule) + if err != nil { + return nil, err + } + return &BancorPoolAddedIterator{contract: _Bancor.contract, event: "PoolAdded", logs: logs, sub: sub}, nil +} + +// WatchPoolAdded is a free log subscription operation binding the contract event 0x95f865c2808f8b2a85eea2611db7843150ee7835ef1403f9755918a97d76933c. +// +// Solidity: event PoolAdded(address indexed pool, address indexed poolCollection) +func (_Bancor *BancorFilterer) WatchPoolAdded(opts *bind.WatchOpts, sink chan<- *BancorPoolAdded, pool []common.Address, poolCollection []common.Address) (event.Subscription, error) { + + var poolRule []interface{} + for _, poolItem := range pool { + poolRule = append(poolRule, poolItem) + } + var poolCollectionRule []interface{} + for _, poolCollectionItem := range poolCollection { + poolCollectionRule = append(poolCollectionRule, poolCollectionItem) + } + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "PoolAdded", poolRule, poolCollectionRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorPoolAdded) + if err := _Bancor.contract.UnpackLog(event, "PoolAdded", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParsePoolAdded is a log parse operation binding the contract event 0x95f865c2808f8b2a85eea2611db7843150ee7835ef1403f9755918a97d76933c. +// +// Solidity: event PoolAdded(address indexed pool, address indexed poolCollection) +func (_Bancor *BancorFilterer) ParsePoolAdded(log types.Log) (*BancorPoolAdded, error) { + event := new(BancorPoolAdded) + if err := _Bancor.contract.UnpackLog(event, "PoolAdded", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorPoolCollectionAddedIterator is returned from FilterPoolCollectionAdded and is used to iterate over the raw logs and unpacked data for PoolCollectionAdded events raised by the Bancor contract. +type BancorPoolCollectionAddedIterator struct { + Event *BancorPoolCollectionAdded // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorPoolCollectionAddedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorPoolCollectionAdded) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorPoolCollectionAdded) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorPoolCollectionAddedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorPoolCollectionAddedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorPoolCollectionAdded represents a PoolCollectionAdded event raised by the Bancor contract. +type BancorPoolCollectionAdded struct { + PoolType uint16 + PoolCollection common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterPoolCollectionAdded is a free log retrieval operation binding the contract event 0x5ae87719d73cb0fabb219f0e4b6e0a614ed7506f8a08bdb20bebf313573151b7. +// +// Solidity: event PoolCollectionAdded(uint16 indexed poolType, address indexed poolCollection) +func (_Bancor *BancorFilterer) FilterPoolCollectionAdded(opts *bind.FilterOpts, poolType []uint16, poolCollection []common.Address) (*BancorPoolCollectionAddedIterator, error) { + + var poolTypeRule []interface{} + for _, poolTypeItem := range poolType { + poolTypeRule = append(poolTypeRule, poolTypeItem) + } + var poolCollectionRule []interface{} + for _, poolCollectionItem := range poolCollection { + poolCollectionRule = append(poolCollectionRule, poolCollectionItem) + } + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "PoolCollectionAdded", poolTypeRule, poolCollectionRule) + if err != nil { + return nil, err + } + return &BancorPoolCollectionAddedIterator{contract: _Bancor.contract, event: "PoolCollectionAdded", logs: logs, sub: sub}, nil +} + +// WatchPoolCollectionAdded is a free log subscription operation binding the contract event 0x5ae87719d73cb0fabb219f0e4b6e0a614ed7506f8a08bdb20bebf313573151b7. +// +// Solidity: event PoolCollectionAdded(uint16 indexed poolType, address indexed poolCollection) +func (_Bancor *BancorFilterer) WatchPoolCollectionAdded(opts *bind.WatchOpts, sink chan<- *BancorPoolCollectionAdded, poolType []uint16, poolCollection []common.Address) (event.Subscription, error) { + + var poolTypeRule []interface{} + for _, poolTypeItem := range poolType { + poolTypeRule = append(poolTypeRule, poolTypeItem) + } + var poolCollectionRule []interface{} + for _, poolCollectionItem := range poolCollection { + poolCollectionRule = append(poolCollectionRule, poolCollectionItem) + } + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "PoolCollectionAdded", poolTypeRule, poolCollectionRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorPoolCollectionAdded) + if err := _Bancor.contract.UnpackLog(event, "PoolCollectionAdded", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParsePoolCollectionAdded is a log parse operation binding the contract event 0x5ae87719d73cb0fabb219f0e4b6e0a614ed7506f8a08bdb20bebf313573151b7. +// +// Solidity: event PoolCollectionAdded(uint16 indexed poolType, address indexed poolCollection) +func (_Bancor *BancorFilterer) ParsePoolCollectionAdded(log types.Log) (*BancorPoolCollectionAdded, error) { + event := new(BancorPoolCollectionAdded) + if err := _Bancor.contract.UnpackLog(event, "PoolCollectionAdded", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorPoolCollectionRemovedIterator is returned from FilterPoolCollectionRemoved and is used to iterate over the raw logs and unpacked data for PoolCollectionRemoved events raised by the Bancor contract. +type BancorPoolCollectionRemovedIterator struct { + Event *BancorPoolCollectionRemoved // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorPoolCollectionRemovedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorPoolCollectionRemoved) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorPoolCollectionRemoved) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorPoolCollectionRemovedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorPoolCollectionRemovedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorPoolCollectionRemoved represents a PoolCollectionRemoved event raised by the Bancor contract. +type BancorPoolCollectionRemoved struct { + PoolType uint16 + PoolCollection common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterPoolCollectionRemoved is a free log retrieval operation binding the contract event 0xa0c1e3924f995e5ba38f53b4effb6d4b3eeb84176a2951c589115140f638ac09. +// +// Solidity: event PoolCollectionRemoved(uint16 indexed poolType, address indexed poolCollection) +func (_Bancor *BancorFilterer) FilterPoolCollectionRemoved(opts *bind.FilterOpts, poolType []uint16, poolCollection []common.Address) (*BancorPoolCollectionRemovedIterator, error) { + + var poolTypeRule []interface{} + for _, poolTypeItem := range poolType { + poolTypeRule = append(poolTypeRule, poolTypeItem) + } + var poolCollectionRule []interface{} + for _, poolCollectionItem := range poolCollection { + poolCollectionRule = append(poolCollectionRule, poolCollectionItem) + } + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "PoolCollectionRemoved", poolTypeRule, poolCollectionRule) + if err != nil { + return nil, err + } + return &BancorPoolCollectionRemovedIterator{contract: _Bancor.contract, event: "PoolCollectionRemoved", logs: logs, sub: sub}, nil +} + +// WatchPoolCollectionRemoved is a free log subscription operation binding the contract event 0xa0c1e3924f995e5ba38f53b4effb6d4b3eeb84176a2951c589115140f638ac09. +// +// Solidity: event PoolCollectionRemoved(uint16 indexed poolType, address indexed poolCollection) +func (_Bancor *BancorFilterer) WatchPoolCollectionRemoved(opts *bind.WatchOpts, sink chan<- *BancorPoolCollectionRemoved, poolType []uint16, poolCollection []common.Address) (event.Subscription, error) { + + var poolTypeRule []interface{} + for _, poolTypeItem := range poolType { + poolTypeRule = append(poolTypeRule, poolTypeItem) + } + var poolCollectionRule []interface{} + for _, poolCollectionItem := range poolCollection { + poolCollectionRule = append(poolCollectionRule, poolCollectionItem) + } + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "PoolCollectionRemoved", poolTypeRule, poolCollectionRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorPoolCollectionRemoved) + if err := _Bancor.contract.UnpackLog(event, "PoolCollectionRemoved", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParsePoolCollectionRemoved is a log parse operation binding the contract event 0xa0c1e3924f995e5ba38f53b4effb6d4b3eeb84176a2951c589115140f638ac09. +// +// Solidity: event PoolCollectionRemoved(uint16 indexed poolType, address indexed poolCollection) +func (_Bancor *BancorFilterer) ParsePoolCollectionRemoved(log types.Log) (*BancorPoolCollectionRemoved, error) { + event := new(BancorPoolCollectionRemoved) + if err := _Bancor.contract.UnpackLog(event, "PoolCollectionRemoved", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorPoolCreatedIterator is returned from FilterPoolCreated and is used to iterate over the raw logs and unpacked data for PoolCreated events raised by the Bancor contract. +type BancorPoolCreatedIterator struct { + Event *BancorPoolCreated // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorPoolCreatedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorPoolCreated) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorPoolCreated) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorPoolCreatedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorPoolCreatedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorPoolCreated represents a PoolCreated event raised by the Bancor contract. +type BancorPoolCreated struct { + Pool common.Address + PoolCollection common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterPoolCreated is a free log retrieval operation binding the contract event 0x4f2ce4e40f623ca765fc0167a25cb7842ceaafb8d82d3dec26ca0d0e0d2d4896. +// +// Solidity: event PoolCreated(address indexed pool, address indexed poolCollection) +func (_Bancor *BancorFilterer) FilterPoolCreated(opts *bind.FilterOpts, pool []common.Address, poolCollection []common.Address) (*BancorPoolCreatedIterator, error) { + + var poolRule []interface{} + for _, poolItem := range pool { + poolRule = append(poolRule, poolItem) + } + var poolCollectionRule []interface{} + for _, poolCollectionItem := range poolCollection { + poolCollectionRule = append(poolCollectionRule, poolCollectionItem) + } + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "PoolCreated", poolRule, poolCollectionRule) + if err != nil { + return nil, err + } + return &BancorPoolCreatedIterator{contract: _Bancor.contract, event: "PoolCreated", logs: logs, sub: sub}, nil +} + +// WatchPoolCreated is a free log subscription operation binding the contract event 0x4f2ce4e40f623ca765fc0167a25cb7842ceaafb8d82d3dec26ca0d0e0d2d4896. +// +// Solidity: event PoolCreated(address indexed pool, address indexed poolCollection) +func (_Bancor *BancorFilterer) WatchPoolCreated(opts *bind.WatchOpts, sink chan<- *BancorPoolCreated, pool []common.Address, poolCollection []common.Address) (event.Subscription, error) { + + var poolRule []interface{} + for _, poolItem := range pool { + poolRule = append(poolRule, poolItem) + } + var poolCollectionRule []interface{} + for _, poolCollectionItem := range poolCollection { + poolCollectionRule = append(poolCollectionRule, poolCollectionItem) + } + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "PoolCreated", poolRule, poolCollectionRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorPoolCreated) + if err := _Bancor.contract.UnpackLog(event, "PoolCreated", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParsePoolCreated is a log parse operation binding the contract event 0x4f2ce4e40f623ca765fc0167a25cb7842ceaafb8d82d3dec26ca0d0e0d2d4896. +// +// Solidity: event PoolCreated(address indexed pool, address indexed poolCollection) +func (_Bancor *BancorFilterer) ParsePoolCreated(log types.Log) (*BancorPoolCreated, error) { + event := new(BancorPoolCreated) + if err := _Bancor.contract.UnpackLog(event, "PoolCreated", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorPoolRemovedIterator is returned from FilterPoolRemoved and is used to iterate over the raw logs and unpacked data for PoolRemoved events raised by the Bancor contract. +type BancorPoolRemovedIterator struct { + Event *BancorPoolRemoved // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorPoolRemovedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorPoolRemoved) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorPoolRemoved) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorPoolRemovedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorPoolRemovedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorPoolRemoved represents a PoolRemoved event raised by the Bancor contract. +type BancorPoolRemoved struct { + Pool common.Address + PoolCollection common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterPoolRemoved is a free log retrieval operation binding the contract event 0x987eb3c2f78454541205f72f34839b434c306c9eaf4922efd7c0c3060fdb2e4c. +// +// Solidity: event PoolRemoved(address indexed pool, address indexed poolCollection) +func (_Bancor *BancorFilterer) FilterPoolRemoved(opts *bind.FilterOpts, pool []common.Address, poolCollection []common.Address) (*BancorPoolRemovedIterator, error) { + + var poolRule []interface{} + for _, poolItem := range pool { + poolRule = append(poolRule, poolItem) + } + var poolCollectionRule []interface{} + for _, poolCollectionItem := range poolCollection { + poolCollectionRule = append(poolCollectionRule, poolCollectionItem) + } + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "PoolRemoved", poolRule, poolCollectionRule) + if err != nil { + return nil, err + } + return &BancorPoolRemovedIterator{contract: _Bancor.contract, event: "PoolRemoved", logs: logs, sub: sub}, nil +} + +// WatchPoolRemoved is a free log subscription operation binding the contract event 0x987eb3c2f78454541205f72f34839b434c306c9eaf4922efd7c0c3060fdb2e4c. +// +// Solidity: event PoolRemoved(address indexed pool, address indexed poolCollection) +func (_Bancor *BancorFilterer) WatchPoolRemoved(opts *bind.WatchOpts, sink chan<- *BancorPoolRemoved, pool []common.Address, poolCollection []common.Address) (event.Subscription, error) { + + var poolRule []interface{} + for _, poolItem := range pool { + poolRule = append(poolRule, poolItem) + } + var poolCollectionRule []interface{} + for _, poolCollectionItem := range poolCollection { + poolCollectionRule = append(poolCollectionRule, poolCollectionItem) + } + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "PoolRemoved", poolRule, poolCollectionRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorPoolRemoved) + if err := _Bancor.contract.UnpackLog(event, "PoolRemoved", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParsePoolRemoved is a log parse operation binding the contract event 0x987eb3c2f78454541205f72f34839b434c306c9eaf4922efd7c0c3060fdb2e4c. +// +// Solidity: event PoolRemoved(address indexed pool, address indexed poolCollection) +func (_Bancor *BancorFilterer) ParsePoolRemoved(log types.Log) (*BancorPoolRemoved, error) { + event := new(BancorPoolRemoved) + if err := _Bancor.contract.UnpackLog(event, "PoolRemoved", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorRoleAdminChangedIterator is returned from FilterRoleAdminChanged and is used to iterate over the raw logs and unpacked data for RoleAdminChanged events raised by the Bancor contract. +type BancorRoleAdminChangedIterator struct { + Event *BancorRoleAdminChanged // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorRoleAdminChangedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorRoleAdminChanged) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorRoleAdminChanged) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorRoleAdminChangedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorRoleAdminChangedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorRoleAdminChanged represents a RoleAdminChanged event raised by the Bancor contract. +type BancorRoleAdminChanged struct { + Role [32]byte + PreviousAdminRole [32]byte + NewAdminRole [32]byte + Raw types.Log // Blockchain specific contextual infos +} + +// FilterRoleAdminChanged is a free log retrieval operation binding the contract event 0xbd79b86ffe0ab8e8776151514217cd7cacd52c909f66475c3af44e129f0b00ff. +// +// Solidity: event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole) +func (_Bancor *BancorFilterer) FilterRoleAdminChanged(opts *bind.FilterOpts, role [][32]byte, previousAdminRole [][32]byte, newAdminRole [][32]byte) (*BancorRoleAdminChangedIterator, error) { + + var roleRule []interface{} + for _, roleItem := range role { + roleRule = append(roleRule, roleItem) + } + var previousAdminRoleRule []interface{} + for _, previousAdminRoleItem := range previousAdminRole { + previousAdminRoleRule = append(previousAdminRoleRule, previousAdminRoleItem) + } + var newAdminRoleRule []interface{} + for _, newAdminRoleItem := range newAdminRole { + newAdminRoleRule = append(newAdminRoleRule, newAdminRoleItem) + } + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "RoleAdminChanged", roleRule, previousAdminRoleRule, newAdminRoleRule) + if err != nil { + return nil, err + } + return &BancorRoleAdminChangedIterator{contract: _Bancor.contract, event: "RoleAdminChanged", logs: logs, sub: sub}, nil +} + +// WatchRoleAdminChanged is a free log subscription operation binding the contract event 0xbd79b86ffe0ab8e8776151514217cd7cacd52c909f66475c3af44e129f0b00ff. +// +// Solidity: event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole) +func (_Bancor *BancorFilterer) WatchRoleAdminChanged(opts *bind.WatchOpts, sink chan<- *BancorRoleAdminChanged, role [][32]byte, previousAdminRole [][32]byte, newAdminRole [][32]byte) (event.Subscription, error) { + + var roleRule []interface{} + for _, roleItem := range role { + roleRule = append(roleRule, roleItem) + } + var previousAdminRoleRule []interface{} + for _, previousAdminRoleItem := range previousAdminRole { + previousAdminRoleRule = append(previousAdminRoleRule, previousAdminRoleItem) + } + var newAdminRoleRule []interface{} + for _, newAdminRoleItem := range newAdminRole { + newAdminRoleRule = append(newAdminRoleRule, newAdminRoleItem) + } + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "RoleAdminChanged", roleRule, previousAdminRoleRule, newAdminRoleRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorRoleAdminChanged) + if err := _Bancor.contract.UnpackLog(event, "RoleAdminChanged", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseRoleAdminChanged is a log parse operation binding the contract event 0xbd79b86ffe0ab8e8776151514217cd7cacd52c909f66475c3af44e129f0b00ff. +// +// Solidity: event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole) +func (_Bancor *BancorFilterer) ParseRoleAdminChanged(log types.Log) (*BancorRoleAdminChanged, error) { + event := new(BancorRoleAdminChanged) + if err := _Bancor.contract.UnpackLog(event, "RoleAdminChanged", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorRoleGrantedIterator is returned from FilterRoleGranted and is used to iterate over the raw logs and unpacked data for RoleGranted events raised by the Bancor contract. +type BancorRoleGrantedIterator struct { + Event *BancorRoleGranted // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorRoleGrantedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorRoleGranted) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorRoleGranted) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorRoleGrantedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorRoleGrantedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorRoleGranted represents a RoleGranted event raised by the Bancor contract. +type BancorRoleGranted struct { + Role [32]byte + Account common.Address + Sender common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterRoleGranted is a free log retrieval operation binding the contract event 0x2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d. +// +// Solidity: event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender) +func (_Bancor *BancorFilterer) FilterRoleGranted(opts *bind.FilterOpts, role [][32]byte, account []common.Address, sender []common.Address) (*BancorRoleGrantedIterator, error) { + + var roleRule []interface{} + for _, roleItem := range role { + roleRule = append(roleRule, roleItem) + } + var accountRule []interface{} + for _, accountItem := range account { + accountRule = append(accountRule, accountItem) + } + var senderRule []interface{} + for _, senderItem := range sender { + senderRule = append(senderRule, senderItem) + } + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "RoleGranted", roleRule, accountRule, senderRule) + if err != nil { + return nil, err + } + return &BancorRoleGrantedIterator{contract: _Bancor.contract, event: "RoleGranted", logs: logs, sub: sub}, nil +} + +// WatchRoleGranted is a free log subscription operation binding the contract event 0x2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d. +// +// Solidity: event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender) +func (_Bancor *BancorFilterer) WatchRoleGranted(opts *bind.WatchOpts, sink chan<- *BancorRoleGranted, role [][32]byte, account []common.Address, sender []common.Address) (event.Subscription, error) { + + var roleRule []interface{} + for _, roleItem := range role { + roleRule = append(roleRule, roleItem) + } + var accountRule []interface{} + for _, accountItem := range account { + accountRule = append(accountRule, accountItem) + } + var senderRule []interface{} + for _, senderItem := range sender { + senderRule = append(senderRule, senderItem) + } + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "RoleGranted", roleRule, accountRule, senderRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorRoleGranted) + if err := _Bancor.contract.UnpackLog(event, "RoleGranted", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseRoleGranted is a log parse operation binding the contract event 0x2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d. +// +// Solidity: event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender) +func (_Bancor *BancorFilterer) ParseRoleGranted(log types.Log) (*BancorRoleGranted, error) { + event := new(BancorRoleGranted) + if err := _Bancor.contract.UnpackLog(event, "RoleGranted", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorRoleRevokedIterator is returned from FilterRoleRevoked and is used to iterate over the raw logs and unpacked data for RoleRevoked events raised by the Bancor contract. +type BancorRoleRevokedIterator struct { + Event *BancorRoleRevoked // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorRoleRevokedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorRoleRevoked) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorRoleRevoked) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorRoleRevokedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorRoleRevokedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorRoleRevoked represents a RoleRevoked event raised by the Bancor contract. +type BancorRoleRevoked struct { + Role [32]byte + Account common.Address + Sender common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterRoleRevoked is a free log retrieval operation binding the contract event 0xf6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b. +// +// Solidity: event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender) +func (_Bancor *BancorFilterer) FilterRoleRevoked(opts *bind.FilterOpts, role [][32]byte, account []common.Address, sender []common.Address) (*BancorRoleRevokedIterator, error) { + + var roleRule []interface{} + for _, roleItem := range role { + roleRule = append(roleRule, roleItem) + } + var accountRule []interface{} + for _, accountItem := range account { + accountRule = append(accountRule, accountItem) + } + var senderRule []interface{} + for _, senderItem := range sender { + senderRule = append(senderRule, senderItem) + } + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "RoleRevoked", roleRule, accountRule, senderRule) + if err != nil { + return nil, err + } + return &BancorRoleRevokedIterator{contract: _Bancor.contract, event: "RoleRevoked", logs: logs, sub: sub}, nil +} + +// WatchRoleRevoked is a free log subscription operation binding the contract event 0xf6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b. +// +// Solidity: event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender) +func (_Bancor *BancorFilterer) WatchRoleRevoked(opts *bind.WatchOpts, sink chan<- *BancorRoleRevoked, role [][32]byte, account []common.Address, sender []common.Address) (event.Subscription, error) { + + var roleRule []interface{} + for _, roleItem := range role { + roleRule = append(roleRule, roleItem) + } + var accountRule []interface{} + for _, accountItem := range account { + accountRule = append(accountRule, accountItem) + } + var senderRule []interface{} + for _, senderItem := range sender { + senderRule = append(senderRule, senderItem) + } + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "RoleRevoked", roleRule, accountRule, senderRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorRoleRevoked) + if err := _Bancor.contract.UnpackLog(event, "RoleRevoked", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseRoleRevoked is a log parse operation binding the contract event 0xf6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b. +// +// Solidity: event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender) +func (_Bancor *BancorFilterer) ParseRoleRevoked(log types.Log) (*BancorRoleRevoked, error) { + event := new(BancorRoleRevoked) + if err := _Bancor.contract.UnpackLog(event, "RoleRevoked", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorTokensTradedIterator is returned from FilterTokensTraded and is used to iterate over the raw logs and unpacked data for TokensTraded events raised by the Bancor contract. +type BancorTokensTradedIterator struct { + Event *BancorTokensTraded // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorTokensTradedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorTokensTraded) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorTokensTraded) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorTokensTradedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorTokensTradedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorTokensTraded represents a TokensTraded event raised by the Bancor contract. +type BancorTokensTraded struct { + ContextId [32]byte + SourceToken common.Address + TargetToken common.Address + SourceAmount *big.Int + TargetAmount *big.Int + BntAmount *big.Int + TargetFeeAmount *big.Int + BntFeeAmount *big.Int + Trader common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterTokensTraded is a free log retrieval operation binding the contract event 0x5c02c2bb2d1d082317eb23916ca27b3e7c294398b60061a2ad54f1c3c018c318. +// +// Solidity: event TokensTraded(bytes32 indexed contextId, address indexed sourceToken, address indexed targetToken, uint256 sourceAmount, uint256 targetAmount, uint256 bntAmount, uint256 targetFeeAmount, uint256 bntFeeAmount, address trader) +func (_Bancor *BancorFilterer) FilterTokensTraded(opts *bind.FilterOpts, contextId [][32]byte, sourceToken []common.Address, targetToken []common.Address) (*BancorTokensTradedIterator, error) { + + var contextIdRule []interface{} + for _, contextIdItem := range contextId { + contextIdRule = append(contextIdRule, contextIdItem) + } + var sourceTokenRule []interface{} + for _, sourceTokenItem := range sourceToken { + sourceTokenRule = append(sourceTokenRule, sourceTokenItem) + } + var targetTokenRule []interface{} + for _, targetTokenItem := range targetToken { + targetTokenRule = append(targetTokenRule, targetTokenItem) + } + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "TokensTraded", contextIdRule, sourceTokenRule, targetTokenRule) + if err != nil { + return nil, err + } + return &BancorTokensTradedIterator{contract: _Bancor.contract, event: "TokensTraded", logs: logs, sub: sub}, nil +} + +// WatchTokensTraded is a free log subscription operation binding the contract event 0x5c02c2bb2d1d082317eb23916ca27b3e7c294398b60061a2ad54f1c3c018c318. +// +// Solidity: event TokensTraded(bytes32 indexed contextId, address indexed sourceToken, address indexed targetToken, uint256 sourceAmount, uint256 targetAmount, uint256 bntAmount, uint256 targetFeeAmount, uint256 bntFeeAmount, address trader) +func (_Bancor *BancorFilterer) WatchTokensTraded(opts *bind.WatchOpts, sink chan<- *BancorTokensTraded, contextId [][32]byte, sourceToken []common.Address, targetToken []common.Address) (event.Subscription, error) { + + var contextIdRule []interface{} + for _, contextIdItem := range contextId { + contextIdRule = append(contextIdRule, contextIdItem) + } + var sourceTokenRule []interface{} + for _, sourceTokenItem := range sourceToken { + sourceTokenRule = append(sourceTokenRule, sourceTokenItem) + } + var targetTokenRule []interface{} + for _, targetTokenItem := range targetToken { + targetTokenRule = append(targetTokenRule, targetTokenItem) + } + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "TokensTraded", contextIdRule, sourceTokenRule, targetTokenRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorTokensTraded) + if err := _Bancor.contract.UnpackLog(event, "TokensTraded", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseTokensTraded is a log parse operation binding the contract event 0x5c02c2bb2d1d082317eb23916ca27b3e7c294398b60061a2ad54f1c3c018c318. +// +// Solidity: event TokensTraded(bytes32 indexed contextId, address indexed sourceToken, address indexed targetToken, uint256 sourceAmount, uint256 targetAmount, uint256 bntAmount, uint256 targetFeeAmount, uint256 bntFeeAmount, address trader) +func (_Bancor *BancorFilterer) ParseTokensTraded(log types.Log) (*BancorTokensTraded, error) { + event := new(BancorTokensTraded) + if err := _Bancor.contract.UnpackLog(event, "TokensTraded", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorUnpausedIterator is returned from FilterUnpaused and is used to iterate over the raw logs and unpacked data for Unpaused events raised by the Bancor contract. +type BancorUnpausedIterator struct { + Event *BancorUnpaused // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorUnpausedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorUnpaused) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorUnpaused) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorUnpausedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorUnpausedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorUnpaused represents a Unpaused event raised by the Bancor contract. +type BancorUnpaused struct { + Account common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterUnpaused is a free log retrieval operation binding the contract event 0x5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa. +// +// Solidity: event Unpaused(address account) +func (_Bancor *BancorFilterer) FilterUnpaused(opts *bind.FilterOpts) (*BancorUnpausedIterator, error) { + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "Unpaused") + if err != nil { + return nil, err + } + return &BancorUnpausedIterator{contract: _Bancor.contract, event: "Unpaused", logs: logs, sub: sub}, nil +} + +// WatchUnpaused is a free log subscription operation binding the contract event 0x5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa. +// +// Solidity: event Unpaused(address account) +func (_Bancor *BancorFilterer) WatchUnpaused(opts *bind.WatchOpts, sink chan<- *BancorUnpaused) (event.Subscription, error) { + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "Unpaused") + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorUnpaused) + if err := _Bancor.contract.UnpackLog(event, "Unpaused", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseUnpaused is a log parse operation binding the contract event 0x5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa. +// +// Solidity: event Unpaused(address account) +func (_Bancor *BancorFilterer) ParseUnpaused(log types.Log) (*BancorUnpaused, error) { + event := new(BancorUnpaused) + if err := _Bancor.contract.UnpackLog(event, "Unpaused", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} diff --git a/zcnbridge/ethereum/bind.sh b/zcnbridge/ethereum/bind.sh deleted file mode 100755 index 321aa610a..000000000 --- a/zcnbridge/ethereum/bind.sh +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/sh -# shellcheck disable=SC2164 -cd ./erc20 -#solc --abi ERC20.sol | awk '/JSON ABI/{x=1;next}x' > erc20.abi -#solc --bin ERC20.sol | awk '/Binary:/{x=1;next}x' > erc20.bin -#abigen --bin=erc20.bin --abi=erc20.abi --pkg=erc20 --out=erc20.go -abigen --pkg erc20 --sol ERC20.sol --out ./erc20.go diff --git a/zcnbridge/ethereum/erc20/Context.sol b/zcnbridge/ethereum/erc20/Context.sol deleted file mode 100644 index 052c09172..000000000 --- a/zcnbridge/ethereum/erc20/Context.sol +++ /dev/null @@ -1,24 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.3.2 (utils/Context.sol) - -pragma solidity ^0.8.0; - -/** - * @dev Provides information about the current execution context, including the - * sender of the transaction and its data. While these are generally available - * via msg.sender and msg.data, they should not be accessed in such a direct - * manner, since when dealing with meta-transactions the account sending and - * paying for execution may not be the actual sender (as far as an application - * is concerned). - * - * This contract is only required for intermediate, library-like contracts. - */ -abstract contract Context { - function _msgSender() internal view virtual returns (address) { - return msg.sender; - } - - function _msgData() internal view virtual returns (bytes calldata) { - return msg.data; - } -} \ No newline at end of file diff --git a/zcnbridge/ethereum/erc20/ERC20.sol b/zcnbridge/ethereum/erc20/ERC20.sol deleted file mode 100644 index 308941e6f..000000000 --- a/zcnbridge/ethereum/erc20/ERC20.sol +++ /dev/null @@ -1,356 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.3.2 (token/ERC20/ERC20.sol) - -pragma solidity ^0.8.0; - -import "./IERC20.sol"; -import "./IERC20Metadata.sol"; -import "./Context.sol"; - -/** - * @dev Implementation of the {IERC20} interface. - * - * This implementation is agnostic to the way tokens are created. This means - * that a supply mechanism has to be added in a derived contract using {_mint}. - * For a generic mechanism see {ERC20PresetMinterPauser}. - * - * TIP: For a detailed writeup see our guide - * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How - * to implement supply mechanisms]. - * - * We have followed general OpenZeppelin Contracts guidelines: functions revert - * instead returning `false` on failure. This behavior is nonetheless - * conventional and does not conflict with the expectations of ERC20 - * applications. - * - * Additionally, an {Approval} event is emitted on calls to {transferFrom}. - * This allows applications to reconstruct the allowance for all accounts just - * by listening to said events. Other implementations of the EIP may not emit - * these events, as it isn't required by the specification. - * - * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} - * functions have been added to mitigate the well-known issues around setting - * allowances. See {IERC20-approve}. - */ -contract ERC20 is Context, IERC20, IERC20Metadata { - mapping(address => uint256) private _balances; - - mapping(address => mapping(address => uint256)) private _allowances; - - uint256 private _totalSupply; - - string private _name; - string private _symbol; - - /** - * @dev Sets the values for {name} and {symbol}. - * - * The default value of {decimals} is 18. To select a different value for - * {decimals} you should overload it. - * - * All two of these values are immutable: they can only be set once during - * construction. - */ - constructor(string memory name_, string memory symbol_) { - _name = name_; - _symbol = symbol_; - } - - /** - * @dev Returns the name of the token. - */ - function name() public view virtual override returns (string memory) { - return _name; - } - - /** - * @dev Returns the symbol of the token, usually a shorter version of the - * name. - */ - function symbol() public view virtual override returns (string memory) { - return _symbol; - } - - /** - * @dev Returns the number of decimals used to get its user representation. - * For example, if `decimals` equals `2`, a balance of `505` tokens should - * be displayed to a user as `5.05` (`505 / 10 ** 2`). - * - * Tokens usually opt for a value of 18, imitating the relationship between - * Ether and Wei. This is the value {ERC20} uses, unless this function is - * overridden; - * - * NOTE: This information is only used for _display_ purposes: it in - * no way affects any of the arithmetic of the contract, including - * {IERC20-balanceOf} and {IERC20-transfer}. - */ - function decimals() public view virtual override returns (uint8) { - return 18; - } - - /** - * @dev See {IERC20-totalSupply}. - */ - function totalSupply() public view virtual override returns (uint256) { - return _totalSupply; - } - - /** - * @dev See {IERC20-balanceOf}. - */ - function balanceOf(address account) public view virtual override returns (uint256) { - return _balances[account]; - } - - /** - * @dev See {IERC20-transfer}. - * - * Requirements: - * - * - `recipient` cannot be the zero address. - * - the caller must have a balance of at least `amount`. - */ - function transfer(address recipient, uint256 amount) public virtual override returns (bool) { - _transfer(_msgSender(), recipient, amount); - return true; - } - - /** - * @dev See {IERC20-allowance}. - */ - function allowance(address owner, address spender) public view virtual override returns (uint256) { - return _allowances[owner][spender]; - } - - /** - * @dev See {IERC20-approve}. - * - * Requirements: - * - * - `spender` cannot be the zero address. - */ - function approve(address spender, uint256 amount) public virtual override returns (bool) { - _approve(_msgSender(), spender, amount); - return true; - } - - /** - * @dev See {IERC20-transferFrom}. - * - * Emits an {Approval} event indicating the updated allowance. This is not - * required by the EIP. See the note at the beginning of {ERC20}. - * - * Requirements: - * - * - `sender` and `recipient` cannot be the zero address. - * - `sender` must have a balance of at least `amount`. - * - the caller must have allowance for ``sender``'s tokens of at least - * `amount`. - */ - function transferFrom( - address sender, - address recipient, - uint256 amount - ) public virtual override returns (bool) { - _transfer(sender, recipient, amount); - - uint256 currentAllowance = _allowances[sender][_msgSender()]; - require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); - unchecked { - _approve(sender, _msgSender(), currentAllowance - amount); - } - - return true; - } - - /** - * @dev Atomically increases the allowance granted to `spender` by the caller. - * - * This is an alternative to {approve} that can be used as a mitigation for - * problems described in {IERC20-approve}. - * - * Emits an {Approval} event indicating the updated allowance. - * - * Requirements: - * - * - `spender` cannot be the zero address. - */ - function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { - _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); - return true; - } - - /** - * @dev Atomically decreases the allowance granted to `spender` by the caller. - * - * This is an alternative to {approve} that can be used as a mitigation for - * problems described in {IERC20-approve}. - * - * Emits an {Approval} event indicating the updated allowance. - * - * Requirements: - * - * - `spender` cannot be the zero address. - * - `spender` must have allowance for the caller of at least - * `subtractedValue`. - */ - function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { - uint256 currentAllowance = _allowances[_msgSender()][spender]; - require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); - unchecked { - _approve(_msgSender(), spender, currentAllowance - subtractedValue); - } - - return true; - } - - /** - * @dev Moves `amount` of tokens from `sender` to `recipient`. - * - * This internal function is equivalent to {transfer}, and can be used to - * e.g. implement automatic token fees, slashing mechanisms, etc. - * - * Emits a {Transfer} event. - * - * Requirements: - * - * - `sender` cannot be the zero address. - * - `recipient` cannot be the zero address. - * - `sender` must have a balance of at least `amount`. - */ - function _transfer( - address sender, - address recipient, - uint256 amount - ) internal virtual { - require(sender != address(0), "ERC20: transfer from the zero address"); - require(recipient != address(0), "ERC20: transfer to the zero address"); - - _beforeTokenTransfer(sender, recipient, amount); - - uint256 senderBalance = _balances[sender]; - require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); - unchecked { - _balances[sender] = senderBalance - amount; - } - _balances[recipient] += amount; - - emit Transfer(sender, recipient, amount); - - _afterTokenTransfer(sender, recipient, amount); - } - - /** @dev Creates `amount` tokens and assigns them to `account`, increasing - * the total supply. - * - * Emits a {Transfer} event with `from` set to the zero address. - * - * Requirements: - * - * - `account` cannot be the zero address. - */ - function _mint(address account, uint256 amount) internal virtual { - require(account != address(0), "ERC20: mint to the zero address"); - - _beforeTokenTransfer(address(0), account, amount); - - _totalSupply += amount; - _balances[account] += amount; - emit Transfer(address(0), account, amount); - - _afterTokenTransfer(address(0), account, amount); - } - - /** - * @dev Destroys `amount` tokens from `account`, reducing the - * total supply. - * - * Emits a {Transfer} event with `to` set to the zero address. - * - * Requirements: - * - * - `account` cannot be the zero address. - * - `account` must have at least `amount` tokens. - */ - function _burn(address account, uint256 amount) internal virtual { - require(account != address(0), "ERC20: burn from the zero address"); - - _beforeTokenTransfer(account, address(0), amount); - - uint256 accountBalance = _balances[account]; - require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); - unchecked { - _balances[account] = accountBalance - amount; - } - _totalSupply -= amount; - - emit Transfer(account, address(0), amount); - - _afterTokenTransfer(account, address(0), amount); - } - - /** - * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. - * - * This internal function is equivalent to `approve`, and can be used to - * e.g. set automatic allowances for certain subsystems, etc. - * - * Emits an {Approval} event. - * - * Requirements: - * - * - `owner` cannot be the zero address. - * - `spender` cannot be the zero address. - */ - function _approve( - address owner, - address spender, - uint256 amount - ) internal virtual { - require(owner != address(0), "ERC20: approve from the zero address"); - require(spender != address(0), "ERC20: approve to the zero address"); - - _allowances[owner][spender] = amount; - emit Approval(owner, spender, amount); - } - - /** - * @dev Hook that is called before any transfer of tokens. This includes - * minting and burning. - * - * Calling conditions: - * - * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens - * will be transferred to `to`. - * - when `from` is zero, `amount` tokens will be minted for `to`. - * - when `to` is zero, `amount` of ``from``'s tokens will be burned. - * - `from` and `to` are never both zero. - * - * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. - */ - function _beforeTokenTransfer( - address from, - address to, - uint256 amount - ) internal virtual {} - - /** - * @dev Hook that is called after any transfer of tokens. This includes - * minting and burning. - * - * Calling conditions: - * - * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens - * has been transferred to `to`. - * - when `from` is zero, `amount` tokens have been minted for `to`. - * - when `to` is zero, `amount` of ``from``'s tokens have been burned. - * - `from` and `to` are never both zero. - * - * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. - */ - function _afterTokenTransfer( - address from, - address to, - uint256 amount - ) internal virtual {} -} \ No newline at end of file diff --git a/zcnbridge/ethereum/erc20/IERC20.sol b/zcnbridge/ethereum/erc20/IERC20.sol deleted file mode 100644 index 014b5706d..000000000 --- a/zcnbridge/ethereum/erc20/IERC20.sol +++ /dev/null @@ -1,82 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.3.2 (token/ERC20/IERC20.sol) - -pragma solidity ^0.8.0; - -/** - * @dev Interface of the ERC20 standard as defined in the EIP. - */ -interface IERC20 { - /** - * @dev Returns the amount of tokens in existence. - */ - function totalSupply() external view returns (uint256); - - /** - * @dev Returns the amount of tokens owned by `account`. - */ - function balanceOf(address account) external view returns (uint256); - - /** - * @dev Moves `amount` tokens from the caller's account to `recipient`. - * - * Returns a boolean value indicating whether the operation succeeded. - * - * Emits a {Transfer} event. - */ - function transfer(address recipient, uint256 amount) external returns (bool); - - /** - * @dev Returns the remaining number of tokens that `spender` will be - * allowed to spend on behalf of `owner` through {transferFrom}. This is - * zero by default. - * - * This value changes when {approve} or {transferFrom} are called. - */ - function allowance(address owner, address spender) external view returns (uint256); - - /** - * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. - * - * Returns a boolean value indicating whether the operation succeeded. - * - * IMPORTANT: Beware that changing an allowance with this method brings the risk - * that someone may use both the old and the new allowance by unfortunate - * transaction ordering. One possible solution to mitigate this race - * condition is to first reduce the spender's allowance to 0 and set the - * desired value afterwards: - * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 - * - * Emits an {Approval} event. - */ - function approve(address spender, uint256 amount) external returns (bool); - - /** - * @dev Moves `amount` tokens from `sender` to `recipient` using the - * allowance mechanism. `amount` is then deducted from the caller's - * allowance. - * - * Returns a boolean value indicating whether the operation succeeded. - * - * Emits a {Transfer} event. - */ - function transferFrom( - address sender, - address recipient, - uint256 amount - ) external returns (bool); - - /** - * @dev Emitted when `value` tokens are moved from one account (`from`) to - * another (`to`). - * - * Note that `value` may be zero. - */ - event Transfer(address indexed from, address indexed to, uint256 value); - - /** - * @dev Emitted when the allowance of a `spender` for an `owner` is set by - * a call to {approve}. `value` is the new allowance. - */ - event Approval(address indexed owner, address indexed spender, uint256 value); -} \ No newline at end of file diff --git a/zcnbridge/ethereum/erc20/IERC20Metadata.sol b/zcnbridge/ethereum/erc20/IERC20Metadata.sol deleted file mode 100644 index 3f8166f0d..000000000 --- a/zcnbridge/ethereum/erc20/IERC20Metadata.sol +++ /dev/null @@ -1,28 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.3.2 (token/ERC20/extensions/IERC20Metadata.sol) - -pragma solidity ^0.8.0; - -import "./IERC20.sol"; - -/** - * @dev Interface for the optional metadata functions from the ERC20 standard. - * - * _Available since v4.1._ - */ -interface IERC20Metadata is IERC20 { - /** - * @dev Returns the name of the token. - */ - function name() external view returns (string memory); - - /** - * @dev Returns the symbol of the token. - */ - function symbol() external view returns (string memory); - - /** - * @dev Returns the decimals places of the token. - */ - function decimals() external view returns (uint8); -} \ No newline at end of file diff --git a/zcnbridge/ethereum/erc20/erc20.go b/zcnbridge/ethereum/erc20/erc20.go deleted file mode 100644 index 064174d8a..000000000 --- a/zcnbridge/ethereum/erc20/erc20.go +++ /dev/null @@ -1,2319 +0,0 @@ -// Code generated - DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package erc20 - -import ( - "errors" - "math/big" - "strings" - - ethereum "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/event" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = errors.New - _ = big.NewInt - _ = strings.NewReader - _ = ethereum.NotFound - _ = bind.Bind - _ = common.Big1 - _ = types.BloomLookup - _ = event.NewSubscription -) - -// ContextMetaData contains all meta data concerning the Context contract. -var ContextMetaData = &bind.MetaData{ - ABI: "[]", -} - -// ContextABI is the input ABI used to generate the binding from. -// Deprecated: Use ContextMetaData.ABI instead. -var ContextABI = ContextMetaData.ABI - -// Context is an auto generated Go binding around an Ethereum contract. -type Context struct { - ContextCaller // Read-only binding to the contract - ContextTransactor // Write-only binding to the contract - ContextFilterer // Log filterer for contract events -} - -// ContextCaller is an auto generated read-only Go binding around an Ethereum contract. -type ContextCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ContextTransactor is an auto generated write-only Go binding around an Ethereum contract. -type ContextTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ContextFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type ContextFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ContextSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type ContextSession struct { - Contract *Context // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// ContextCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type ContextCallerSession struct { - Contract *ContextCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// ContextTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type ContextTransactorSession struct { - Contract *ContextTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// ContextRaw is an auto generated low-level Go binding around an Ethereum contract. -type ContextRaw struct { - Contract *Context // Generic contract binding to access the raw methods on -} - -// ContextCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type ContextCallerRaw struct { - Contract *ContextCaller // Generic read-only contract binding to access the raw methods on -} - -// ContextTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type ContextTransactorRaw struct { - Contract *ContextTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewContext creates a new instance of Context, bound to a specific deployed contract. -func NewContext(address common.Address, backend bind.ContractBackend) (*Context, error) { - contract, err := bindContext(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &Context{ContextCaller: ContextCaller{contract: contract}, ContextTransactor: ContextTransactor{contract: contract}, ContextFilterer: ContextFilterer{contract: contract}}, nil -} - -// NewContextCaller creates a new read-only instance of Context, bound to a specific deployed contract. -func NewContextCaller(address common.Address, caller bind.ContractCaller) (*ContextCaller, error) { - contract, err := bindContext(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &ContextCaller{contract: contract}, nil -} - -// NewContextTransactor creates a new write-only instance of Context, bound to a specific deployed contract. -func NewContextTransactor(address common.Address, transactor bind.ContractTransactor) (*ContextTransactor, error) { - contract, err := bindContext(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &ContextTransactor{contract: contract}, nil -} - -// NewContextFilterer creates a new log filterer instance of Context, bound to a specific deployed contract. -func NewContextFilterer(address common.Address, filterer bind.ContractFilterer) (*ContextFilterer, error) { - contract, err := bindContext(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &ContextFilterer{contract: contract}, nil -} - -// bindContext binds a generic wrapper to an already deployed contract. -func bindContext(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(ContextABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Context *ContextRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Context.Contract.ContextCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Context *ContextRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Context.Contract.ContextTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Context *ContextRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Context.Contract.ContextTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Context *ContextCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Context.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Context *ContextTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Context.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Context *ContextTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Context.Contract.contract.Transact(opts, method, params...) -} - -// ERC20MetaData contains all meta data concerning the ERC20 contract. -var ERC20MetaData = &bind.MetaData{ - ABI: "[{\"inputs\":[{\"internalType\":\"string\",\"name\":\"name_\",\"type\":\"string\"},{\"internalType\":\"string\",\"name\":\"symbol_\",\"type\":\"string\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"internalType\":\"uint8\",\"name\":\"\",\"type\":\"uint8\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"subtractedValue\",\"type\":\"uint256\"}],\"name\":\"decreaseAllowance\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"addedValue\",\"type\":\"uint256\"}],\"name\":\"increaseAllowance\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]", - Sigs: map[string]string{ - "dd62ed3e": "allowance(address,address)", - "095ea7b3": "approve(address,uint256)", - "70a08231": "balanceOf(address)", - "313ce567": "decimals()", - "a457c2d7": "decreaseAllowance(address,uint256)", - "39509351": "increaseAllowance(address,uint256)", - "06fdde03": "name()", - "95d89b41": "symbol()", - "18160ddd": "totalSupply()", - "a9059cbb": "transfer(address,uint256)", - "23b872dd": "transferFrom(address,address,uint256)", - }, - Bin: "0x60806040523480156200001157600080fd5b5060405162000b5638038062000b568339810160408190526200003491620001db565b81516200004990600390602085019062000068565b5080516200005f90600490602084019062000068565b50505062000282565b828054620000769062000245565b90600052602060002090601f0160209004810192826200009a5760008555620000e5565b82601f10620000b557805160ff1916838001178555620000e5565b82800160010185558215620000e5579182015b82811115620000e5578251825591602001919060010190620000c8565b50620000f3929150620000f7565b5090565b5b80821115620000f35760008155600101620000f8565b634e487b7160e01b600052604160045260246000fd5b600082601f8301126200013657600080fd5b81516001600160401b03808211156200015357620001536200010e565b604051601f8301601f19908116603f011681019082821181831017156200017e576200017e6200010e565b816040528381526020925086838588010111156200019b57600080fd5b600091505b83821015620001bf5785820183015181830184015290820190620001a0565b83821115620001d15760008385830101525b9695505050505050565b60008060408385031215620001ef57600080fd5b82516001600160401b03808211156200020757600080fd5b620002158683870162000124565b935060208501519150808211156200022c57600080fd5b506200023b8582860162000124565b9150509250929050565b600181811c908216806200025a57607f821691505b602082108114156200027c57634e487b7160e01b600052602260045260246000fd5b50919050565b6108c480620002926000396000f3fe608060405234801561001057600080fd5b50600436106100a95760003560e01c80633950935111610071578063395093511461012357806370a082311461013657806395d89b411461015f578063a457c2d714610167578063a9059cbb1461017a578063dd62ed3e1461018d57600080fd5b806306fdde03146100ae578063095ea7b3146100cc57806318160ddd146100ef57806323b872dd14610101578063313ce56714610114575b600080fd5b6100b66101c6565b6040516100c39190610701565b60405180910390f35b6100df6100da366004610772565b610258565b60405190151581526020016100c3565b6002545b6040519081526020016100c3565b6100df61010f36600461079c565b61026e565b604051601281526020016100c3565b6100df610131366004610772565b61031d565b6100f36101443660046107d8565b6001600160a01b031660009081526020819052604090205490565b6100b6610359565b6100df610175366004610772565b610368565b6100df610188366004610772565b610401565b6100f361019b3660046107fa565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b6060600380546101d59061082d565b80601f01602080910402602001604051908101604052809291908181526020018280546102019061082d565b801561024e5780601f106102235761010080835404028352916020019161024e565b820191906000526020600020905b81548152906001019060200180831161023157829003601f168201915b5050505050905090565b600061026533848461040e565b50600192915050565b600061027b848484610532565b6001600160a01b0384166000908152600160209081526040808320338452909152902054828110156103055760405162461bcd60e51b815260206004820152602860248201527f45524332303a207472616e7366657220616d6f756e74206578636565647320616044820152676c6c6f77616e636560c01b60648201526084015b60405180910390fd5b610312853385840361040e565b506001949350505050565b3360008181526001602090815260408083206001600160a01b03871684529091528120549091610265918590610354908690610868565b61040e565b6060600480546101d59061082d565b3360009081526001602090815260408083206001600160a01b0386168452909152812054828110156103ea5760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b60648201526084016102fc565b6103f7338585840361040e565b5060019392505050565b6000610265338484610532565b6001600160a01b0383166104705760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b60648201526084016102fc565b6001600160a01b0382166104d15760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b60648201526084016102fc565b6001600160a01b0383811660008181526001602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b6001600160a01b0383166105965760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b60648201526084016102fc565b6001600160a01b0382166105f85760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b60648201526084016102fc565b6001600160a01b038316600090815260208190526040902054818110156106705760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b60648201526084016102fc565b6001600160a01b038085166000908152602081905260408082208585039055918516815290812080548492906106a7908490610868565b92505081905550826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040516106f391815260200190565b60405180910390a350505050565b600060208083528351808285015260005b8181101561072e57858101830151858201604001528201610712565b81811115610740576000604083870101525b50601f01601f1916929092016040019392505050565b80356001600160a01b038116811461076d57600080fd5b919050565b6000806040838503121561078557600080fd5b61078e83610756565b946020939093013593505050565b6000806000606084860312156107b157600080fd5b6107ba84610756565b92506107c860208501610756565b9150604084013590509250925092565b6000602082840312156107ea57600080fd5b6107f382610756565b9392505050565b6000806040838503121561080d57600080fd5b61081683610756565b915061082460208401610756565b90509250929050565b600181811c9082168061084157607f821691505b6020821081141561086257634e487b7160e01b600052602260045260246000fd5b50919050565b6000821982111561088957634e487b7160e01b600052601160045260246000fd5b50019056fea26469706673582212203a382710d330bfc5c08286d13b123167071c03a623c45f800ccb995904d07eef64736f6c63430008090033", -} - -// ERC20ABI is the input ABI used to generate the binding from. -// Deprecated: Use ERC20MetaData.ABI instead. -var ERC20ABI = ERC20MetaData.ABI - -// Deprecated: Use ERC20MetaData.Sigs instead. -// ERC20FuncSigs maps the 4-byte function signature to its string representation. -var ERC20FuncSigs = ERC20MetaData.Sigs - -// ERC20Bin is the compiled bytecode used for deploying new contracts. -// Deprecated: Use ERC20MetaData.Bin instead. -var ERC20Bin = ERC20MetaData.Bin - -// DeployERC20 deploys a new Ethereum contract, binding an instance of ERC20 to it. -func DeployERC20(auth *bind.TransactOpts, backend bind.ContractBackend, name_ string, symbol_ string) (common.Address, *types.Transaction, *ERC20, error) { - parsed, err := ERC20MetaData.GetAbi() - if err != nil { - return common.Address{}, nil, nil, err - } - if parsed == nil { - return common.Address{}, nil, nil, errors.New("GetABI returned nil") - } - - address, tx, contract, err := bind.DeployContract(auth, *parsed, common.FromHex(ERC20Bin), backend, name_, symbol_) - if err != nil { - return common.Address{}, nil, nil, err - } - return address, tx, &ERC20{ERC20Caller: ERC20Caller{contract: contract}, ERC20Transactor: ERC20Transactor{contract: contract}, ERC20Filterer: ERC20Filterer{contract: contract}}, nil -} - -// ERC20 is an auto generated Go binding around an Ethereum contract. -type ERC20 struct { - ERC20Caller // Read-only binding to the contract - ERC20Transactor // Write-only binding to the contract - ERC20Filterer // Log filterer for contract events -} - -// ERC20Caller is an auto generated read-only Go binding around an Ethereum contract. -type ERC20Caller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ERC20Transactor is an auto generated write-only Go binding around an Ethereum contract. -type ERC20Transactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ERC20Filterer is an auto generated log filtering Go binding around an Ethereum contract events. -type ERC20Filterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ERC20Session is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type ERC20Session struct { - Contract *ERC20 // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// ERC20CallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type ERC20CallerSession struct { - Contract *ERC20Caller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// ERC20TransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type ERC20TransactorSession struct { - Contract *ERC20Transactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// ERC20Raw is an auto generated low-level Go binding around an Ethereum contract. -type ERC20Raw struct { - Contract *ERC20 // Generic contract binding to access the raw methods on -} - -// ERC20CallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type ERC20CallerRaw struct { - Contract *ERC20Caller // Generic read-only contract binding to access the raw methods on -} - -// ERC20TransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type ERC20TransactorRaw struct { - Contract *ERC20Transactor // Generic write-only contract binding to access the raw methods on -} - -// NewERC20 creates a new instance of ERC20, bound to a specific deployed contract. -func NewERC20(address common.Address, backend bind.ContractBackend) (*ERC20, error) { - contract, err := bindERC20(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &ERC20{ERC20Caller: ERC20Caller{contract: contract}, ERC20Transactor: ERC20Transactor{contract: contract}, ERC20Filterer: ERC20Filterer{contract: contract}}, nil -} - -// NewERC20Caller creates a new read-only instance of ERC20, bound to a specific deployed contract. -func NewERC20Caller(address common.Address, caller bind.ContractCaller) (*ERC20Caller, error) { - contract, err := bindERC20(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &ERC20Caller{contract: contract}, nil -} - -// NewERC20Transactor creates a new write-only instance of ERC20, bound to a specific deployed contract. -func NewERC20Transactor(address common.Address, transactor bind.ContractTransactor) (*ERC20Transactor, error) { - contract, err := bindERC20(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &ERC20Transactor{contract: contract}, nil -} - -// NewERC20Filterer creates a new log filterer instance of ERC20, bound to a specific deployed contract. -func NewERC20Filterer(address common.Address, filterer bind.ContractFilterer) (*ERC20Filterer, error) { - contract, err := bindERC20(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &ERC20Filterer{contract: contract}, nil -} - -// bindERC20 binds a generic wrapper to an already deployed contract. -func bindERC20(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(ERC20ABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_ERC20 *ERC20Raw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _ERC20.Contract.ERC20Caller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_ERC20 *ERC20Raw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _ERC20.Contract.ERC20Transactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_ERC20 *ERC20Raw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _ERC20.Contract.ERC20Transactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_ERC20 *ERC20CallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _ERC20.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_ERC20 *ERC20TransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _ERC20.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_ERC20 *ERC20TransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _ERC20.Contract.contract.Transact(opts, method, params...) -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_ERC20 *ERC20Caller) Allowance(opts *bind.CallOpts, owner common.Address, spender common.Address) (*big.Int, error) { - var out []interface{} - err := _ERC20.contract.Call(opts, &out, "allowance", owner, spender) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_ERC20 *ERC20Session) Allowance(owner common.Address, spender common.Address) (*big.Int, error) { - return _ERC20.Contract.Allowance(&_ERC20.CallOpts, owner, spender) -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_ERC20 *ERC20CallerSession) Allowance(owner common.Address, spender common.Address) (*big.Int, error) { - return _ERC20.Contract.Allowance(&_ERC20.CallOpts, owner, spender) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_ERC20 *ERC20Caller) BalanceOf(opts *bind.CallOpts, account common.Address) (*big.Int, error) { - var out []interface{} - err := _ERC20.contract.Call(opts, &out, "balanceOf", account) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_ERC20 *ERC20Session) BalanceOf(account common.Address) (*big.Int, error) { - return _ERC20.Contract.BalanceOf(&_ERC20.CallOpts, account) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_ERC20 *ERC20CallerSession) BalanceOf(account common.Address) (*big.Int, error) { - return _ERC20.Contract.BalanceOf(&_ERC20.CallOpts, account) -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() view returns(uint8) -func (_ERC20 *ERC20Caller) Decimals(opts *bind.CallOpts) (uint8, error) { - var out []interface{} - err := _ERC20.contract.Call(opts, &out, "decimals") - - if err != nil { - return *new(uint8), err - } - - out0 := *abi.ConvertType(out[0], new(uint8)).(*uint8) - - return out0, err - -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() view returns(uint8) -func (_ERC20 *ERC20Session) Decimals() (uint8, error) { - return _ERC20.Contract.Decimals(&_ERC20.CallOpts) -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() view returns(uint8) -func (_ERC20 *ERC20CallerSession) Decimals() (uint8, error) { - return _ERC20.Contract.Decimals(&_ERC20.CallOpts) -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_ERC20 *ERC20Caller) Name(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _ERC20.contract.Call(opts, &out, "name") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_ERC20 *ERC20Session) Name() (string, error) { - return _ERC20.Contract.Name(&_ERC20.CallOpts) -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_ERC20 *ERC20CallerSession) Name() (string, error) { - return _ERC20.Contract.Name(&_ERC20.CallOpts) -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_ERC20 *ERC20Caller) Symbol(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _ERC20.contract.Call(opts, &out, "symbol") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_ERC20 *ERC20Session) Symbol() (string, error) { - return _ERC20.Contract.Symbol(&_ERC20.CallOpts) -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_ERC20 *ERC20CallerSession) Symbol() (string, error) { - return _ERC20.Contract.Symbol(&_ERC20.CallOpts) -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_ERC20 *ERC20Caller) TotalSupply(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _ERC20.contract.Call(opts, &out, "totalSupply") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_ERC20 *ERC20Session) TotalSupply() (*big.Int, error) { - return _ERC20.Contract.TotalSupply(&_ERC20.CallOpts) -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_ERC20 *ERC20CallerSession) TotalSupply() (*big.Int, error) { - return _ERC20.Contract.TotalSupply(&_ERC20.CallOpts) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_ERC20 *ERC20Transactor) Approve(opts *bind.TransactOpts, spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.contract.Transact(opts, "approve", spender, amount) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_ERC20 *ERC20Session) Approve(spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.Approve(&_ERC20.TransactOpts, spender, amount) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_ERC20 *ERC20TransactorSession) Approve(spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.Approve(&_ERC20.TransactOpts, spender, amount) -} - -// DecreaseAllowance is a paid mutator transaction binding the contract method 0xa457c2d7. -// -// Solidity: function decreaseAllowance(address spender, uint256 subtractedValue) returns(bool) -func (_ERC20 *ERC20Transactor) DecreaseAllowance(opts *bind.TransactOpts, spender common.Address, subtractedValue *big.Int) (*types.Transaction, error) { - return _ERC20.contract.Transact(opts, "decreaseAllowance", spender, subtractedValue) -} - -// DecreaseAllowance is a paid mutator transaction binding the contract method 0xa457c2d7. -// -// Solidity: function decreaseAllowance(address spender, uint256 subtractedValue) returns(bool) -func (_ERC20 *ERC20Session) DecreaseAllowance(spender common.Address, subtractedValue *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.DecreaseAllowance(&_ERC20.TransactOpts, spender, subtractedValue) -} - -// DecreaseAllowance is a paid mutator transaction binding the contract method 0xa457c2d7. -// -// Solidity: function decreaseAllowance(address spender, uint256 subtractedValue) returns(bool) -func (_ERC20 *ERC20TransactorSession) DecreaseAllowance(spender common.Address, subtractedValue *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.DecreaseAllowance(&_ERC20.TransactOpts, spender, subtractedValue) -} - -// IncreaseAllowance is a paid mutator transaction binding the contract method 0x39509351. -// -// Solidity: function increaseAllowance(address spender, uint256 addedValue) returns(bool) -func (_ERC20 *ERC20Transactor) IncreaseAllowance(opts *bind.TransactOpts, spender common.Address, addedValue *big.Int) (*types.Transaction, error) { - return _ERC20.contract.Transact(opts, "increaseAllowance", spender, addedValue) -} - -// IncreaseAllowance is a paid mutator transaction binding the contract method 0x39509351. -// -// Solidity: function increaseAllowance(address spender, uint256 addedValue) returns(bool) -func (_ERC20 *ERC20Session) IncreaseAllowance(spender common.Address, addedValue *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.IncreaseAllowance(&_ERC20.TransactOpts, spender, addedValue) -} - -// IncreaseAllowance is a paid mutator transaction binding the contract method 0x39509351. -// -// Solidity: function increaseAllowance(address spender, uint256 addedValue) returns(bool) -func (_ERC20 *ERC20TransactorSession) IncreaseAllowance(spender common.Address, addedValue *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.IncreaseAllowance(&_ERC20.TransactOpts, spender, addedValue) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_ERC20 *ERC20Transactor) Transfer(opts *bind.TransactOpts, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.contract.Transact(opts, "transfer", recipient, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_ERC20 *ERC20Session) Transfer(recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.Transfer(&_ERC20.TransactOpts, recipient, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_ERC20 *ERC20TransactorSession) Transfer(recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.Transfer(&_ERC20.TransactOpts, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_ERC20 *ERC20Transactor) TransferFrom(opts *bind.TransactOpts, sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.contract.Transact(opts, "transferFrom", sender, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_ERC20 *ERC20Session) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.TransferFrom(&_ERC20.TransactOpts, sender, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_ERC20 *ERC20TransactorSession) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.TransferFrom(&_ERC20.TransactOpts, sender, recipient, amount) -} - -// ERC20ApprovalIterator is returned from FilterApproval and is used to iterate over the raw logs and unpacked data for Approval events raised by the ERC20 contract. -type ERC20ApprovalIterator struct { - Event *ERC20Approval // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *ERC20ApprovalIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(ERC20Approval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(ERC20Approval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *ERC20ApprovalIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *ERC20ApprovalIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// ERC20Approval represents a Approval event raised by the ERC20 contract. -type ERC20Approval struct { - Owner common.Address - Spender common.Address - Value *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterApproval is a free log retrieval operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_ERC20 *ERC20Filterer) FilterApproval(opts *bind.FilterOpts, owner []common.Address, spender []common.Address) (*ERC20ApprovalIterator, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var spenderRule []interface{} - for _, spenderItem := range spender { - spenderRule = append(spenderRule, spenderItem) - } - - logs, sub, err := _ERC20.contract.FilterLogs(opts, "Approval", ownerRule, spenderRule) - if err != nil { - return nil, err - } - return &ERC20ApprovalIterator{contract: _ERC20.contract, event: "Approval", logs: logs, sub: sub}, nil -} - -// WatchApproval is a free log subscription operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_ERC20 *ERC20Filterer) WatchApproval(opts *bind.WatchOpts, sink chan<- *ERC20Approval, owner []common.Address, spender []common.Address) (event.Subscription, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var spenderRule []interface{} - for _, spenderItem := range spender { - spenderRule = append(spenderRule, spenderItem) - } - - logs, sub, err := _ERC20.contract.WatchLogs(opts, "Approval", ownerRule, spenderRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(ERC20Approval) - if err := _ERC20.contract.UnpackLog(event, "Approval", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseApproval is a log parse operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_ERC20 *ERC20Filterer) ParseApproval(log types.Log) (*ERC20Approval, error) { - event := new(ERC20Approval) - if err := _ERC20.contract.UnpackLog(event, "Approval", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// ERC20TransferIterator is returned from FilterTransfer and is used to iterate over the raw logs and unpacked data for Transfer events raised by the ERC20 contract. -type ERC20TransferIterator struct { - Event *ERC20Transfer // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *ERC20TransferIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(ERC20Transfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(ERC20Transfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *ERC20TransferIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *ERC20TransferIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// ERC20Transfer represents a Transfer event raised by the ERC20 contract. -type ERC20Transfer struct { - From common.Address - To common.Address - Value *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterTransfer is a free log retrieval operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_ERC20 *ERC20Filterer) FilterTransfer(opts *bind.FilterOpts, from []common.Address, to []common.Address) (*ERC20TransferIterator, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - logs, sub, err := _ERC20.contract.FilterLogs(opts, "Transfer", fromRule, toRule) - if err != nil { - return nil, err - } - return &ERC20TransferIterator{contract: _ERC20.contract, event: "Transfer", logs: logs, sub: sub}, nil -} - -// WatchTransfer is a free log subscription operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_ERC20 *ERC20Filterer) WatchTransfer(opts *bind.WatchOpts, sink chan<- *ERC20Transfer, from []common.Address, to []common.Address) (event.Subscription, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - logs, sub, err := _ERC20.contract.WatchLogs(opts, "Transfer", fromRule, toRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(ERC20Transfer) - if err := _ERC20.contract.UnpackLog(event, "Transfer", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseTransfer is a log parse operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_ERC20 *ERC20Filterer) ParseTransfer(log types.Log) (*ERC20Transfer, error) { - event := new(ERC20Transfer) - if err := _ERC20.contract.UnpackLog(event, "Transfer", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// IERC20MetaData contains all meta data concerning the IERC20 contract. -var IERC20MetaData = &bind.MetaData{ - ABI: "[{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]", - Sigs: map[string]string{ - "dd62ed3e": "allowance(address,address)", - "095ea7b3": "approve(address,uint256)", - "70a08231": "balanceOf(address)", - "18160ddd": "totalSupply()", - "a9059cbb": "transfer(address,uint256)", - "23b872dd": "transferFrom(address,address,uint256)", - }, -} - -// IERC20ABI is the input ABI used to generate the binding from. -// Deprecated: Use IERC20MetaData.ABI instead. -var IERC20ABI = IERC20MetaData.ABI - -// Deprecated: Use IERC20MetaData.Sigs instead. -// IERC20FuncSigs maps the 4-byte function signature to its string representation. -var IERC20FuncSigs = IERC20MetaData.Sigs - -// IERC20 is an auto generated Go binding around an Ethereum contract. -type IERC20 struct { - IERC20Caller // Read-only binding to the contract - IERC20Transactor // Write-only binding to the contract - IERC20Filterer // Log filterer for contract events -} - -// IERC20Caller is an auto generated read-only Go binding around an Ethereum contract. -type IERC20Caller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IERC20Transactor is an auto generated write-only Go binding around an Ethereum contract. -type IERC20Transactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IERC20Filterer is an auto generated log filtering Go binding around an Ethereum contract events. -type IERC20Filterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IERC20Session is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type IERC20Session struct { - Contract *IERC20 // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// IERC20CallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type IERC20CallerSession struct { - Contract *IERC20Caller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// IERC20TransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type IERC20TransactorSession struct { - Contract *IERC20Transactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// IERC20Raw is an auto generated low-level Go binding around an Ethereum contract. -type IERC20Raw struct { - Contract *IERC20 // Generic contract binding to access the raw methods on -} - -// IERC20CallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type IERC20CallerRaw struct { - Contract *IERC20Caller // Generic read-only contract binding to access the raw methods on -} - -// IERC20TransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type IERC20TransactorRaw struct { - Contract *IERC20Transactor // Generic write-only contract binding to access the raw methods on -} - -// NewIERC20 creates a new instance of IERC20, bound to a specific deployed contract. -func NewIERC20(address common.Address, backend bind.ContractBackend) (*IERC20, error) { - contract, err := bindIERC20(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &IERC20{IERC20Caller: IERC20Caller{contract: contract}, IERC20Transactor: IERC20Transactor{contract: contract}, IERC20Filterer: IERC20Filterer{contract: contract}}, nil -} - -// NewIERC20Caller creates a new read-only instance of IERC20, bound to a specific deployed contract. -func NewIERC20Caller(address common.Address, caller bind.ContractCaller) (*IERC20Caller, error) { - contract, err := bindIERC20(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &IERC20Caller{contract: contract}, nil -} - -// NewIERC20Transactor creates a new write-only instance of IERC20, bound to a specific deployed contract. -func NewIERC20Transactor(address common.Address, transactor bind.ContractTransactor) (*IERC20Transactor, error) { - contract, err := bindIERC20(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &IERC20Transactor{contract: contract}, nil -} - -// NewIERC20Filterer creates a new log filterer instance of IERC20, bound to a specific deployed contract. -func NewIERC20Filterer(address common.Address, filterer bind.ContractFilterer) (*IERC20Filterer, error) { - contract, err := bindIERC20(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &IERC20Filterer{contract: contract}, nil -} - -// bindIERC20 binds a generic wrapper to an already deployed contract. -func bindIERC20(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(IERC20ABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_IERC20 *IERC20Raw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _IERC20.Contract.IERC20Caller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_IERC20 *IERC20Raw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _IERC20.Contract.IERC20Transactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_IERC20 *IERC20Raw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _IERC20.Contract.IERC20Transactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_IERC20 *IERC20CallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _IERC20.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_IERC20 *IERC20TransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _IERC20.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_IERC20 *IERC20TransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _IERC20.Contract.contract.Transact(opts, method, params...) -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_IERC20 *IERC20Caller) Allowance(opts *bind.CallOpts, owner common.Address, spender common.Address) (*big.Int, error) { - var out []interface{} - err := _IERC20.contract.Call(opts, &out, "allowance", owner, spender) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_IERC20 *IERC20Session) Allowance(owner common.Address, spender common.Address) (*big.Int, error) { - return _IERC20.Contract.Allowance(&_IERC20.CallOpts, owner, spender) -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_IERC20 *IERC20CallerSession) Allowance(owner common.Address, spender common.Address) (*big.Int, error) { - return _IERC20.Contract.Allowance(&_IERC20.CallOpts, owner, spender) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_IERC20 *IERC20Caller) BalanceOf(opts *bind.CallOpts, account common.Address) (*big.Int, error) { - var out []interface{} - err := _IERC20.contract.Call(opts, &out, "balanceOf", account) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_IERC20 *IERC20Session) BalanceOf(account common.Address) (*big.Int, error) { - return _IERC20.Contract.BalanceOf(&_IERC20.CallOpts, account) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_IERC20 *IERC20CallerSession) BalanceOf(account common.Address) (*big.Int, error) { - return _IERC20.Contract.BalanceOf(&_IERC20.CallOpts, account) -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_IERC20 *IERC20Caller) TotalSupply(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _IERC20.contract.Call(opts, &out, "totalSupply") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_IERC20 *IERC20Session) TotalSupply() (*big.Int, error) { - return _IERC20.Contract.TotalSupply(&_IERC20.CallOpts) -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_IERC20 *IERC20CallerSession) TotalSupply() (*big.Int, error) { - return _IERC20.Contract.TotalSupply(&_IERC20.CallOpts) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_IERC20 *IERC20Transactor) Approve(opts *bind.TransactOpts, spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.contract.Transact(opts, "approve", spender, amount) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_IERC20 *IERC20Session) Approve(spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.Contract.Approve(&_IERC20.TransactOpts, spender, amount) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_IERC20 *IERC20TransactorSession) Approve(spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.Contract.Approve(&_IERC20.TransactOpts, spender, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_IERC20 *IERC20Transactor) Transfer(opts *bind.TransactOpts, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.contract.Transact(opts, "transfer", recipient, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_IERC20 *IERC20Session) Transfer(recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.Contract.Transfer(&_IERC20.TransactOpts, recipient, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_IERC20 *IERC20TransactorSession) Transfer(recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.Contract.Transfer(&_IERC20.TransactOpts, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_IERC20 *IERC20Transactor) TransferFrom(opts *bind.TransactOpts, sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.contract.Transact(opts, "transferFrom", sender, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_IERC20 *IERC20Session) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.Contract.TransferFrom(&_IERC20.TransactOpts, sender, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_IERC20 *IERC20TransactorSession) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.Contract.TransferFrom(&_IERC20.TransactOpts, sender, recipient, amount) -} - -// IERC20ApprovalIterator is returned from FilterApproval and is used to iterate over the raw logs and unpacked data for Approval events raised by the IERC20 contract. -type IERC20ApprovalIterator struct { - Event *IERC20Approval // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *IERC20ApprovalIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(IERC20Approval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(IERC20Approval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *IERC20ApprovalIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *IERC20ApprovalIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// IERC20Approval represents a Approval event raised by the IERC20 contract. -type IERC20Approval struct { - Owner common.Address - Spender common.Address - Value *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterApproval is a free log retrieval operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_IERC20 *IERC20Filterer) FilterApproval(opts *bind.FilterOpts, owner []common.Address, spender []common.Address) (*IERC20ApprovalIterator, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var spenderRule []interface{} - for _, spenderItem := range spender { - spenderRule = append(spenderRule, spenderItem) - } - - logs, sub, err := _IERC20.contract.FilterLogs(opts, "Approval", ownerRule, spenderRule) - if err != nil { - return nil, err - } - return &IERC20ApprovalIterator{contract: _IERC20.contract, event: "Approval", logs: logs, sub: sub}, nil -} - -// WatchApproval is a free log subscription operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_IERC20 *IERC20Filterer) WatchApproval(opts *bind.WatchOpts, sink chan<- *IERC20Approval, owner []common.Address, spender []common.Address) (event.Subscription, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var spenderRule []interface{} - for _, spenderItem := range spender { - spenderRule = append(spenderRule, spenderItem) - } - - logs, sub, err := _IERC20.contract.WatchLogs(opts, "Approval", ownerRule, spenderRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(IERC20Approval) - if err := _IERC20.contract.UnpackLog(event, "Approval", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseApproval is a log parse operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_IERC20 *IERC20Filterer) ParseApproval(log types.Log) (*IERC20Approval, error) { - event := new(IERC20Approval) - if err := _IERC20.contract.UnpackLog(event, "Approval", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// IERC20TransferIterator is returned from FilterTransfer and is used to iterate over the raw logs and unpacked data for Transfer events raised by the IERC20 contract. -type IERC20TransferIterator struct { - Event *IERC20Transfer // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *IERC20TransferIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(IERC20Transfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(IERC20Transfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *IERC20TransferIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *IERC20TransferIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// IERC20Transfer represents a Transfer event raised by the IERC20 contract. -type IERC20Transfer struct { - From common.Address - To common.Address - Value *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterTransfer is a free log retrieval operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_IERC20 *IERC20Filterer) FilterTransfer(opts *bind.FilterOpts, from []common.Address, to []common.Address) (*IERC20TransferIterator, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - logs, sub, err := _IERC20.contract.FilterLogs(opts, "Transfer", fromRule, toRule) - if err != nil { - return nil, err - } - return &IERC20TransferIterator{contract: _IERC20.contract, event: "Transfer", logs: logs, sub: sub}, nil -} - -// WatchTransfer is a free log subscription operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_IERC20 *IERC20Filterer) WatchTransfer(opts *bind.WatchOpts, sink chan<- *IERC20Transfer, from []common.Address, to []common.Address) (event.Subscription, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - logs, sub, err := _IERC20.contract.WatchLogs(opts, "Transfer", fromRule, toRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(IERC20Transfer) - if err := _IERC20.contract.UnpackLog(event, "Transfer", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseTransfer is a log parse operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_IERC20 *IERC20Filterer) ParseTransfer(log types.Log) (*IERC20Transfer, error) { - event := new(IERC20Transfer) - if err := _IERC20.contract.UnpackLog(event, "Transfer", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// IERC20MetadataMetaData contains all meta data concerning the IERC20Metadata contract. -var IERC20MetadataMetaData = &bind.MetaData{ - ABI: "[{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"internalType\":\"uint8\",\"name\":\"\",\"type\":\"uint8\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]", - Sigs: map[string]string{ - "dd62ed3e": "allowance(address,address)", - "095ea7b3": "approve(address,uint256)", - "70a08231": "balanceOf(address)", - "313ce567": "decimals()", - "06fdde03": "name()", - "95d89b41": "symbol()", - "18160ddd": "totalSupply()", - "a9059cbb": "transfer(address,uint256)", - "23b872dd": "transferFrom(address,address,uint256)", - }, -} - -// IERC20MetadataABI is the input ABI used to generate the binding from. -// Deprecated: Use IERC20MetadataMetaData.ABI instead. -var IERC20MetadataABI = IERC20MetadataMetaData.ABI - -// Deprecated: Use IERC20MetadataMetaData.Sigs instead. -// IERC20MetadataFuncSigs maps the 4-byte function signature to its string representation. -var IERC20MetadataFuncSigs = IERC20MetadataMetaData.Sigs - -// IERC20Metadata is an auto generated Go binding around an Ethereum contract. -type IERC20Metadata struct { - IERC20MetadataCaller // Read-only binding to the contract - IERC20MetadataTransactor // Write-only binding to the contract - IERC20MetadataFilterer // Log filterer for contract events -} - -// IERC20MetadataCaller is an auto generated read-only Go binding around an Ethereum contract. -type IERC20MetadataCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IERC20MetadataTransactor is an auto generated write-only Go binding around an Ethereum contract. -type IERC20MetadataTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IERC20MetadataFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type IERC20MetadataFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IERC20MetadataSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type IERC20MetadataSession struct { - Contract *IERC20Metadata // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// IERC20MetadataCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type IERC20MetadataCallerSession struct { - Contract *IERC20MetadataCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// IERC20MetadataTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type IERC20MetadataTransactorSession struct { - Contract *IERC20MetadataTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// IERC20MetadataRaw is an auto generated low-level Go binding around an Ethereum contract. -type IERC20MetadataRaw struct { - Contract *IERC20Metadata // Generic contract binding to access the raw methods on -} - -// IERC20MetadataCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type IERC20MetadataCallerRaw struct { - Contract *IERC20MetadataCaller // Generic read-only contract binding to access the raw methods on -} - -// IERC20MetadataTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type IERC20MetadataTransactorRaw struct { - Contract *IERC20MetadataTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewIERC20Metadata creates a new instance of IERC20Metadata, bound to a specific deployed contract. -func NewIERC20Metadata(address common.Address, backend bind.ContractBackend) (*IERC20Metadata, error) { - contract, err := bindIERC20Metadata(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &IERC20Metadata{IERC20MetadataCaller: IERC20MetadataCaller{contract: contract}, IERC20MetadataTransactor: IERC20MetadataTransactor{contract: contract}, IERC20MetadataFilterer: IERC20MetadataFilterer{contract: contract}}, nil -} - -// NewIERC20MetadataCaller creates a new read-only instance of IERC20Metadata, bound to a specific deployed contract. -func NewIERC20MetadataCaller(address common.Address, caller bind.ContractCaller) (*IERC20MetadataCaller, error) { - contract, err := bindIERC20Metadata(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &IERC20MetadataCaller{contract: contract}, nil -} - -// NewIERC20MetadataTransactor creates a new write-only instance of IERC20Metadata, bound to a specific deployed contract. -func NewIERC20MetadataTransactor(address common.Address, transactor bind.ContractTransactor) (*IERC20MetadataTransactor, error) { - contract, err := bindIERC20Metadata(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &IERC20MetadataTransactor{contract: contract}, nil -} - -// NewIERC20MetadataFilterer creates a new log filterer instance of IERC20Metadata, bound to a specific deployed contract. -func NewIERC20MetadataFilterer(address common.Address, filterer bind.ContractFilterer) (*IERC20MetadataFilterer, error) { - contract, err := bindIERC20Metadata(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &IERC20MetadataFilterer{contract: contract}, nil -} - -// bindIERC20Metadata binds a generic wrapper to an already deployed contract. -func bindIERC20Metadata(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(IERC20MetadataABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_IERC20Metadata *IERC20MetadataRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _IERC20Metadata.Contract.IERC20MetadataCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_IERC20Metadata *IERC20MetadataRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _IERC20Metadata.Contract.IERC20MetadataTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_IERC20Metadata *IERC20MetadataRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _IERC20Metadata.Contract.IERC20MetadataTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_IERC20Metadata *IERC20MetadataCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _IERC20Metadata.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_IERC20Metadata *IERC20MetadataTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _IERC20Metadata.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_IERC20Metadata *IERC20MetadataTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _IERC20Metadata.Contract.contract.Transact(opts, method, params...) -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_IERC20Metadata *IERC20MetadataCaller) Allowance(opts *bind.CallOpts, owner common.Address, spender common.Address) (*big.Int, error) { - var out []interface{} - err := _IERC20Metadata.contract.Call(opts, &out, "allowance", owner, spender) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_IERC20Metadata *IERC20MetadataSession) Allowance(owner common.Address, spender common.Address) (*big.Int, error) { - return _IERC20Metadata.Contract.Allowance(&_IERC20Metadata.CallOpts, owner, spender) -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_IERC20Metadata *IERC20MetadataCallerSession) Allowance(owner common.Address, spender common.Address) (*big.Int, error) { - return _IERC20Metadata.Contract.Allowance(&_IERC20Metadata.CallOpts, owner, spender) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_IERC20Metadata *IERC20MetadataCaller) BalanceOf(opts *bind.CallOpts, account common.Address) (*big.Int, error) { - var out []interface{} - err := _IERC20Metadata.contract.Call(opts, &out, "balanceOf", account) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_IERC20Metadata *IERC20MetadataSession) BalanceOf(account common.Address) (*big.Int, error) { - return _IERC20Metadata.Contract.BalanceOf(&_IERC20Metadata.CallOpts, account) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_IERC20Metadata *IERC20MetadataCallerSession) BalanceOf(account common.Address) (*big.Int, error) { - return _IERC20Metadata.Contract.BalanceOf(&_IERC20Metadata.CallOpts, account) -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() view returns(uint8) -func (_IERC20Metadata *IERC20MetadataCaller) Decimals(opts *bind.CallOpts) (uint8, error) { - var out []interface{} - err := _IERC20Metadata.contract.Call(opts, &out, "decimals") - - if err != nil { - return *new(uint8), err - } - - out0 := *abi.ConvertType(out[0], new(uint8)).(*uint8) - - return out0, err - -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() view returns(uint8) -func (_IERC20Metadata *IERC20MetadataSession) Decimals() (uint8, error) { - return _IERC20Metadata.Contract.Decimals(&_IERC20Metadata.CallOpts) -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() view returns(uint8) -func (_IERC20Metadata *IERC20MetadataCallerSession) Decimals() (uint8, error) { - return _IERC20Metadata.Contract.Decimals(&_IERC20Metadata.CallOpts) -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_IERC20Metadata *IERC20MetadataCaller) Name(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _IERC20Metadata.contract.Call(opts, &out, "name") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_IERC20Metadata *IERC20MetadataSession) Name() (string, error) { - return _IERC20Metadata.Contract.Name(&_IERC20Metadata.CallOpts) -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_IERC20Metadata *IERC20MetadataCallerSession) Name() (string, error) { - return _IERC20Metadata.Contract.Name(&_IERC20Metadata.CallOpts) -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_IERC20Metadata *IERC20MetadataCaller) Symbol(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _IERC20Metadata.contract.Call(opts, &out, "symbol") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_IERC20Metadata *IERC20MetadataSession) Symbol() (string, error) { - return _IERC20Metadata.Contract.Symbol(&_IERC20Metadata.CallOpts) -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_IERC20Metadata *IERC20MetadataCallerSession) Symbol() (string, error) { - return _IERC20Metadata.Contract.Symbol(&_IERC20Metadata.CallOpts) -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_IERC20Metadata *IERC20MetadataCaller) TotalSupply(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _IERC20Metadata.contract.Call(opts, &out, "totalSupply") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_IERC20Metadata *IERC20MetadataSession) TotalSupply() (*big.Int, error) { - return _IERC20Metadata.Contract.TotalSupply(&_IERC20Metadata.CallOpts) -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_IERC20Metadata *IERC20MetadataCallerSession) TotalSupply() (*big.Int, error) { - return _IERC20Metadata.Contract.TotalSupply(&_IERC20Metadata.CallOpts) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataTransactor) Approve(opts *bind.TransactOpts, spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.contract.Transact(opts, "approve", spender, amount) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataSession) Approve(spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.Contract.Approve(&_IERC20Metadata.TransactOpts, spender, amount) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataTransactorSession) Approve(spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.Contract.Approve(&_IERC20Metadata.TransactOpts, spender, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataTransactor) Transfer(opts *bind.TransactOpts, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.contract.Transact(opts, "transfer", recipient, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataSession) Transfer(recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.Contract.Transfer(&_IERC20Metadata.TransactOpts, recipient, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataTransactorSession) Transfer(recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.Contract.Transfer(&_IERC20Metadata.TransactOpts, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataTransactor) TransferFrom(opts *bind.TransactOpts, sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.contract.Transact(opts, "transferFrom", sender, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataSession) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.Contract.TransferFrom(&_IERC20Metadata.TransactOpts, sender, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataTransactorSession) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.Contract.TransferFrom(&_IERC20Metadata.TransactOpts, sender, recipient, amount) -} - -// IERC20MetadataApprovalIterator is returned from FilterApproval and is used to iterate over the raw logs and unpacked data for Approval events raised by the IERC20Metadata contract. -type IERC20MetadataApprovalIterator struct { - Event *IERC20MetadataApproval // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *IERC20MetadataApprovalIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(IERC20MetadataApproval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(IERC20MetadataApproval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *IERC20MetadataApprovalIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *IERC20MetadataApprovalIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// IERC20MetadataApproval represents a Approval event raised by the IERC20Metadata contract. -type IERC20MetadataApproval struct { - Owner common.Address - Spender common.Address - Value *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterApproval is a free log retrieval operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_IERC20Metadata *IERC20MetadataFilterer) FilterApproval(opts *bind.FilterOpts, owner []common.Address, spender []common.Address) (*IERC20MetadataApprovalIterator, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var spenderRule []interface{} - for _, spenderItem := range spender { - spenderRule = append(spenderRule, spenderItem) - } - - logs, sub, err := _IERC20Metadata.contract.FilterLogs(opts, "Approval", ownerRule, spenderRule) - if err != nil { - return nil, err - } - return &IERC20MetadataApprovalIterator{contract: _IERC20Metadata.contract, event: "Approval", logs: logs, sub: sub}, nil -} - -// WatchApproval is a free log subscription operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_IERC20Metadata *IERC20MetadataFilterer) WatchApproval(opts *bind.WatchOpts, sink chan<- *IERC20MetadataApproval, owner []common.Address, spender []common.Address) (event.Subscription, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var spenderRule []interface{} - for _, spenderItem := range spender { - spenderRule = append(spenderRule, spenderItem) - } - - logs, sub, err := _IERC20Metadata.contract.WatchLogs(opts, "Approval", ownerRule, spenderRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(IERC20MetadataApproval) - if err := _IERC20Metadata.contract.UnpackLog(event, "Approval", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseApproval is a log parse operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_IERC20Metadata *IERC20MetadataFilterer) ParseApproval(log types.Log) (*IERC20MetadataApproval, error) { - event := new(IERC20MetadataApproval) - if err := _IERC20Metadata.contract.UnpackLog(event, "Approval", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// IERC20MetadataTransferIterator is returned from FilterTransfer and is used to iterate over the raw logs and unpacked data for Transfer events raised by the IERC20Metadata contract. -type IERC20MetadataTransferIterator struct { - Event *IERC20MetadataTransfer // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *IERC20MetadataTransferIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(IERC20MetadataTransfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(IERC20MetadataTransfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *IERC20MetadataTransferIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *IERC20MetadataTransferIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// IERC20MetadataTransfer represents a Transfer event raised by the IERC20Metadata contract. -type IERC20MetadataTransfer struct { - From common.Address - To common.Address - Value *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterTransfer is a free log retrieval operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_IERC20Metadata *IERC20MetadataFilterer) FilterTransfer(opts *bind.FilterOpts, from []common.Address, to []common.Address) (*IERC20MetadataTransferIterator, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - logs, sub, err := _IERC20Metadata.contract.FilterLogs(opts, "Transfer", fromRule, toRule) - if err != nil { - return nil, err - } - return &IERC20MetadataTransferIterator{contract: _IERC20Metadata.contract, event: "Transfer", logs: logs, sub: sub}, nil -} - -// WatchTransfer is a free log subscription operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_IERC20Metadata *IERC20MetadataFilterer) WatchTransfer(opts *bind.WatchOpts, sink chan<- *IERC20MetadataTransfer, from []common.Address, to []common.Address) (event.Subscription, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - logs, sub, err := _IERC20Metadata.contract.WatchLogs(opts, "Transfer", fromRule, toRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(IERC20MetadataTransfer) - if err := _IERC20Metadata.contract.UnpackLog(event, "Transfer", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseTransfer is a log parse operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_IERC20Metadata *IERC20MetadataFilterer) ParseTransfer(log types.Log) (*IERC20MetadataTransfer, error) { - event := new(IERC20MetadataTransfer) - if err := _IERC20Metadata.contract.UnpackLog(event, "Transfer", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} diff --git a/zcnbridge/ethereum/token/token.go b/zcnbridge/ethereum/token/token.go new file mode 100644 index 000000000..25d2e740d --- /dev/null +++ b/zcnbridge/ethereum/token/token.go @@ -0,0 +1,1336 @@ +// Code generated - DO NOT EDIT. +// This file is a generated binding and any manual changes will be lost. + +package token + +import ( + "errors" + "math/big" + "strings" + + ethereum "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/event" +) + +// Reference imports to suppress errors if they are not otherwise used. +var ( + _ = errors.New + _ = big.NewInt + _ = strings.NewReader + _ = ethereum.NotFound + _ = bind.Bind + _ = common.Big1 + _ = types.BloomLookup + _ = event.NewSubscription + _ = abi.ConvertType +) + +// TokenMetaData contains all meta data concerning the Token contract. +var TokenMetaData = &bind.MetaData{ + ABI: "[{\"constant\":true,\"inputs\":[],\"name\":\"mintingFinished\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_amount\",\"type\":\"uint256\"}],\"name\":\"mint\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_subtractedValue\",\"type\":\"uint256\"}],\"name\":\"decreaseApproval\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"balance\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"finishMinting\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_addedValue\",\"type\":\"uint256\"}],\"name\":\"increaseApproval\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"},{\"name\":\"_spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"Mint\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[],\"name\":\"MintFinished\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"}]", +} + +// TokenABI is the input ABI used to generate the binding from. +// Deprecated: Use TokenMetaData.ABI instead. +var TokenABI = TokenMetaData.ABI + +// Token is an auto generated Go binding around an Ethereum contract. +type Token struct { + TokenCaller // Read-only binding to the contract + TokenTransactor // Write-only binding to the contract + TokenFilterer // Log filterer for contract events +} + +// TokenCaller is an auto generated read-only Go binding around an Ethereum contract. +type TokenCaller struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// TokenTransactor is an auto generated write-only Go binding around an Ethereum contract. +type TokenTransactor struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// TokenFilterer is an auto generated log filtering Go binding around an Ethereum contract events. +type TokenFilterer struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// TokenSession is an auto generated Go binding around an Ethereum contract, +// with pre-set call and transact options. +type TokenSession struct { + Contract *Token // Generic contract binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// TokenCallerSession is an auto generated read-only Go binding around an Ethereum contract, +// with pre-set call options. +type TokenCallerSession struct { + Contract *TokenCaller // Generic contract caller binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session +} + +// TokenTransactorSession is an auto generated write-only Go binding around an Ethereum contract, +// with pre-set transact options. +type TokenTransactorSession struct { + Contract *TokenTransactor // Generic contract transactor binding to set the session for + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// TokenRaw is an auto generated low-level Go binding around an Ethereum contract. +type TokenRaw struct { + Contract *Token // Generic contract binding to access the raw methods on +} + +// TokenCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. +type TokenCallerRaw struct { + Contract *TokenCaller // Generic read-only contract binding to access the raw methods on +} + +// TokenTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. +type TokenTransactorRaw struct { + Contract *TokenTransactor // Generic write-only contract binding to access the raw methods on +} + +// NewToken creates a new instance of Token, bound to a specific deployed contract. +func NewToken(address common.Address, backend bind.ContractBackend) (*Token, error) { + contract, err := bindToken(address, backend, backend, backend) + if err != nil { + return nil, err + } + return &Token{TokenCaller: TokenCaller{contract: contract}, TokenTransactor: TokenTransactor{contract: contract}, TokenFilterer: TokenFilterer{contract: contract}}, nil +} + +// NewTokenCaller creates a new read-only instance of Token, bound to a specific deployed contract. +func NewTokenCaller(address common.Address, caller bind.ContractCaller) (*TokenCaller, error) { + contract, err := bindToken(address, caller, nil, nil) + if err != nil { + return nil, err + } + return &TokenCaller{contract: contract}, nil +} + +// NewTokenTransactor creates a new write-only instance of Token, bound to a specific deployed contract. +func NewTokenTransactor(address common.Address, transactor bind.ContractTransactor) (*TokenTransactor, error) { + contract, err := bindToken(address, nil, transactor, nil) + if err != nil { + return nil, err + } + return &TokenTransactor{contract: contract}, nil +} + +// NewTokenFilterer creates a new log filterer instance of Token, bound to a specific deployed contract. +func NewTokenFilterer(address common.Address, filterer bind.ContractFilterer) (*TokenFilterer, error) { + contract, err := bindToken(address, nil, nil, filterer) + if err != nil { + return nil, err + } + return &TokenFilterer{contract: contract}, nil +} + +// bindToken binds a generic wrapper to an already deployed contract. +func bindToken(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { + parsed, err := TokenMetaData.GetAbi() + if err != nil { + return nil, err + } + return bind.NewBoundContract(address, *parsed, caller, transactor, filterer), nil +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_Token *TokenRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _Token.Contract.TokenCaller.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_Token *TokenRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Token.Contract.TokenTransactor.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_Token *TokenRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _Token.Contract.TokenTransactor.contract.Transact(opts, method, params...) +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_Token *TokenCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _Token.Contract.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_Token *TokenTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Token.Contract.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_Token *TokenTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _Token.Contract.contract.Transact(opts, method, params...) +} + +// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. +// +// Solidity: function allowance(address _owner, address _spender) view returns(uint256) +func (_Token *TokenCaller) Allowance(opts *bind.CallOpts, _owner common.Address, _spender common.Address) (*big.Int, error) { + var out []interface{} + err := _Token.contract.Call(opts, &out, "allowance", _owner, _spender) + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. +// +// Solidity: function allowance(address _owner, address _spender) view returns(uint256) +func (_Token *TokenSession) Allowance(_owner common.Address, _spender common.Address) (*big.Int, error) { + return _Token.Contract.Allowance(&_Token.CallOpts, _owner, _spender) +} + +// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. +// +// Solidity: function allowance(address _owner, address _spender) view returns(uint256) +func (_Token *TokenCallerSession) Allowance(_owner common.Address, _spender common.Address) (*big.Int, error) { + return _Token.Contract.Allowance(&_Token.CallOpts, _owner, _spender) +} + +// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. +// +// Solidity: function balanceOf(address _owner) view returns(uint256 balance) +func (_Token *TokenCaller) BalanceOf(opts *bind.CallOpts, _owner common.Address) (*big.Int, error) { + var out []interface{} + err := _Token.contract.Call(opts, &out, "balanceOf", _owner) + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. +// +// Solidity: function balanceOf(address _owner) view returns(uint256 balance) +func (_Token *TokenSession) BalanceOf(_owner common.Address) (*big.Int, error) { + return _Token.Contract.BalanceOf(&_Token.CallOpts, _owner) +} + +// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. +// +// Solidity: function balanceOf(address _owner) view returns(uint256 balance) +func (_Token *TokenCallerSession) BalanceOf(_owner common.Address) (*big.Int, error) { + return _Token.Contract.BalanceOf(&_Token.CallOpts, _owner) +} + +// Decimals is a free data retrieval call binding the contract method 0x313ce567. +// +// Solidity: function decimals() view returns(uint8) +func (_Token *TokenCaller) Decimals(opts *bind.CallOpts) (uint8, error) { + var out []interface{} + err := _Token.contract.Call(opts, &out, "decimals") + + if err != nil { + return *new(uint8), err + } + + out0 := *abi.ConvertType(out[0], new(uint8)).(*uint8) + + return out0, err + +} + +// Decimals is a free data retrieval call binding the contract method 0x313ce567. +// +// Solidity: function decimals() view returns(uint8) +func (_Token *TokenSession) Decimals() (uint8, error) { + return _Token.Contract.Decimals(&_Token.CallOpts) +} + +// Decimals is a free data retrieval call binding the contract method 0x313ce567. +// +// Solidity: function decimals() view returns(uint8) +func (_Token *TokenCallerSession) Decimals() (uint8, error) { + return _Token.Contract.Decimals(&_Token.CallOpts) +} + +// MintingFinished is a free data retrieval call binding the contract method 0x05d2035b. +// +// Solidity: function mintingFinished() view returns(bool) +func (_Token *TokenCaller) MintingFinished(opts *bind.CallOpts) (bool, error) { + var out []interface{} + err := _Token.contract.Call(opts, &out, "mintingFinished") + + if err != nil { + return *new(bool), err + } + + out0 := *abi.ConvertType(out[0], new(bool)).(*bool) + + return out0, err + +} + +// MintingFinished is a free data retrieval call binding the contract method 0x05d2035b. +// +// Solidity: function mintingFinished() view returns(bool) +func (_Token *TokenSession) MintingFinished() (bool, error) { + return _Token.Contract.MintingFinished(&_Token.CallOpts) +} + +// MintingFinished is a free data retrieval call binding the contract method 0x05d2035b. +// +// Solidity: function mintingFinished() view returns(bool) +func (_Token *TokenCallerSession) MintingFinished() (bool, error) { + return _Token.Contract.MintingFinished(&_Token.CallOpts) +} + +// Name is a free data retrieval call binding the contract method 0x06fdde03. +// +// Solidity: function name() view returns(string) +func (_Token *TokenCaller) Name(opts *bind.CallOpts) (string, error) { + var out []interface{} + err := _Token.contract.Call(opts, &out, "name") + + if err != nil { + return *new(string), err + } + + out0 := *abi.ConvertType(out[0], new(string)).(*string) + + return out0, err + +} + +// Name is a free data retrieval call binding the contract method 0x06fdde03. +// +// Solidity: function name() view returns(string) +func (_Token *TokenSession) Name() (string, error) { + return _Token.Contract.Name(&_Token.CallOpts) +} + +// Name is a free data retrieval call binding the contract method 0x06fdde03. +// +// Solidity: function name() view returns(string) +func (_Token *TokenCallerSession) Name() (string, error) { + return _Token.Contract.Name(&_Token.CallOpts) +} + +// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. +// +// Solidity: function owner() view returns(address) +func (_Token *TokenCaller) Owner(opts *bind.CallOpts) (common.Address, error) { + var out []interface{} + err := _Token.contract.Call(opts, &out, "owner") + + if err != nil { + return *new(common.Address), err + } + + out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) + + return out0, err + +} + +// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. +// +// Solidity: function owner() view returns(address) +func (_Token *TokenSession) Owner() (common.Address, error) { + return _Token.Contract.Owner(&_Token.CallOpts) +} + +// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. +// +// Solidity: function owner() view returns(address) +func (_Token *TokenCallerSession) Owner() (common.Address, error) { + return _Token.Contract.Owner(&_Token.CallOpts) +} + +// Symbol is a free data retrieval call binding the contract method 0x95d89b41. +// +// Solidity: function symbol() view returns(string) +func (_Token *TokenCaller) Symbol(opts *bind.CallOpts) (string, error) { + var out []interface{} + err := _Token.contract.Call(opts, &out, "symbol") + + if err != nil { + return *new(string), err + } + + out0 := *abi.ConvertType(out[0], new(string)).(*string) + + return out0, err + +} + +// Symbol is a free data retrieval call binding the contract method 0x95d89b41. +// +// Solidity: function symbol() view returns(string) +func (_Token *TokenSession) Symbol() (string, error) { + return _Token.Contract.Symbol(&_Token.CallOpts) +} + +// Symbol is a free data retrieval call binding the contract method 0x95d89b41. +// +// Solidity: function symbol() view returns(string) +func (_Token *TokenCallerSession) Symbol() (string, error) { + return _Token.Contract.Symbol(&_Token.CallOpts) +} + +// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. +// +// Solidity: function totalSupply() view returns(uint256) +func (_Token *TokenCaller) TotalSupply(opts *bind.CallOpts) (*big.Int, error) { + var out []interface{} + err := _Token.contract.Call(opts, &out, "totalSupply") + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. +// +// Solidity: function totalSupply() view returns(uint256) +func (_Token *TokenSession) TotalSupply() (*big.Int, error) { + return _Token.Contract.TotalSupply(&_Token.CallOpts) +} + +// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. +// +// Solidity: function totalSupply() view returns(uint256) +func (_Token *TokenCallerSession) TotalSupply() (*big.Int, error) { + return _Token.Contract.TotalSupply(&_Token.CallOpts) +} + +// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. +// +// Solidity: function approve(address _spender, uint256 _value) returns(bool) +func (_Token *TokenTransactor) Approve(opts *bind.TransactOpts, _spender common.Address, _value *big.Int) (*types.Transaction, error) { + return _Token.contract.Transact(opts, "approve", _spender, _value) +} + +// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. +// +// Solidity: function approve(address _spender, uint256 _value) returns(bool) +func (_Token *TokenSession) Approve(_spender common.Address, _value *big.Int) (*types.Transaction, error) { + return _Token.Contract.Approve(&_Token.TransactOpts, _spender, _value) +} + +// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. +// +// Solidity: function approve(address _spender, uint256 _value) returns(bool) +func (_Token *TokenTransactorSession) Approve(_spender common.Address, _value *big.Int) (*types.Transaction, error) { + return _Token.Contract.Approve(&_Token.TransactOpts, _spender, _value) +} + +// DecreaseApproval is a paid mutator transaction binding the contract method 0x66188463. +// +// Solidity: function decreaseApproval(address _spender, uint256 _subtractedValue) returns(bool) +func (_Token *TokenTransactor) DecreaseApproval(opts *bind.TransactOpts, _spender common.Address, _subtractedValue *big.Int) (*types.Transaction, error) { + return _Token.contract.Transact(opts, "decreaseApproval", _spender, _subtractedValue) +} + +// DecreaseApproval is a paid mutator transaction binding the contract method 0x66188463. +// +// Solidity: function decreaseApproval(address _spender, uint256 _subtractedValue) returns(bool) +func (_Token *TokenSession) DecreaseApproval(_spender common.Address, _subtractedValue *big.Int) (*types.Transaction, error) { + return _Token.Contract.DecreaseApproval(&_Token.TransactOpts, _spender, _subtractedValue) +} + +// DecreaseApproval is a paid mutator transaction binding the contract method 0x66188463. +// +// Solidity: function decreaseApproval(address _spender, uint256 _subtractedValue) returns(bool) +func (_Token *TokenTransactorSession) DecreaseApproval(_spender common.Address, _subtractedValue *big.Int) (*types.Transaction, error) { + return _Token.Contract.DecreaseApproval(&_Token.TransactOpts, _spender, _subtractedValue) +} + +// FinishMinting is a paid mutator transaction binding the contract method 0x7d64bcb4. +// +// Solidity: function finishMinting() returns(bool) +func (_Token *TokenTransactor) FinishMinting(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Token.contract.Transact(opts, "finishMinting") +} + +// FinishMinting is a paid mutator transaction binding the contract method 0x7d64bcb4. +// +// Solidity: function finishMinting() returns(bool) +func (_Token *TokenSession) FinishMinting() (*types.Transaction, error) { + return _Token.Contract.FinishMinting(&_Token.TransactOpts) +} + +// FinishMinting is a paid mutator transaction binding the contract method 0x7d64bcb4. +// +// Solidity: function finishMinting() returns(bool) +func (_Token *TokenTransactorSession) FinishMinting() (*types.Transaction, error) { + return _Token.Contract.FinishMinting(&_Token.TransactOpts) +} + +// IncreaseApproval is a paid mutator transaction binding the contract method 0xd73dd623. +// +// Solidity: function increaseApproval(address _spender, uint256 _addedValue) returns(bool) +func (_Token *TokenTransactor) IncreaseApproval(opts *bind.TransactOpts, _spender common.Address, _addedValue *big.Int) (*types.Transaction, error) { + return _Token.contract.Transact(opts, "increaseApproval", _spender, _addedValue) +} + +// IncreaseApproval is a paid mutator transaction binding the contract method 0xd73dd623. +// +// Solidity: function increaseApproval(address _spender, uint256 _addedValue) returns(bool) +func (_Token *TokenSession) IncreaseApproval(_spender common.Address, _addedValue *big.Int) (*types.Transaction, error) { + return _Token.Contract.IncreaseApproval(&_Token.TransactOpts, _spender, _addedValue) +} + +// IncreaseApproval is a paid mutator transaction binding the contract method 0xd73dd623. +// +// Solidity: function increaseApproval(address _spender, uint256 _addedValue) returns(bool) +func (_Token *TokenTransactorSession) IncreaseApproval(_spender common.Address, _addedValue *big.Int) (*types.Transaction, error) { + return _Token.Contract.IncreaseApproval(&_Token.TransactOpts, _spender, _addedValue) +} + +// Mint is a paid mutator transaction binding the contract method 0x40c10f19. +// +// Solidity: function mint(address _to, uint256 _amount) returns(bool) +func (_Token *TokenTransactor) Mint(opts *bind.TransactOpts, _to common.Address, _amount *big.Int) (*types.Transaction, error) { + return _Token.contract.Transact(opts, "mint", _to, _amount) +} + +// Mint is a paid mutator transaction binding the contract method 0x40c10f19. +// +// Solidity: function mint(address _to, uint256 _amount) returns(bool) +func (_Token *TokenSession) Mint(_to common.Address, _amount *big.Int) (*types.Transaction, error) { + return _Token.Contract.Mint(&_Token.TransactOpts, _to, _amount) +} + +// Mint is a paid mutator transaction binding the contract method 0x40c10f19. +// +// Solidity: function mint(address _to, uint256 _amount) returns(bool) +func (_Token *TokenTransactorSession) Mint(_to common.Address, _amount *big.Int) (*types.Transaction, error) { + return _Token.Contract.Mint(&_Token.TransactOpts, _to, _amount) +} + +// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. +// +// Solidity: function transfer(address _to, uint256 _value) returns(bool) +func (_Token *TokenTransactor) Transfer(opts *bind.TransactOpts, _to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Token.contract.Transact(opts, "transfer", _to, _value) +} + +// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. +// +// Solidity: function transfer(address _to, uint256 _value) returns(bool) +func (_Token *TokenSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Token.Contract.Transfer(&_Token.TransactOpts, _to, _value) +} + +// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. +// +// Solidity: function transfer(address _to, uint256 _value) returns(bool) +func (_Token *TokenTransactorSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Token.Contract.Transfer(&_Token.TransactOpts, _to, _value) +} + +// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. +// +// Solidity: function transferFrom(address _from, address _to, uint256 _value) returns(bool) +func (_Token *TokenTransactor) TransferFrom(opts *bind.TransactOpts, _from common.Address, _to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Token.contract.Transact(opts, "transferFrom", _from, _to, _value) +} + +// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. +// +// Solidity: function transferFrom(address _from, address _to, uint256 _value) returns(bool) +func (_Token *TokenSession) TransferFrom(_from common.Address, _to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Token.Contract.TransferFrom(&_Token.TransactOpts, _from, _to, _value) +} + +// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. +// +// Solidity: function transferFrom(address _from, address _to, uint256 _value) returns(bool) +func (_Token *TokenTransactorSession) TransferFrom(_from common.Address, _to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Token.Contract.TransferFrom(&_Token.TransactOpts, _from, _to, _value) +} + +// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. +// +// Solidity: function transferOwnership(address newOwner) returns() +func (_Token *TokenTransactor) TransferOwnership(opts *bind.TransactOpts, newOwner common.Address) (*types.Transaction, error) { + return _Token.contract.Transact(opts, "transferOwnership", newOwner) +} + +// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. +// +// Solidity: function transferOwnership(address newOwner) returns() +func (_Token *TokenSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) { + return _Token.Contract.TransferOwnership(&_Token.TransactOpts, newOwner) +} + +// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. +// +// Solidity: function transferOwnership(address newOwner) returns() +func (_Token *TokenTransactorSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) { + return _Token.Contract.TransferOwnership(&_Token.TransactOpts, newOwner) +} + +// TokenApprovalIterator is returned from FilterApproval and is used to iterate over the raw logs and unpacked data for Approval events raised by the Token contract. +type TokenApprovalIterator struct { + Event *TokenApproval // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *TokenApprovalIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(TokenApproval) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(TokenApproval) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *TokenApprovalIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *TokenApprovalIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// TokenApproval represents a Approval event raised by the Token contract. +type TokenApproval struct { + Owner common.Address + Spender common.Address + Value *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterApproval is a free log retrieval operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. +// +// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) +func (_Token *TokenFilterer) FilterApproval(opts *bind.FilterOpts, owner []common.Address, spender []common.Address) (*TokenApprovalIterator, error) { + + var ownerRule []interface{} + for _, ownerItem := range owner { + ownerRule = append(ownerRule, ownerItem) + } + var spenderRule []interface{} + for _, spenderItem := range spender { + spenderRule = append(spenderRule, spenderItem) + } + + logs, sub, err := _Token.contract.FilterLogs(opts, "Approval", ownerRule, spenderRule) + if err != nil { + return nil, err + } + return &TokenApprovalIterator{contract: _Token.contract, event: "Approval", logs: logs, sub: sub}, nil +} + +// WatchApproval is a free log subscription operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. +// +// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) +func (_Token *TokenFilterer) WatchApproval(opts *bind.WatchOpts, sink chan<- *TokenApproval, owner []common.Address, spender []common.Address) (event.Subscription, error) { + + var ownerRule []interface{} + for _, ownerItem := range owner { + ownerRule = append(ownerRule, ownerItem) + } + var spenderRule []interface{} + for _, spenderItem := range spender { + spenderRule = append(spenderRule, spenderItem) + } + + logs, sub, err := _Token.contract.WatchLogs(opts, "Approval", ownerRule, spenderRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(TokenApproval) + if err := _Token.contract.UnpackLog(event, "Approval", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseApproval is a log parse operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. +// +// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) +func (_Token *TokenFilterer) ParseApproval(log types.Log) (*TokenApproval, error) { + event := new(TokenApproval) + if err := _Token.contract.UnpackLog(event, "Approval", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// TokenMintIterator is returned from FilterMint and is used to iterate over the raw logs and unpacked data for Mint events raised by the Token contract. +type TokenMintIterator struct { + Event *TokenMint // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *TokenMintIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(TokenMint) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(TokenMint) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *TokenMintIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *TokenMintIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// TokenMint represents a Mint event raised by the Token contract. +type TokenMint struct { + To common.Address + Amount *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterMint is a free log retrieval operation binding the contract event 0x0f6798a560793a54c3bcfe86a93cde1e73087d944c0ea20544137d4121396885. +// +// Solidity: event Mint(address indexed to, uint256 amount) +func (_Token *TokenFilterer) FilterMint(opts *bind.FilterOpts, to []common.Address) (*TokenMintIterator, error) { + + var toRule []interface{} + for _, toItem := range to { + toRule = append(toRule, toItem) + } + + logs, sub, err := _Token.contract.FilterLogs(opts, "Mint", toRule) + if err != nil { + return nil, err + } + return &TokenMintIterator{contract: _Token.contract, event: "Mint", logs: logs, sub: sub}, nil +} + +// WatchMint is a free log subscription operation binding the contract event 0x0f6798a560793a54c3bcfe86a93cde1e73087d944c0ea20544137d4121396885. +// +// Solidity: event Mint(address indexed to, uint256 amount) +func (_Token *TokenFilterer) WatchMint(opts *bind.WatchOpts, sink chan<- *TokenMint, to []common.Address) (event.Subscription, error) { + + var toRule []interface{} + for _, toItem := range to { + toRule = append(toRule, toItem) + } + + logs, sub, err := _Token.contract.WatchLogs(opts, "Mint", toRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(TokenMint) + if err := _Token.contract.UnpackLog(event, "Mint", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseMint is a log parse operation binding the contract event 0x0f6798a560793a54c3bcfe86a93cde1e73087d944c0ea20544137d4121396885. +// +// Solidity: event Mint(address indexed to, uint256 amount) +func (_Token *TokenFilterer) ParseMint(log types.Log) (*TokenMint, error) { + event := new(TokenMint) + if err := _Token.contract.UnpackLog(event, "Mint", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// TokenMintFinishedIterator is returned from FilterMintFinished and is used to iterate over the raw logs and unpacked data for MintFinished events raised by the Token contract. +type TokenMintFinishedIterator struct { + Event *TokenMintFinished // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *TokenMintFinishedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(TokenMintFinished) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(TokenMintFinished) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *TokenMintFinishedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *TokenMintFinishedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// TokenMintFinished represents a MintFinished event raised by the Token contract. +type TokenMintFinished struct { + Raw types.Log // Blockchain specific contextual infos +} + +// FilterMintFinished is a free log retrieval operation binding the contract event 0xae5184fba832cb2b1f702aca6117b8d265eaf03ad33eb133f19dde0f5920fa08. +// +// Solidity: event MintFinished() +func (_Token *TokenFilterer) FilterMintFinished(opts *bind.FilterOpts) (*TokenMintFinishedIterator, error) { + + logs, sub, err := _Token.contract.FilterLogs(opts, "MintFinished") + if err != nil { + return nil, err + } + return &TokenMintFinishedIterator{contract: _Token.contract, event: "MintFinished", logs: logs, sub: sub}, nil +} + +// WatchMintFinished is a free log subscription operation binding the contract event 0xae5184fba832cb2b1f702aca6117b8d265eaf03ad33eb133f19dde0f5920fa08. +// +// Solidity: event MintFinished() +func (_Token *TokenFilterer) WatchMintFinished(opts *bind.WatchOpts, sink chan<- *TokenMintFinished) (event.Subscription, error) { + + logs, sub, err := _Token.contract.WatchLogs(opts, "MintFinished") + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(TokenMintFinished) + if err := _Token.contract.UnpackLog(event, "MintFinished", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseMintFinished is a log parse operation binding the contract event 0xae5184fba832cb2b1f702aca6117b8d265eaf03ad33eb133f19dde0f5920fa08. +// +// Solidity: event MintFinished() +func (_Token *TokenFilterer) ParseMintFinished(log types.Log) (*TokenMintFinished, error) { + event := new(TokenMintFinished) + if err := _Token.contract.UnpackLog(event, "MintFinished", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// TokenOwnershipTransferredIterator is returned from FilterOwnershipTransferred and is used to iterate over the raw logs and unpacked data for OwnershipTransferred events raised by the Token contract. +type TokenOwnershipTransferredIterator struct { + Event *TokenOwnershipTransferred // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *TokenOwnershipTransferredIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(TokenOwnershipTransferred) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(TokenOwnershipTransferred) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *TokenOwnershipTransferredIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *TokenOwnershipTransferredIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// TokenOwnershipTransferred represents a OwnershipTransferred event raised by the Token contract. +type TokenOwnershipTransferred struct { + PreviousOwner common.Address + NewOwner common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterOwnershipTransferred is a free log retrieval operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. +// +// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) +func (_Token *TokenFilterer) FilterOwnershipTransferred(opts *bind.FilterOpts, previousOwner []common.Address, newOwner []common.Address) (*TokenOwnershipTransferredIterator, error) { + + var previousOwnerRule []interface{} + for _, previousOwnerItem := range previousOwner { + previousOwnerRule = append(previousOwnerRule, previousOwnerItem) + } + var newOwnerRule []interface{} + for _, newOwnerItem := range newOwner { + newOwnerRule = append(newOwnerRule, newOwnerItem) + } + + logs, sub, err := _Token.contract.FilterLogs(opts, "OwnershipTransferred", previousOwnerRule, newOwnerRule) + if err != nil { + return nil, err + } + return &TokenOwnershipTransferredIterator{contract: _Token.contract, event: "OwnershipTransferred", logs: logs, sub: sub}, nil +} + +// WatchOwnershipTransferred is a free log subscription operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. +// +// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) +func (_Token *TokenFilterer) WatchOwnershipTransferred(opts *bind.WatchOpts, sink chan<- *TokenOwnershipTransferred, previousOwner []common.Address, newOwner []common.Address) (event.Subscription, error) { + + var previousOwnerRule []interface{} + for _, previousOwnerItem := range previousOwner { + previousOwnerRule = append(previousOwnerRule, previousOwnerItem) + } + var newOwnerRule []interface{} + for _, newOwnerItem := range newOwner { + newOwnerRule = append(newOwnerRule, newOwnerItem) + } + + logs, sub, err := _Token.contract.WatchLogs(opts, "OwnershipTransferred", previousOwnerRule, newOwnerRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(TokenOwnershipTransferred) + if err := _Token.contract.UnpackLog(event, "OwnershipTransferred", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseOwnershipTransferred is a log parse operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. +// +// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) +func (_Token *TokenFilterer) ParseOwnershipTransferred(log types.Log) (*TokenOwnershipTransferred, error) { + event := new(TokenOwnershipTransferred) + if err := _Token.contract.UnpackLog(event, "OwnershipTransferred", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// TokenTransferIterator is returned from FilterTransfer and is used to iterate over the raw logs and unpacked data for Transfer events raised by the Token contract. +type TokenTransferIterator struct { + Event *TokenTransfer // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *TokenTransferIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(TokenTransfer) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(TokenTransfer) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *TokenTransferIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *TokenTransferIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// TokenTransfer represents a Transfer event raised by the Token contract. +type TokenTransfer struct { + From common.Address + To common.Address + Value *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterTransfer is a free log retrieval operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. +// +// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) +func (_Token *TokenFilterer) FilterTransfer(opts *bind.FilterOpts, from []common.Address, to []common.Address) (*TokenTransferIterator, error) { + + var fromRule []interface{} + for _, fromItem := range from { + fromRule = append(fromRule, fromItem) + } + var toRule []interface{} + for _, toItem := range to { + toRule = append(toRule, toItem) + } + + logs, sub, err := _Token.contract.FilterLogs(opts, "Transfer", fromRule, toRule) + if err != nil { + return nil, err + } + return &TokenTransferIterator{contract: _Token.contract, event: "Transfer", logs: logs, sub: sub}, nil +} + +// WatchTransfer is a free log subscription operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. +// +// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) +func (_Token *TokenFilterer) WatchTransfer(opts *bind.WatchOpts, sink chan<- *TokenTransfer, from []common.Address, to []common.Address) (event.Subscription, error) { + + var fromRule []interface{} + for _, fromItem := range from { + fromRule = append(fromRule, fromItem) + } + var toRule []interface{} + for _, toItem := range to { + toRule = append(toRule, toItem) + } + + logs, sub, err := _Token.contract.WatchLogs(opts, "Transfer", fromRule, toRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(TokenTransfer) + if err := _Token.contract.UnpackLog(event, "Transfer", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseTransfer is a log parse operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. +// +// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) +func (_Token *TokenFilterer) ParseTransfer(log types.Log) (*TokenTransfer, error) { + event := new(TokenTransfer) + if err := _Token.contract.UnpackLog(event, "Transfer", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} diff --git a/zcnbridge/keystore.go b/zcnbridge/keystore.go index 0beaf30dc..477cd54d1 100644 --- a/zcnbridge/keystore.go +++ b/zcnbridge/keystore.go @@ -12,6 +12,13 @@ import ( "github.com/pkg/errors" ) +// DetailedAccount describes detailed account +type DetailedAccount struct { + EthereumAddress, + PublicKey, + PrivateKey accounts.Account +} + // KeyStore is a wrapper, which exposes Ethereum KeyStore methods used by DEX bridge. type KeyStore interface { Find(accounts.Account) (accounts.Account, error) @@ -24,23 +31,23 @@ type keyStore struct { ks *keystore.KeyStore } -// Creates new KeyStore wrapper instance +// NewKeyStore creates new KeyStore wrapper instance func NewKeyStore(path string) KeyStore { return &keyStore{ ks: keystore.NewKeyStore(path, keystore.StandardScryptN, keystore.StandardScryptP), } } -// TimedUnlock forwards request to Ethereum KeyStore TimedUnlock method -func (k *keyStore) TimedUnlock(account accounts.Account, passPhrase string, timeout time.Duration) error { - return k.ks.TimedUnlock(account, passPhrase, timeout) -} - // Find forwards request to Ethereum KeyStore Find method func (k *keyStore) Find(account accounts.Account) (accounts.Account, error) { return k.ks.Find(account) } +// TimedUnlock forwards request to Ethereum KeyStore TimedUnlock method +func (k *keyStore) TimedUnlock(account accounts.Account, passPhrase string, timeout time.Duration) error { + return k.ks.TimedUnlock(account, passPhrase, timeout) +} + // SignHash forwards request to Ethereum KeyStore SignHash method func (k *keyStore) SignHash(account accounts.Account, hash []byte) ([]byte, error) { return k.ks.SignHash(account, hash) diff --git a/zcncore/mswallet_base.go b/zcncore/mswallet_base.go index b51d70c37..c1762cd92 100644 --- a/zcncore/mswallet_base.go +++ b/zcncore/mswallet_base.go @@ -13,7 +13,7 @@ import ( "github.com/0chain/gosdk/core/zcncrypto" ) -//MSVoteCallback callback definition multisig Vote function +// MSVoteCallback callback definition multisig Vote function type MSVoteCallback interface { OnVoteComplete(status int, proposal string, err string) } @@ -123,6 +123,10 @@ func GetClientID(pkey string) string { return encryption.Hash(publicKeyBytes) } +func GetClientWalletKey() string { + return _config.wallet.ClientKey +} + func GetClientWalletID() string { return _config.wallet.ClientID } diff --git a/zcnswap/config/config.go b/zcnswap/config/config.go deleted file mode 100644 index 0d1b0182b..000000000 --- a/zcnswap/config/config.go +++ /dev/null @@ -1,69 +0,0 @@ -package config - -import ( - "errors" - "os" - - thrown "github.com/0chain/errors" - "github.com/0chain/gosdk/core/conf" - "github.com/0chain/gosdk/core/sys" - "github.com/spf13/viper" -) - -var Configuration SwapConfig - -type SwapConfig struct { - BancorAddress string - UsdcTokenAddress string - ZcnTokenAddress string - WalletMnemonic string -} - -func Init(file string) error { - var err error - Configuration, err = loadConfigFile(file) - - return err -} - -func SetWalletMnemonic(mnemonic string) { - Configuration.WalletMnemonic = mnemonic -} - -// LoadConfigFile load and parse Config from file -func loadConfigFile(file string) (SwapConfig, error) { - - var cfg SwapConfig - var err error - - _, err = sys.Files.Stat(file) - - if err != nil { - if errors.Is(err, os.ErrNotExist) { - return cfg, thrown.Throw(conf.ErrMssingConfig, file) - } - return cfg, err - } - - v := viper.New() - - v.SetConfigFile(file) - - if err := v.ReadInConfig(); err != nil { - return cfg, thrown.Throw(conf.ErrBadParsing, err.Error()) - } - - return loadConfig(v) -} - -// LoadConfig load and parse config -func loadConfig(v conf.Reader) (SwapConfig, error) { - - var cfg SwapConfig - - cfg.UsdcTokenAddress = v.GetString("zcnswap.usdc_token_address") - cfg.BancorAddress = v.GetString("zcnswap.bancor_address") - cfg.ZcnTokenAddress = v.GetString("zcnswap.zcn_token_address") - - return cfg, nil -} diff --git a/zcnswap/contracts/IERC20.sol b/zcnswap/contracts/IERC20.sol deleted file mode 100755 index a23208dae..000000000 --- a/zcnswap/contracts/IERC20.sol +++ /dev/null @@ -1,14 +0,0 @@ -pragma solidity 0.8.9; -pragma abicoder v2; - -interface IERC20 { - function transferFrom( - address sender, - address recipient, - uint256 amount - ) external returns (bool); - - function approve(address spender, uint256 tokens) - external - returns (bool success); -} diff --git a/zcnswap/contracts/IQuoter.sol b/zcnswap/contracts/IQuoter.sol deleted file mode 100755 index ed7fd2a67..000000000 --- a/zcnswap/contracts/IQuoter.sol +++ /dev/null @@ -1,55 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-or-later -pragma solidity >=0.7.5; -pragma abicoder v2; - -/// @title Quoter Interface -/// @notice Supports quoting the calculated amounts from exact input or exact output swaps -/// @dev These functions are not marked view because they rely on calling non-view functions and reverting -/// to compute the result. They are also not gas efficient and should not be called on-chain. -interface IQuoter { - /// @notice Returns the amount out received for a given exact input swap without executing the swap - /// @param path The path of the swap, i.e. each token pair and the pool fee - /// @param amountIn The amount of the first token to swap - /// @return amountOut The amount of the last token that would be received - function quoteExactInput(bytes memory path, uint256 amountIn) - external - returns (uint256 amountOut); - - /// @notice Returns the amount out received for a given exact input but for a swap of a single pool - /// @param tokenIn The token being swapped in - /// @param tokenOut The token being swapped out - /// @param fee The fee of the token pool to consider for the pair - /// @param amountIn The desired input amount - /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap - /// @return amountOut The amount of `tokenOut` that would be received - function quoteExactInputSingle( - address tokenIn, - address tokenOut, - uint24 fee, - uint256 amountIn, - uint160 sqrtPriceLimitX96 - ) external returns (uint256 amountOut); - - /// @notice Returns the amount in required for a given exact output swap without executing the swap - /// @param path The path of the swap, i.e. each token pair and the pool fee. Path must be provided in reverse order - /// @param amountOut The amount of the last token to receive - /// @return amountIn The amount of first token required to be paid - function quoteExactOutput(bytes memory path, uint256 amountOut) - external - returns (uint256 amountIn); - - /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool - /// @param tokenIn The token being swapped in - /// @param tokenOut The token being swapped out - /// @param fee The fee of the token pool to consider for the pair - /// @param amountOut The desired output amount - /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap - /// @return amountIn The amount required as the input for the swap in order to receive `amountOut` - function quoteExactOutputSingle( - address tokenIn, - address tokenOut, - uint24 fee, - uint256 amountOut, - uint160 sqrtPriceLimitX96 - ) external returns (uint256 amountIn); -} diff --git a/zcnswap/contracts/ISwapRouter.sol b/zcnswap/contracts/ISwapRouter.sol deleted file mode 100755 index 1e4207143..000000000 --- a/zcnswap/contracts/ISwapRouter.sol +++ /dev/null @@ -1,79 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-or-later -pragma solidity >=0.7.5; -pragma abicoder v2; - -import "./IUniswapV3SwapCallback.sol"; - -/// @title Router token swapping functionality -/// @notice Functions for swapping tokens via Uniswap V3 -interface ISwapRouter is IUniswapV3SwapCallback { - struct ExactInputSingleParams { - address tokenIn; - address tokenOut; - uint24 fee; - address recipient; - uint256 deadline; - uint256 amountIn; - uint256 amountOutMinimum; - uint160 sqrtPriceLimitX96; - } - - /// @notice Swaps `amountIn` of one token for as much as possible of another token - /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata - /// @return amountOut The amount of the received token - function exactInputSingle(ExactInputSingleParams calldata params) - external - payable - returns (uint256 amountOut); - - struct ExactInputParams { - bytes path; - address recipient; - uint256 deadline; - uint256 amountIn; - uint256 amountOutMinimum; - } - - /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path - /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata - /// @return amountOut The amount of the received token - function exactInput(ExactInputParams calldata params) - external - payable - returns (uint256 amountOut); - - struct ExactOutputSingleParams { - address tokenIn; - address tokenOut; - uint24 fee; - address recipient; - uint256 deadline; - uint256 amountOut; - uint256 amountInMaximum; - uint160 sqrtPriceLimitX96; - } - - /// @notice Swaps as little as possible of one token for `amountOut` of another token - /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata - /// @return amountIn The amount of the input token - function exactOutputSingle(ExactOutputSingleParams calldata params) - external - payable - returns (uint256 amountIn); - - struct ExactOutputParams { - bytes path; - address recipient; - uint256 deadline; - uint256 amountOut; - uint256 amountInMaximum; - } - - /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) - /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata - /// @return amountIn The amount of the input token - function exactOutput(ExactOutputParams calldata params) - external - payable - returns (uint256 amountIn); -} diff --git a/zcnswap/contracts/bancor.go b/zcnswap/contracts/bancor.go deleted file mode 100755 index 8b78c5809..000000000 --- a/zcnswap/contracts/bancor.go +++ /dev/null @@ -1,445 +0,0 @@ -// Code generated - DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package contracts - -import ( - "errors" - "math/big" - "strings" - - ethereum "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/event" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = errors.New - _ = big.NewInt - _ = strings.NewReader - _ = ethereum.NotFound - _ = bind.Bind - _ = common.Big1 - _ = types.BloomLookup - _ = event.NewSubscription -) - -// IBancorNetworkMetaData contains all meta data concerning the IBancorNetwork contract. -var IBancorNetworkMetaData = &bind.MetaData{ - ABI: "[{\"inputs\":[{\"internalType\":\"contractIReserveToken\",\"name\":\"sourceToken\",\"type\":\"address\"},{\"internalType\":\"contractIReserveToken\",\"name\":\"targetToken\",\"type\":\"address\"}],\"name\":\"conversionPath\",\"outputs\":[{\"internalType\":\"address[]\",\"name\":\"\",\"type\":\"address[]\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"uint256\",\"name\":\"sourceAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"minReturn\",\"type\":\"uint256\"},{\"internalType\":\"addresspayable\",\"name\":\"beneficiary\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"affiliateAccount\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"affiliateFee\",\"type\":\"uint256\"}],\"name\":\"convertByPath\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"uint256\",\"name\":\"sourceAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"minReturn\",\"type\":\"uint256\"},{\"internalType\":\"addresspayable\",\"name\":\"beneficiary\",\"type\":\"address\"}],\"name\":\"convertByPath2\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"uint256\",\"name\":\"sourceAmount\",\"type\":\"uint256\"}],\"name\":\"rateByPath\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"}]", - Sigs: map[string]string{ - "d734fa19": "conversionPath(address,address)", - "b77d239b": "convertByPath(address[],uint256,uint256,address,address,uint256)", - "f8394fb7": "convertByPath2(address[],uint256,uint256,address)", - "7f9c0ecd": "rateByPath(address[],uint256)", - }, -} - -// IBancorNetworkABI is the input ABI used to generate the binding from. -// Deprecated: Use IBancorNetworkMetaData.ABI instead. -var IBancorNetworkABI = IBancorNetworkMetaData.ABI - -// Deprecated: Use IBancorNetworkMetaData.Sigs instead. -// IBancorNetworkFuncSigs maps the 4-byte function signature to its string representation. -var IBancorNetworkFuncSigs = IBancorNetworkMetaData.Sigs - -// IBancorNetwork is an auto generated Go binding around an Ethereum contract. -type IBancorNetwork struct { - IBancorNetworkCaller // Read-only binding to the contract - IBancorNetworkTransactor // Write-only binding to the contract - IBancorNetworkFilterer // Log filterer for contract events -} - -// IBancorNetworkCaller is an auto generated read-only Go binding around an Ethereum contract. -type IBancorNetworkCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IBancorNetworkTransactor is an auto generated write-only Go binding around an Ethereum contract. -type IBancorNetworkTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IBancorNetworkFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type IBancorNetworkFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IBancorNetworkSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type IBancorNetworkSession struct { - Contract *IBancorNetwork // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// IBancorNetworkCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type IBancorNetworkCallerSession struct { - Contract *IBancorNetworkCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// IBancorNetworkTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type IBancorNetworkTransactorSession struct { - Contract *IBancorNetworkTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// IBancorNetworkRaw is an auto generated low-level Go binding around an Ethereum contract. -type IBancorNetworkRaw struct { - Contract *IBancorNetwork // Generic contract binding to access the raw methods on -} - -// IBancorNetworkCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type IBancorNetworkCallerRaw struct { - Contract *IBancorNetworkCaller // Generic read-only contract binding to access the raw methods on -} - -// IBancorNetworkTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type IBancorNetworkTransactorRaw struct { - Contract *IBancorNetworkTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewIBancorNetwork creates a new instance of IBancorNetwork, bound to a specific deployed contract. -func NewIBancorNetwork(address common.Address, backend bind.ContractBackend) (*IBancorNetwork, error) { - contract, err := bindIBancorNetwork(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &IBancorNetwork{IBancorNetworkCaller: IBancorNetworkCaller{contract: contract}, IBancorNetworkTransactor: IBancorNetworkTransactor{contract: contract}, IBancorNetworkFilterer: IBancorNetworkFilterer{contract: contract}}, nil -} - -// NewIBancorNetworkCaller creates a new read-only instance of IBancorNetwork, bound to a specific deployed contract. -func NewIBancorNetworkCaller(address common.Address, caller bind.ContractCaller) (*IBancorNetworkCaller, error) { - contract, err := bindIBancorNetwork(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &IBancorNetworkCaller{contract: contract}, nil -} - -// NewIBancorNetworkTransactor creates a new write-only instance of IBancorNetwork, bound to a specific deployed contract. -func NewIBancorNetworkTransactor(address common.Address, transactor bind.ContractTransactor) (*IBancorNetworkTransactor, error) { - contract, err := bindIBancorNetwork(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &IBancorNetworkTransactor{contract: contract}, nil -} - -// NewIBancorNetworkFilterer creates a new log filterer instance of IBancorNetwork, bound to a specific deployed contract. -func NewIBancorNetworkFilterer(address common.Address, filterer bind.ContractFilterer) (*IBancorNetworkFilterer, error) { - contract, err := bindIBancorNetwork(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &IBancorNetworkFilterer{contract: contract}, nil -} - -// bindIBancorNetwork binds a generic wrapper to an already deployed contract. -func bindIBancorNetwork(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(IBancorNetworkABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_IBancorNetwork *IBancorNetworkRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _IBancorNetwork.Contract.IBancorNetworkCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_IBancorNetwork *IBancorNetworkRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _IBancorNetwork.Contract.IBancorNetworkTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_IBancorNetwork *IBancorNetworkRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _IBancorNetwork.Contract.IBancorNetworkTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_IBancorNetwork *IBancorNetworkCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _IBancorNetwork.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_IBancorNetwork *IBancorNetworkTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _IBancorNetwork.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_IBancorNetwork *IBancorNetworkTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _IBancorNetwork.Contract.contract.Transact(opts, method, params...) -} - -// ConversionPath is a free data retrieval call binding the contract method 0xd734fa19. -// -// Solidity: function conversionPath(address sourceToken, address targetToken) view returns(address[]) -func (_IBancorNetwork *IBancorNetworkCaller) ConversionPath(opts *bind.CallOpts, sourceToken common.Address, targetToken common.Address) ([]common.Address, error) { - var out []interface{} - err := _IBancorNetwork.contract.Call(opts, &out, "conversionPath", sourceToken, targetToken) - - if err != nil { - return *new([]common.Address), err - } - - out0 := *abi.ConvertType(out[0], new([]common.Address)).(*[]common.Address) - - return out0, err - -} - -// ConversionPath is a free data retrieval call binding the contract method 0xd734fa19. -// -// Solidity: function conversionPath(address sourceToken, address targetToken) view returns(address[]) -func (_IBancorNetwork *IBancorNetworkSession) ConversionPath(sourceToken common.Address, targetToken common.Address) ([]common.Address, error) { - return _IBancorNetwork.Contract.ConversionPath(&_IBancorNetwork.CallOpts, sourceToken, targetToken) -} - -// ConversionPath is a free data retrieval call binding the contract method 0xd734fa19. -// -// Solidity: function conversionPath(address sourceToken, address targetToken) view returns(address[]) -func (_IBancorNetwork *IBancorNetworkCallerSession) ConversionPath(sourceToken common.Address, targetToken common.Address) ([]common.Address, error) { - return _IBancorNetwork.Contract.ConversionPath(&_IBancorNetwork.CallOpts, sourceToken, targetToken) -} - -// RateByPath is a free data retrieval call binding the contract method 0x7f9c0ecd. -// -// Solidity: function rateByPath(address[] path, uint256 sourceAmount) view returns(uint256) -func (_IBancorNetwork *IBancorNetworkCaller) RateByPath(opts *bind.CallOpts, path []common.Address, sourceAmount *big.Int) (*big.Int, error) { - var out []interface{} - err := _IBancorNetwork.contract.Call(opts, &out, "rateByPath", path, sourceAmount) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// RateByPath is a free data retrieval call binding the contract method 0x7f9c0ecd. -// -// Solidity: function rateByPath(address[] path, uint256 sourceAmount) view returns(uint256) -func (_IBancorNetwork *IBancorNetworkSession) RateByPath(path []common.Address, sourceAmount *big.Int) (*big.Int, error) { - return _IBancorNetwork.Contract.RateByPath(&_IBancorNetwork.CallOpts, path, sourceAmount) -} - -// RateByPath is a free data retrieval call binding the contract method 0x7f9c0ecd. -// -// Solidity: function rateByPath(address[] path, uint256 sourceAmount) view returns(uint256) -func (_IBancorNetwork *IBancorNetworkCallerSession) RateByPath(path []common.Address, sourceAmount *big.Int) (*big.Int, error) { - return _IBancorNetwork.Contract.RateByPath(&_IBancorNetwork.CallOpts, path, sourceAmount) -} - -// ConvertByPath is a paid mutator transaction binding the contract method 0xb77d239b. -// -// Solidity: function convertByPath(address[] path, uint256 sourceAmount, uint256 minReturn, address beneficiary, address affiliateAccount, uint256 affiliateFee) payable returns(uint256) -func (_IBancorNetwork *IBancorNetworkTransactor) ConvertByPath(opts *bind.TransactOpts, path []common.Address, sourceAmount *big.Int, minReturn *big.Int, beneficiary common.Address, affiliateAccount common.Address, affiliateFee *big.Int) (*types.Transaction, error) { - return _IBancorNetwork.contract.Transact(opts, "convertByPath", path, sourceAmount, minReturn, beneficiary, affiliateAccount, affiliateFee) -} - -// ConvertByPath is a paid mutator transaction binding the contract method 0xb77d239b. -// -// Solidity: function convertByPath(address[] path, uint256 sourceAmount, uint256 minReturn, address beneficiary, address affiliateAccount, uint256 affiliateFee) payable returns(uint256) -func (_IBancorNetwork *IBancorNetworkSession) ConvertByPath(path []common.Address, sourceAmount *big.Int, minReturn *big.Int, beneficiary common.Address, affiliateAccount common.Address, affiliateFee *big.Int) (*types.Transaction, error) { - return _IBancorNetwork.Contract.ConvertByPath(&_IBancorNetwork.TransactOpts, path, sourceAmount, minReturn, beneficiary, affiliateAccount, affiliateFee) -} - -// ConvertByPath is a paid mutator transaction binding the contract method 0xb77d239b. -// -// Solidity: function convertByPath(address[] path, uint256 sourceAmount, uint256 minReturn, address beneficiary, address affiliateAccount, uint256 affiliateFee) payable returns(uint256) -func (_IBancorNetwork *IBancorNetworkTransactorSession) ConvertByPath(path []common.Address, sourceAmount *big.Int, minReturn *big.Int, beneficiary common.Address, affiliateAccount common.Address, affiliateFee *big.Int) (*types.Transaction, error) { - return _IBancorNetwork.Contract.ConvertByPath(&_IBancorNetwork.TransactOpts, path, sourceAmount, minReturn, beneficiary, affiliateAccount, affiliateFee) -} - -// ConvertByPath2 is a paid mutator transaction binding the contract method 0xf8394fb7. -// -// Solidity: function convertByPath2(address[] path, uint256 sourceAmount, uint256 minReturn, address beneficiary) payable returns(uint256) -func (_IBancorNetwork *IBancorNetworkTransactor) ConvertByPath2(opts *bind.TransactOpts, path []common.Address, sourceAmount *big.Int, minReturn *big.Int, beneficiary common.Address) (*types.Transaction, error) { - return _IBancorNetwork.contract.Transact(opts, "convertByPath2", path, sourceAmount, minReturn, beneficiary) -} - -// ConvertByPath2 is a paid mutator transaction binding the contract method 0xf8394fb7. -// -// Solidity: function convertByPath2(address[] path, uint256 sourceAmount, uint256 minReturn, address beneficiary) payable returns(uint256) -func (_IBancorNetwork *IBancorNetworkSession) ConvertByPath2(path []common.Address, sourceAmount *big.Int, minReturn *big.Int, beneficiary common.Address) (*types.Transaction, error) { - return _IBancorNetwork.Contract.ConvertByPath2(&_IBancorNetwork.TransactOpts, path, sourceAmount, minReturn, beneficiary) -} - -// ConvertByPath2 is a paid mutator transaction binding the contract method 0xf8394fb7. -// -// Solidity: function convertByPath2(address[] path, uint256 sourceAmount, uint256 minReturn, address beneficiary) payable returns(uint256) -func (_IBancorNetwork *IBancorNetworkTransactorSession) ConvertByPath2(path []common.Address, sourceAmount *big.Int, minReturn *big.Int, beneficiary common.Address) (*types.Transaction, error) { - return _IBancorNetwork.Contract.ConvertByPath2(&_IBancorNetwork.TransactOpts, path, sourceAmount, minReturn, beneficiary) -} - -// IReserveTokenMetaData contains all meta data concerning the IReserveToken contract. -var IReserveTokenMetaData = &bind.MetaData{ - ABI: "[]", -} - -// IReserveTokenABI is the input ABI used to generate the binding from. -// Deprecated: Use IReserveTokenMetaData.ABI instead. -var IReserveTokenABI = IReserveTokenMetaData.ABI - -// IReserveToken is an auto generated Go binding around an Ethereum contract. -type IReserveToken struct { - IReserveTokenCaller // Read-only binding to the contract - IReserveTokenTransactor // Write-only binding to the contract - IReserveTokenFilterer // Log filterer for contract events -} - -// IReserveTokenCaller is an auto generated read-only Go binding around an Ethereum contract. -type IReserveTokenCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IReserveTokenTransactor is an auto generated write-only Go binding around an Ethereum contract. -type IReserveTokenTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IReserveTokenFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type IReserveTokenFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IReserveTokenSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type IReserveTokenSession struct { - Contract *IReserveToken // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// IReserveTokenCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type IReserveTokenCallerSession struct { - Contract *IReserveTokenCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// IReserveTokenTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type IReserveTokenTransactorSession struct { - Contract *IReserveTokenTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// IReserveTokenRaw is an auto generated low-level Go binding around an Ethereum contract. -type IReserveTokenRaw struct { - Contract *IReserveToken // Generic contract binding to access the raw methods on -} - -// IReserveTokenCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type IReserveTokenCallerRaw struct { - Contract *IReserveTokenCaller // Generic read-only contract binding to access the raw methods on -} - -// IReserveTokenTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type IReserveTokenTransactorRaw struct { - Contract *IReserveTokenTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewIReserveToken creates a new instance of IReserveToken, bound to a specific deployed contract. -func NewIReserveToken(address common.Address, backend bind.ContractBackend) (*IReserveToken, error) { - contract, err := bindIReserveToken(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &IReserveToken{IReserveTokenCaller: IReserveTokenCaller{contract: contract}, IReserveTokenTransactor: IReserveTokenTransactor{contract: contract}, IReserveTokenFilterer: IReserveTokenFilterer{contract: contract}}, nil -} - -// NewIReserveTokenCaller creates a new read-only instance of IReserveToken, bound to a specific deployed contract. -func NewIReserveTokenCaller(address common.Address, caller bind.ContractCaller) (*IReserveTokenCaller, error) { - contract, err := bindIReserveToken(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &IReserveTokenCaller{contract: contract}, nil -} - -// NewIReserveTokenTransactor creates a new write-only instance of IReserveToken, bound to a specific deployed contract. -func NewIReserveTokenTransactor(address common.Address, transactor bind.ContractTransactor) (*IReserveTokenTransactor, error) { - contract, err := bindIReserveToken(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &IReserveTokenTransactor{contract: contract}, nil -} - -// NewIReserveTokenFilterer creates a new log filterer instance of IReserveToken, bound to a specific deployed contract. -func NewIReserveTokenFilterer(address common.Address, filterer bind.ContractFilterer) (*IReserveTokenFilterer, error) { - contract, err := bindIReserveToken(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &IReserveTokenFilterer{contract: contract}, nil -} - -// bindIReserveToken binds a generic wrapper to an already deployed contract. -func bindIReserveToken(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(IReserveTokenABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_IReserveToken *IReserveTokenRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _IReserveToken.Contract.IReserveTokenCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_IReserveToken *IReserveTokenRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _IReserveToken.Contract.IReserveTokenTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_IReserveToken *IReserveTokenRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _IReserveToken.Contract.IReserveTokenTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_IReserveToken *IReserveTokenCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _IReserveToken.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_IReserveToken *IReserveTokenTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _IReserveToken.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_IReserveToken *IReserveTokenTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _IReserveToken.Contract.contract.Transact(opts, method, params...) -} diff --git a/zcnswap/contracts/erc20.go b/zcnswap/contracts/erc20.go deleted file mode 100755 index c87028f5d..000000000 --- a/zcnswap/contracts/erc20.go +++ /dev/null @@ -1,2319 +0,0 @@ -// Code generated - DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package contracts - -import ( - "errors" - "math/big" - "strings" - - ethereum "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/event" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = errors.New - _ = big.NewInt - _ = strings.NewReader - _ = ethereum.NotFound - _ = bind.Bind - _ = common.Big1 - _ = types.BloomLookup - _ = event.NewSubscription -) - -// ContextMetaData contains all meta data concerning the Context contract. -var ContextMetaData = &bind.MetaData{ - ABI: "[]", -} - -// ContextABI is the input ABI used to generate the binding from. -// Deprecated: Use ContextMetaData.ABI instead. -var ContextABI = ContextMetaData.ABI - -// Context is an auto generated Go binding around an Ethereum contract. -type Context struct { - ContextCaller // Read-only binding to the contract - ContextTransactor // Write-only binding to the contract - ContextFilterer // Log filterer for contract events -} - -// ContextCaller is an auto generated read-only Go binding around an Ethereum contract. -type ContextCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ContextTransactor is an auto generated write-only Go binding around an Ethereum contract. -type ContextTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ContextFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type ContextFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ContextSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type ContextSession struct { - Contract *Context // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// ContextCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type ContextCallerSession struct { - Contract *ContextCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// ContextTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type ContextTransactorSession struct { - Contract *ContextTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// ContextRaw is an auto generated low-level Go binding around an Ethereum contract. -type ContextRaw struct { - Contract *Context // Generic contract binding to access the raw methods on -} - -// ContextCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type ContextCallerRaw struct { - Contract *ContextCaller // Generic read-only contract binding to access the raw methods on -} - -// ContextTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type ContextTransactorRaw struct { - Contract *ContextTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewContext creates a new instance of Context, bound to a specific deployed contract. -func NewContext(address common.Address, backend bind.ContractBackend) (*Context, error) { - contract, err := bindContext(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &Context{ContextCaller: ContextCaller{contract: contract}, ContextTransactor: ContextTransactor{contract: contract}, ContextFilterer: ContextFilterer{contract: contract}}, nil -} - -// NewContextCaller creates a new read-only instance of Context, bound to a specific deployed contract. -func NewContextCaller(address common.Address, caller bind.ContractCaller) (*ContextCaller, error) { - contract, err := bindContext(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &ContextCaller{contract: contract}, nil -} - -// NewContextTransactor creates a new write-only instance of Context, bound to a specific deployed contract. -func NewContextTransactor(address common.Address, transactor bind.ContractTransactor) (*ContextTransactor, error) { - contract, err := bindContext(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &ContextTransactor{contract: contract}, nil -} - -// NewContextFilterer creates a new log filterer instance of Context, bound to a specific deployed contract. -func NewContextFilterer(address common.Address, filterer bind.ContractFilterer) (*ContextFilterer, error) { - contract, err := bindContext(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &ContextFilterer{contract: contract}, nil -} - -// bindContext binds a generic wrapper to an already deployed contract. -func bindContext(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(ContextABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Context *ContextRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Context.Contract.ContextCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Context *ContextRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Context.Contract.ContextTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Context *ContextRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Context.Contract.ContextTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Context *ContextCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Context.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Context *ContextTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Context.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Context *ContextTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Context.Contract.contract.Transact(opts, method, params...) -} - -// ERC20MetaData contains all meta data concerning the ERC20 contract. -var ERC20MetaData = &bind.MetaData{ - ABI: "[{\"inputs\":[{\"internalType\":\"string\",\"name\":\"name_\",\"type\":\"string\"},{\"internalType\":\"string\",\"name\":\"symbol_\",\"type\":\"string\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"internalType\":\"uint8\",\"name\":\"\",\"type\":\"uint8\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"subtractedValue\",\"type\":\"uint256\"}],\"name\":\"decreaseAllowance\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"addedValue\",\"type\":\"uint256\"}],\"name\":\"increaseAllowance\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]", - Sigs: map[string]string{ - "dd62ed3e": "allowance(address,address)", - "095ea7b3": "approve(address,uint256)", - "70a08231": "balanceOf(address)", - "313ce567": "decimals()", - "a457c2d7": "decreaseAllowance(address,uint256)", - "39509351": "increaseAllowance(address,uint256)", - "06fdde03": "name()", - "95d89b41": "symbol()", - "18160ddd": "totalSupply()", - "a9059cbb": "transfer(address,uint256)", - "23b872dd": "transferFrom(address,address,uint256)", - }, - Bin: "0x60806040523480156200001157600080fd5b5060405162000b5638038062000b568339810160408190526200003491620001db565b81516200004990600390602085019062000068565b5080516200005f90600490602084019062000068565b50505062000282565b828054620000769062000245565b90600052602060002090601f0160209004810192826200009a5760008555620000e5565b82601f10620000b557805160ff1916838001178555620000e5565b82800160010185558215620000e5579182015b82811115620000e5578251825591602001919060010190620000c8565b50620000f3929150620000f7565b5090565b5b80821115620000f35760008155600101620000f8565b634e487b7160e01b600052604160045260246000fd5b600082601f8301126200013657600080fd5b81516001600160401b03808211156200015357620001536200010e565b604051601f8301601f19908116603f011681019082821181831017156200017e576200017e6200010e565b816040528381526020925086838588010111156200019b57600080fd5b600091505b83821015620001bf5785820183015181830184015290820190620001a0565b83821115620001d15760008385830101525b9695505050505050565b60008060408385031215620001ef57600080fd5b82516001600160401b03808211156200020757600080fd5b620002158683870162000124565b935060208501519150808211156200022c57600080fd5b506200023b8582860162000124565b9150509250929050565b600181811c908216806200025a57607f821691505b602082108114156200027c57634e487b7160e01b600052602260045260246000fd5b50919050565b6108c480620002926000396000f3fe608060405234801561001057600080fd5b50600436106100a95760003560e01c80633950935111610071578063395093511461012357806370a082311461013657806395d89b411461015f578063a457c2d714610167578063a9059cbb1461017a578063dd62ed3e1461018d57600080fd5b806306fdde03146100ae578063095ea7b3146100cc57806318160ddd146100ef57806323b872dd14610101578063313ce56714610114575b600080fd5b6100b66101c6565b6040516100c39190610701565b60405180910390f35b6100df6100da366004610772565b610258565b60405190151581526020016100c3565b6002545b6040519081526020016100c3565b6100df61010f36600461079c565b61026e565b604051601281526020016100c3565b6100df610131366004610772565b61031d565b6100f36101443660046107d8565b6001600160a01b031660009081526020819052604090205490565b6100b6610359565b6100df610175366004610772565b610368565b6100df610188366004610772565b610401565b6100f361019b3660046107fa565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b6060600380546101d59061082d565b80601f01602080910402602001604051908101604052809291908181526020018280546102019061082d565b801561024e5780601f106102235761010080835404028352916020019161024e565b820191906000526020600020905b81548152906001019060200180831161023157829003601f168201915b5050505050905090565b600061026533848461040e565b50600192915050565b600061027b848484610532565b6001600160a01b0384166000908152600160209081526040808320338452909152902054828110156103055760405162461bcd60e51b815260206004820152602860248201527f45524332303a207472616e7366657220616d6f756e74206578636565647320616044820152676c6c6f77616e636560c01b60648201526084015b60405180910390fd5b610312853385840361040e565b506001949350505050565b3360008181526001602090815260408083206001600160a01b03871684529091528120549091610265918590610354908690610868565b61040e565b6060600480546101d59061082d565b3360009081526001602090815260408083206001600160a01b0386168452909152812054828110156103ea5760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b60648201526084016102fc565b6103f7338585840361040e565b5060019392505050565b6000610265338484610532565b6001600160a01b0383166104705760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b60648201526084016102fc565b6001600160a01b0382166104d15760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b60648201526084016102fc565b6001600160a01b0383811660008181526001602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b6001600160a01b0383166105965760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b60648201526084016102fc565b6001600160a01b0382166105f85760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b60648201526084016102fc565b6001600160a01b038316600090815260208190526040902054818110156106705760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b60648201526084016102fc565b6001600160a01b038085166000908152602081905260408082208585039055918516815290812080548492906106a7908490610868565b92505081905550826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040516106f391815260200190565b60405180910390a350505050565b600060208083528351808285015260005b8181101561072e57858101830151858201604001528201610712565b81811115610740576000604083870101525b50601f01601f1916929092016040019392505050565b80356001600160a01b038116811461076d57600080fd5b919050565b6000806040838503121561078557600080fd5b61078e83610756565b946020939093013593505050565b6000806000606084860312156107b157600080fd5b6107ba84610756565b92506107c860208501610756565b9150604084013590509250925092565b6000602082840312156107ea57600080fd5b6107f382610756565b9392505050565b6000806040838503121561080d57600080fd5b61081683610756565b915061082460208401610756565b90509250929050565b600181811c9082168061084157607f821691505b6020821081141561086257634e487b7160e01b600052602260045260246000fd5b50919050565b6000821982111561088957634e487b7160e01b600052601160045260246000fd5b50019056fea26469706673582212203a382710d330bfc5c08286d13b123167071c03a623c45f800ccb995904d07eef64736f6c63430008090033", -} - -// ERC20ABI is the input ABI used to generate the binding from. -// Deprecated: Use ERC20MetaData.ABI instead. -var ERC20ABI = ERC20MetaData.ABI - -// Deprecated: Use ERC20MetaData.Sigs instead. -// ERC20FuncSigs maps the 4-byte function signature to its string representation. -var ERC20FuncSigs = ERC20MetaData.Sigs - -// ERC20Bin is the compiled bytecode used for deploying new contracts. -// Deprecated: Use ERC20MetaData.Bin instead. -var ERC20Bin = ERC20MetaData.Bin - -// DeployERC20 deploys a new Ethereum contract, binding an instance of ERC20 to it. -func DeployERC20(auth *bind.TransactOpts, backend bind.ContractBackend, name_ string, symbol_ string) (common.Address, *types.Transaction, *ERC20, error) { - parsed, err := ERC20MetaData.GetAbi() - if err != nil { - return common.Address{}, nil, nil, err - } - if parsed == nil { - return common.Address{}, nil, nil, errors.New("GetABI returned nil") - } - - address, tx, contract, err := bind.DeployContract(auth, *parsed, common.FromHex(ERC20Bin), backend, name_, symbol_) - if err != nil { - return common.Address{}, nil, nil, err - } - return address, tx, &ERC20{ERC20Caller: ERC20Caller{contract: contract}, ERC20Transactor: ERC20Transactor{contract: contract}, ERC20Filterer: ERC20Filterer{contract: contract}}, nil -} - -// ERC20 is an auto generated Go binding around an Ethereum contract. -type ERC20 struct { - ERC20Caller // Read-only binding to the contract - ERC20Transactor // Write-only binding to the contract - ERC20Filterer // Log filterer for contract events -} - -// ERC20Caller is an auto generated read-only Go binding around an Ethereum contract. -type ERC20Caller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ERC20Transactor is an auto generated write-only Go binding around an Ethereum contract. -type ERC20Transactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ERC20Filterer is an auto generated log filtering Go binding around an Ethereum contract events. -type ERC20Filterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ERC20Session is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type ERC20Session struct { - Contract *ERC20 // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// ERC20CallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type ERC20CallerSession struct { - Contract *ERC20Caller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// ERC20TransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type ERC20TransactorSession struct { - Contract *ERC20Transactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// ERC20Raw is an auto generated low-level Go binding around an Ethereum contract. -type ERC20Raw struct { - Contract *ERC20 // Generic contract binding to access the raw methods on -} - -// ERC20CallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type ERC20CallerRaw struct { - Contract *ERC20Caller // Generic read-only contract binding to access the raw methods on -} - -// ERC20TransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type ERC20TransactorRaw struct { - Contract *ERC20Transactor // Generic write-only contract binding to access the raw methods on -} - -// NewERC20 creates a new instance of ERC20, bound to a specific deployed contract. -func NewERC20(address common.Address, backend bind.ContractBackend) (*ERC20, error) { - contract, err := bindERC20(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &ERC20{ERC20Caller: ERC20Caller{contract: contract}, ERC20Transactor: ERC20Transactor{contract: contract}, ERC20Filterer: ERC20Filterer{contract: contract}}, nil -} - -// NewERC20Caller creates a new read-only instance of ERC20, bound to a specific deployed contract. -func NewERC20Caller(address common.Address, caller bind.ContractCaller) (*ERC20Caller, error) { - contract, err := bindERC20(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &ERC20Caller{contract: contract}, nil -} - -// NewERC20Transactor creates a new write-only instance of ERC20, bound to a specific deployed contract. -func NewERC20Transactor(address common.Address, transactor bind.ContractTransactor) (*ERC20Transactor, error) { - contract, err := bindERC20(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &ERC20Transactor{contract: contract}, nil -} - -// NewERC20Filterer creates a new log filterer instance of ERC20, bound to a specific deployed contract. -func NewERC20Filterer(address common.Address, filterer bind.ContractFilterer) (*ERC20Filterer, error) { - contract, err := bindERC20(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &ERC20Filterer{contract: contract}, nil -} - -// bindERC20 binds a generic wrapper to an already deployed contract. -func bindERC20(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(ERC20ABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_ERC20 *ERC20Raw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _ERC20.Contract.ERC20Caller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_ERC20 *ERC20Raw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _ERC20.Contract.ERC20Transactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_ERC20 *ERC20Raw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _ERC20.Contract.ERC20Transactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_ERC20 *ERC20CallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _ERC20.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_ERC20 *ERC20TransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _ERC20.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_ERC20 *ERC20TransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _ERC20.Contract.contract.Transact(opts, method, params...) -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_ERC20 *ERC20Caller) Allowance(opts *bind.CallOpts, owner common.Address, spender common.Address) (*big.Int, error) { - var out []interface{} - err := _ERC20.contract.Call(opts, &out, "allowance", owner, spender) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_ERC20 *ERC20Session) Allowance(owner common.Address, spender common.Address) (*big.Int, error) { - return _ERC20.Contract.Allowance(&_ERC20.CallOpts, owner, spender) -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_ERC20 *ERC20CallerSession) Allowance(owner common.Address, spender common.Address) (*big.Int, error) { - return _ERC20.Contract.Allowance(&_ERC20.CallOpts, owner, spender) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_ERC20 *ERC20Caller) BalanceOf(opts *bind.CallOpts, account common.Address) (*big.Int, error) { - var out []interface{} - err := _ERC20.contract.Call(opts, &out, "balanceOf", account) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_ERC20 *ERC20Session) BalanceOf(account common.Address) (*big.Int, error) { - return _ERC20.Contract.BalanceOf(&_ERC20.CallOpts, account) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_ERC20 *ERC20CallerSession) BalanceOf(account common.Address) (*big.Int, error) { - return _ERC20.Contract.BalanceOf(&_ERC20.CallOpts, account) -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() view returns(uint8) -func (_ERC20 *ERC20Caller) Decimals(opts *bind.CallOpts) (uint8, error) { - var out []interface{} - err := _ERC20.contract.Call(opts, &out, "decimals") - - if err != nil { - return *new(uint8), err - } - - out0 := *abi.ConvertType(out[0], new(uint8)).(*uint8) - - return out0, err - -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() view returns(uint8) -func (_ERC20 *ERC20Session) Decimals() (uint8, error) { - return _ERC20.Contract.Decimals(&_ERC20.CallOpts) -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() view returns(uint8) -func (_ERC20 *ERC20CallerSession) Decimals() (uint8, error) { - return _ERC20.Contract.Decimals(&_ERC20.CallOpts) -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_ERC20 *ERC20Caller) Name(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _ERC20.contract.Call(opts, &out, "name") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_ERC20 *ERC20Session) Name() (string, error) { - return _ERC20.Contract.Name(&_ERC20.CallOpts) -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_ERC20 *ERC20CallerSession) Name() (string, error) { - return _ERC20.Contract.Name(&_ERC20.CallOpts) -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_ERC20 *ERC20Caller) Symbol(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _ERC20.contract.Call(opts, &out, "symbol") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_ERC20 *ERC20Session) Symbol() (string, error) { - return _ERC20.Contract.Symbol(&_ERC20.CallOpts) -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_ERC20 *ERC20CallerSession) Symbol() (string, error) { - return _ERC20.Contract.Symbol(&_ERC20.CallOpts) -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_ERC20 *ERC20Caller) TotalSupply(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _ERC20.contract.Call(opts, &out, "totalSupply") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_ERC20 *ERC20Session) TotalSupply() (*big.Int, error) { - return _ERC20.Contract.TotalSupply(&_ERC20.CallOpts) -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_ERC20 *ERC20CallerSession) TotalSupply() (*big.Int, error) { - return _ERC20.Contract.TotalSupply(&_ERC20.CallOpts) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_ERC20 *ERC20Transactor) Approve(opts *bind.TransactOpts, spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.contract.Transact(opts, "approve", spender, amount) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_ERC20 *ERC20Session) Approve(spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.Approve(&_ERC20.TransactOpts, spender, amount) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_ERC20 *ERC20TransactorSession) Approve(spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.Approve(&_ERC20.TransactOpts, spender, amount) -} - -// DecreaseAllowance is a paid mutator transaction binding the contract method 0xa457c2d7. -// -// Solidity: function decreaseAllowance(address spender, uint256 subtractedValue) returns(bool) -func (_ERC20 *ERC20Transactor) DecreaseAllowance(opts *bind.TransactOpts, spender common.Address, subtractedValue *big.Int) (*types.Transaction, error) { - return _ERC20.contract.Transact(opts, "decreaseAllowance", spender, subtractedValue) -} - -// DecreaseAllowance is a paid mutator transaction binding the contract method 0xa457c2d7. -// -// Solidity: function decreaseAllowance(address spender, uint256 subtractedValue) returns(bool) -func (_ERC20 *ERC20Session) DecreaseAllowance(spender common.Address, subtractedValue *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.DecreaseAllowance(&_ERC20.TransactOpts, spender, subtractedValue) -} - -// DecreaseAllowance is a paid mutator transaction binding the contract method 0xa457c2d7. -// -// Solidity: function decreaseAllowance(address spender, uint256 subtractedValue) returns(bool) -func (_ERC20 *ERC20TransactorSession) DecreaseAllowance(spender common.Address, subtractedValue *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.DecreaseAllowance(&_ERC20.TransactOpts, spender, subtractedValue) -} - -// IncreaseAllowance is a paid mutator transaction binding the contract method 0x39509351. -// -// Solidity: function increaseAllowance(address spender, uint256 addedValue) returns(bool) -func (_ERC20 *ERC20Transactor) IncreaseAllowance(opts *bind.TransactOpts, spender common.Address, addedValue *big.Int) (*types.Transaction, error) { - return _ERC20.contract.Transact(opts, "increaseAllowance", spender, addedValue) -} - -// IncreaseAllowance is a paid mutator transaction binding the contract method 0x39509351. -// -// Solidity: function increaseAllowance(address spender, uint256 addedValue) returns(bool) -func (_ERC20 *ERC20Session) IncreaseAllowance(spender common.Address, addedValue *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.IncreaseAllowance(&_ERC20.TransactOpts, spender, addedValue) -} - -// IncreaseAllowance is a paid mutator transaction binding the contract method 0x39509351. -// -// Solidity: function increaseAllowance(address spender, uint256 addedValue) returns(bool) -func (_ERC20 *ERC20TransactorSession) IncreaseAllowance(spender common.Address, addedValue *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.IncreaseAllowance(&_ERC20.TransactOpts, spender, addedValue) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_ERC20 *ERC20Transactor) Transfer(opts *bind.TransactOpts, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.contract.Transact(opts, "transfer", recipient, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_ERC20 *ERC20Session) Transfer(recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.Transfer(&_ERC20.TransactOpts, recipient, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_ERC20 *ERC20TransactorSession) Transfer(recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.Transfer(&_ERC20.TransactOpts, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_ERC20 *ERC20Transactor) TransferFrom(opts *bind.TransactOpts, sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.contract.Transact(opts, "transferFrom", sender, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_ERC20 *ERC20Session) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.TransferFrom(&_ERC20.TransactOpts, sender, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_ERC20 *ERC20TransactorSession) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.TransferFrom(&_ERC20.TransactOpts, sender, recipient, amount) -} - -// ERC20ApprovalIterator is returned from FilterApproval and is used to iterate over the raw logs and unpacked data for Approval events raised by the ERC20 contract. -type ERC20ApprovalIterator struct { - Event *ERC20Approval // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *ERC20ApprovalIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(ERC20Approval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(ERC20Approval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *ERC20ApprovalIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *ERC20ApprovalIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// ERC20Approval represents a Approval event raised by the ERC20 contract. -type ERC20Approval struct { - Owner common.Address - Spender common.Address - Value *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterApproval is a free log retrieval operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_ERC20 *ERC20Filterer) FilterApproval(opts *bind.FilterOpts, owner []common.Address, spender []common.Address) (*ERC20ApprovalIterator, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var spenderRule []interface{} - for _, spenderItem := range spender { - spenderRule = append(spenderRule, spenderItem) - } - - logs, sub, err := _ERC20.contract.FilterLogs(opts, "Approval", ownerRule, spenderRule) - if err != nil { - return nil, err - } - return &ERC20ApprovalIterator{contract: _ERC20.contract, event: "Approval", logs: logs, sub: sub}, nil -} - -// WatchApproval is a free log subscription operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_ERC20 *ERC20Filterer) WatchApproval(opts *bind.WatchOpts, sink chan<- *ERC20Approval, owner []common.Address, spender []common.Address) (event.Subscription, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var spenderRule []interface{} - for _, spenderItem := range spender { - spenderRule = append(spenderRule, spenderItem) - } - - logs, sub, err := _ERC20.contract.WatchLogs(opts, "Approval", ownerRule, spenderRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(ERC20Approval) - if err := _ERC20.contract.UnpackLog(event, "Approval", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseApproval is a log parse operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_ERC20 *ERC20Filterer) ParseApproval(log types.Log) (*ERC20Approval, error) { - event := new(ERC20Approval) - if err := _ERC20.contract.UnpackLog(event, "Approval", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// ERC20TransferIterator is returned from FilterTransfer and is used to iterate over the raw logs and unpacked data for Transfer events raised by the ERC20 contract. -type ERC20TransferIterator struct { - Event *ERC20Transfer // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *ERC20TransferIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(ERC20Transfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(ERC20Transfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *ERC20TransferIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *ERC20TransferIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// ERC20Transfer represents a Transfer event raised by the ERC20 contract. -type ERC20Transfer struct { - From common.Address - To common.Address - Value *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterTransfer is a free log retrieval operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_ERC20 *ERC20Filterer) FilterTransfer(opts *bind.FilterOpts, from []common.Address, to []common.Address) (*ERC20TransferIterator, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - logs, sub, err := _ERC20.contract.FilterLogs(opts, "Transfer", fromRule, toRule) - if err != nil { - return nil, err - } - return &ERC20TransferIterator{contract: _ERC20.contract, event: "Transfer", logs: logs, sub: sub}, nil -} - -// WatchTransfer is a free log subscription operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_ERC20 *ERC20Filterer) WatchTransfer(opts *bind.WatchOpts, sink chan<- *ERC20Transfer, from []common.Address, to []common.Address) (event.Subscription, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - logs, sub, err := _ERC20.contract.WatchLogs(opts, "Transfer", fromRule, toRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(ERC20Transfer) - if err := _ERC20.contract.UnpackLog(event, "Transfer", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseTransfer is a log parse operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_ERC20 *ERC20Filterer) ParseTransfer(log types.Log) (*ERC20Transfer, error) { - event := new(ERC20Transfer) - if err := _ERC20.contract.UnpackLog(event, "Transfer", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// IERC20MetaData contains all meta data concerning the IERC20 contract. -var IERC20MetaData = &bind.MetaData{ - ABI: "[{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]", - Sigs: map[string]string{ - "dd62ed3e": "allowance(address,address)", - "095ea7b3": "approve(address,uint256)", - "70a08231": "balanceOf(address)", - "18160ddd": "totalSupply()", - "a9059cbb": "transfer(address,uint256)", - "23b872dd": "transferFrom(address,address,uint256)", - }, -} - -// IERC20ABI is the input ABI used to generate the binding from. -// Deprecated: Use IERC20MetaData.ABI instead. -var IERC20ABI = IERC20MetaData.ABI - -// Deprecated: Use IERC20MetaData.Sigs instead. -// IERC20FuncSigs maps the 4-byte function signature to its string representation. -var IERC20FuncSigs = IERC20MetaData.Sigs - -// IERC20 is an auto generated Go binding around an Ethereum contract. -type IERC20 struct { - IERC20Caller // Read-only binding to the contract - IERC20Transactor // Write-only binding to the contract - IERC20Filterer // Log filterer for contract events -} - -// IERC20Caller is an auto generated read-only Go binding around an Ethereum contract. -type IERC20Caller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IERC20Transactor is an auto generated write-only Go binding around an Ethereum contract. -type IERC20Transactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IERC20Filterer is an auto generated log filtering Go binding around an Ethereum contract events. -type IERC20Filterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IERC20Session is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type IERC20Session struct { - Contract *IERC20 // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// IERC20CallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type IERC20CallerSession struct { - Contract *IERC20Caller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// IERC20TransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type IERC20TransactorSession struct { - Contract *IERC20Transactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// IERC20Raw is an auto generated low-level Go binding around an Ethereum contract. -type IERC20Raw struct { - Contract *IERC20 // Generic contract binding to access the raw methods on -} - -// IERC20CallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type IERC20CallerRaw struct { - Contract *IERC20Caller // Generic read-only contract binding to access the raw methods on -} - -// IERC20TransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type IERC20TransactorRaw struct { - Contract *IERC20Transactor // Generic write-only contract binding to access the raw methods on -} - -// NewIERC20 creates a new instance of IERC20, bound to a specific deployed contract. -func NewIERC20(address common.Address, backend bind.ContractBackend) (*IERC20, error) { - contract, err := bindIERC20(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &IERC20{IERC20Caller: IERC20Caller{contract: contract}, IERC20Transactor: IERC20Transactor{contract: contract}, IERC20Filterer: IERC20Filterer{contract: contract}}, nil -} - -// NewIERC20Caller creates a new read-only instance of IERC20, bound to a specific deployed contract. -func NewIERC20Caller(address common.Address, caller bind.ContractCaller) (*IERC20Caller, error) { - contract, err := bindIERC20(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &IERC20Caller{contract: contract}, nil -} - -// NewIERC20Transactor creates a new write-only instance of IERC20, bound to a specific deployed contract. -func NewIERC20Transactor(address common.Address, transactor bind.ContractTransactor) (*IERC20Transactor, error) { - contract, err := bindIERC20(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &IERC20Transactor{contract: contract}, nil -} - -// NewIERC20Filterer creates a new log filterer instance of IERC20, bound to a specific deployed contract. -func NewIERC20Filterer(address common.Address, filterer bind.ContractFilterer) (*IERC20Filterer, error) { - contract, err := bindIERC20(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &IERC20Filterer{contract: contract}, nil -} - -// bindIERC20 binds a generic wrapper to an already deployed contract. -func bindIERC20(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(IERC20ABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_IERC20 *IERC20Raw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _IERC20.Contract.IERC20Caller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_IERC20 *IERC20Raw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _IERC20.Contract.IERC20Transactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_IERC20 *IERC20Raw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _IERC20.Contract.IERC20Transactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_IERC20 *IERC20CallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _IERC20.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_IERC20 *IERC20TransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _IERC20.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_IERC20 *IERC20TransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _IERC20.Contract.contract.Transact(opts, method, params...) -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_IERC20 *IERC20Caller) Allowance(opts *bind.CallOpts, owner common.Address, spender common.Address) (*big.Int, error) { - var out []interface{} - err := _IERC20.contract.Call(opts, &out, "allowance", owner, spender) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_IERC20 *IERC20Session) Allowance(owner common.Address, spender common.Address) (*big.Int, error) { - return _IERC20.Contract.Allowance(&_IERC20.CallOpts, owner, spender) -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_IERC20 *IERC20CallerSession) Allowance(owner common.Address, spender common.Address) (*big.Int, error) { - return _IERC20.Contract.Allowance(&_IERC20.CallOpts, owner, spender) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_IERC20 *IERC20Caller) BalanceOf(opts *bind.CallOpts, account common.Address) (*big.Int, error) { - var out []interface{} - err := _IERC20.contract.Call(opts, &out, "balanceOf", account) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_IERC20 *IERC20Session) BalanceOf(account common.Address) (*big.Int, error) { - return _IERC20.Contract.BalanceOf(&_IERC20.CallOpts, account) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_IERC20 *IERC20CallerSession) BalanceOf(account common.Address) (*big.Int, error) { - return _IERC20.Contract.BalanceOf(&_IERC20.CallOpts, account) -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_IERC20 *IERC20Caller) TotalSupply(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _IERC20.contract.Call(opts, &out, "totalSupply") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_IERC20 *IERC20Session) TotalSupply() (*big.Int, error) { - return _IERC20.Contract.TotalSupply(&_IERC20.CallOpts) -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_IERC20 *IERC20CallerSession) TotalSupply() (*big.Int, error) { - return _IERC20.Contract.TotalSupply(&_IERC20.CallOpts) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_IERC20 *IERC20Transactor) Approve(opts *bind.TransactOpts, spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.contract.Transact(opts, "approve", spender, amount) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_IERC20 *IERC20Session) Approve(spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.Contract.Approve(&_IERC20.TransactOpts, spender, amount) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_IERC20 *IERC20TransactorSession) Approve(spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.Contract.Approve(&_IERC20.TransactOpts, spender, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_IERC20 *IERC20Transactor) Transfer(opts *bind.TransactOpts, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.contract.Transact(opts, "transfer", recipient, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_IERC20 *IERC20Session) Transfer(recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.Contract.Transfer(&_IERC20.TransactOpts, recipient, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_IERC20 *IERC20TransactorSession) Transfer(recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.Contract.Transfer(&_IERC20.TransactOpts, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_IERC20 *IERC20Transactor) TransferFrom(opts *bind.TransactOpts, sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.contract.Transact(opts, "transferFrom", sender, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_IERC20 *IERC20Session) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.Contract.TransferFrom(&_IERC20.TransactOpts, sender, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_IERC20 *IERC20TransactorSession) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.Contract.TransferFrom(&_IERC20.TransactOpts, sender, recipient, amount) -} - -// IERC20ApprovalIterator is returned from FilterApproval and is used to iterate over the raw logs and unpacked data for Approval events raised by the IERC20 contract. -type IERC20ApprovalIterator struct { - Event *IERC20Approval // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *IERC20ApprovalIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(IERC20Approval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(IERC20Approval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *IERC20ApprovalIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *IERC20ApprovalIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// IERC20Approval represents a Approval event raised by the IERC20 contract. -type IERC20Approval struct { - Owner common.Address - Spender common.Address - Value *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterApproval is a free log retrieval operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_IERC20 *IERC20Filterer) FilterApproval(opts *bind.FilterOpts, owner []common.Address, spender []common.Address) (*IERC20ApprovalIterator, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var spenderRule []interface{} - for _, spenderItem := range spender { - spenderRule = append(spenderRule, spenderItem) - } - - logs, sub, err := _IERC20.contract.FilterLogs(opts, "Approval", ownerRule, spenderRule) - if err != nil { - return nil, err - } - return &IERC20ApprovalIterator{contract: _IERC20.contract, event: "Approval", logs: logs, sub: sub}, nil -} - -// WatchApproval is a free log subscription operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_IERC20 *IERC20Filterer) WatchApproval(opts *bind.WatchOpts, sink chan<- *IERC20Approval, owner []common.Address, spender []common.Address) (event.Subscription, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var spenderRule []interface{} - for _, spenderItem := range spender { - spenderRule = append(spenderRule, spenderItem) - } - - logs, sub, err := _IERC20.contract.WatchLogs(opts, "Approval", ownerRule, spenderRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(IERC20Approval) - if err := _IERC20.contract.UnpackLog(event, "Approval", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseApproval is a log parse operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_IERC20 *IERC20Filterer) ParseApproval(log types.Log) (*IERC20Approval, error) { - event := new(IERC20Approval) - if err := _IERC20.contract.UnpackLog(event, "Approval", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// IERC20TransferIterator is returned from FilterTransfer and is used to iterate over the raw logs and unpacked data for Transfer events raised by the IERC20 contract. -type IERC20TransferIterator struct { - Event *IERC20Transfer // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *IERC20TransferIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(IERC20Transfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(IERC20Transfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *IERC20TransferIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *IERC20TransferIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// IERC20Transfer represents a Transfer event raised by the IERC20 contract. -type IERC20Transfer struct { - From common.Address - To common.Address - Value *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterTransfer is a free log retrieval operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_IERC20 *IERC20Filterer) FilterTransfer(opts *bind.FilterOpts, from []common.Address, to []common.Address) (*IERC20TransferIterator, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - logs, sub, err := _IERC20.contract.FilterLogs(opts, "Transfer", fromRule, toRule) - if err != nil { - return nil, err - } - return &IERC20TransferIterator{contract: _IERC20.contract, event: "Transfer", logs: logs, sub: sub}, nil -} - -// WatchTransfer is a free log subscription operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_IERC20 *IERC20Filterer) WatchTransfer(opts *bind.WatchOpts, sink chan<- *IERC20Transfer, from []common.Address, to []common.Address) (event.Subscription, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - logs, sub, err := _IERC20.contract.WatchLogs(opts, "Transfer", fromRule, toRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(IERC20Transfer) - if err := _IERC20.contract.UnpackLog(event, "Transfer", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseTransfer is a log parse operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_IERC20 *IERC20Filterer) ParseTransfer(log types.Log) (*IERC20Transfer, error) { - event := new(IERC20Transfer) - if err := _IERC20.contract.UnpackLog(event, "Transfer", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// IERC20MetadataMetaData contains all meta data concerning the IERC20Metadata contract. -var IERC20MetadataMetaData = &bind.MetaData{ - ABI: "[{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"internalType\":\"uint8\",\"name\":\"\",\"type\":\"uint8\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]", - Sigs: map[string]string{ - "dd62ed3e": "allowance(address,address)", - "095ea7b3": "approve(address,uint256)", - "70a08231": "balanceOf(address)", - "313ce567": "decimals()", - "06fdde03": "name()", - "95d89b41": "symbol()", - "18160ddd": "totalSupply()", - "a9059cbb": "transfer(address,uint256)", - "23b872dd": "transferFrom(address,address,uint256)", - }, -} - -// IERC20MetadataABI is the input ABI used to generate the binding from. -// Deprecated: Use IERC20MetadataMetaData.ABI instead. -var IERC20MetadataABI = IERC20MetadataMetaData.ABI - -// Deprecated: Use IERC20MetadataMetaData.Sigs instead. -// IERC20MetadataFuncSigs maps the 4-byte function signature to its string representation. -var IERC20MetadataFuncSigs = IERC20MetadataMetaData.Sigs - -// IERC20Metadata is an auto generated Go binding around an Ethereum contract. -type IERC20Metadata struct { - IERC20MetadataCaller // Read-only binding to the contract - IERC20MetadataTransactor // Write-only binding to the contract - IERC20MetadataFilterer // Log filterer for contract events -} - -// IERC20MetadataCaller is an auto generated read-only Go binding around an Ethereum contract. -type IERC20MetadataCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IERC20MetadataTransactor is an auto generated write-only Go binding around an Ethereum contract. -type IERC20MetadataTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IERC20MetadataFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type IERC20MetadataFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IERC20MetadataSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type IERC20MetadataSession struct { - Contract *IERC20Metadata // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// IERC20MetadataCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type IERC20MetadataCallerSession struct { - Contract *IERC20MetadataCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// IERC20MetadataTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type IERC20MetadataTransactorSession struct { - Contract *IERC20MetadataTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// IERC20MetadataRaw is an auto generated low-level Go binding around an Ethereum contract. -type IERC20MetadataRaw struct { - Contract *IERC20Metadata // Generic contract binding to access the raw methods on -} - -// IERC20MetadataCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type IERC20MetadataCallerRaw struct { - Contract *IERC20MetadataCaller // Generic read-only contract binding to access the raw methods on -} - -// IERC20MetadataTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type IERC20MetadataTransactorRaw struct { - Contract *IERC20MetadataTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewIERC20Metadata creates a new instance of IERC20Metadata, bound to a specific deployed contract. -func NewIERC20Metadata(address common.Address, backend bind.ContractBackend) (*IERC20Metadata, error) { - contract, err := bindIERC20Metadata(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &IERC20Metadata{IERC20MetadataCaller: IERC20MetadataCaller{contract: contract}, IERC20MetadataTransactor: IERC20MetadataTransactor{contract: contract}, IERC20MetadataFilterer: IERC20MetadataFilterer{contract: contract}}, nil -} - -// NewIERC20MetadataCaller creates a new read-only instance of IERC20Metadata, bound to a specific deployed contract. -func NewIERC20MetadataCaller(address common.Address, caller bind.ContractCaller) (*IERC20MetadataCaller, error) { - contract, err := bindIERC20Metadata(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &IERC20MetadataCaller{contract: contract}, nil -} - -// NewIERC20MetadataTransactor creates a new write-only instance of IERC20Metadata, bound to a specific deployed contract. -func NewIERC20MetadataTransactor(address common.Address, transactor bind.ContractTransactor) (*IERC20MetadataTransactor, error) { - contract, err := bindIERC20Metadata(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &IERC20MetadataTransactor{contract: contract}, nil -} - -// NewIERC20MetadataFilterer creates a new log filterer instance of IERC20Metadata, bound to a specific deployed contract. -func NewIERC20MetadataFilterer(address common.Address, filterer bind.ContractFilterer) (*IERC20MetadataFilterer, error) { - contract, err := bindIERC20Metadata(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &IERC20MetadataFilterer{contract: contract}, nil -} - -// bindIERC20Metadata binds a generic wrapper to an already deployed contract. -func bindIERC20Metadata(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(IERC20MetadataABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_IERC20Metadata *IERC20MetadataRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _IERC20Metadata.Contract.IERC20MetadataCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_IERC20Metadata *IERC20MetadataRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _IERC20Metadata.Contract.IERC20MetadataTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_IERC20Metadata *IERC20MetadataRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _IERC20Metadata.Contract.IERC20MetadataTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_IERC20Metadata *IERC20MetadataCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _IERC20Metadata.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_IERC20Metadata *IERC20MetadataTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _IERC20Metadata.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_IERC20Metadata *IERC20MetadataTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _IERC20Metadata.Contract.contract.Transact(opts, method, params...) -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_IERC20Metadata *IERC20MetadataCaller) Allowance(opts *bind.CallOpts, owner common.Address, spender common.Address) (*big.Int, error) { - var out []interface{} - err := _IERC20Metadata.contract.Call(opts, &out, "allowance", owner, spender) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_IERC20Metadata *IERC20MetadataSession) Allowance(owner common.Address, spender common.Address) (*big.Int, error) { - return _IERC20Metadata.Contract.Allowance(&_IERC20Metadata.CallOpts, owner, spender) -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_IERC20Metadata *IERC20MetadataCallerSession) Allowance(owner common.Address, spender common.Address) (*big.Int, error) { - return _IERC20Metadata.Contract.Allowance(&_IERC20Metadata.CallOpts, owner, spender) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_IERC20Metadata *IERC20MetadataCaller) BalanceOf(opts *bind.CallOpts, account common.Address) (*big.Int, error) { - var out []interface{} - err := _IERC20Metadata.contract.Call(opts, &out, "balanceOf", account) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_IERC20Metadata *IERC20MetadataSession) BalanceOf(account common.Address) (*big.Int, error) { - return _IERC20Metadata.Contract.BalanceOf(&_IERC20Metadata.CallOpts, account) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_IERC20Metadata *IERC20MetadataCallerSession) BalanceOf(account common.Address) (*big.Int, error) { - return _IERC20Metadata.Contract.BalanceOf(&_IERC20Metadata.CallOpts, account) -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() view returns(uint8) -func (_IERC20Metadata *IERC20MetadataCaller) Decimals(opts *bind.CallOpts) (uint8, error) { - var out []interface{} - err := _IERC20Metadata.contract.Call(opts, &out, "decimals") - - if err != nil { - return *new(uint8), err - } - - out0 := *abi.ConvertType(out[0], new(uint8)).(*uint8) - - return out0, err - -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() view returns(uint8) -func (_IERC20Metadata *IERC20MetadataSession) Decimals() (uint8, error) { - return _IERC20Metadata.Contract.Decimals(&_IERC20Metadata.CallOpts) -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() view returns(uint8) -func (_IERC20Metadata *IERC20MetadataCallerSession) Decimals() (uint8, error) { - return _IERC20Metadata.Contract.Decimals(&_IERC20Metadata.CallOpts) -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_IERC20Metadata *IERC20MetadataCaller) Name(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _IERC20Metadata.contract.Call(opts, &out, "name") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_IERC20Metadata *IERC20MetadataSession) Name() (string, error) { - return _IERC20Metadata.Contract.Name(&_IERC20Metadata.CallOpts) -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_IERC20Metadata *IERC20MetadataCallerSession) Name() (string, error) { - return _IERC20Metadata.Contract.Name(&_IERC20Metadata.CallOpts) -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_IERC20Metadata *IERC20MetadataCaller) Symbol(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _IERC20Metadata.contract.Call(opts, &out, "symbol") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_IERC20Metadata *IERC20MetadataSession) Symbol() (string, error) { - return _IERC20Metadata.Contract.Symbol(&_IERC20Metadata.CallOpts) -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_IERC20Metadata *IERC20MetadataCallerSession) Symbol() (string, error) { - return _IERC20Metadata.Contract.Symbol(&_IERC20Metadata.CallOpts) -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_IERC20Metadata *IERC20MetadataCaller) TotalSupply(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _IERC20Metadata.contract.Call(opts, &out, "totalSupply") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_IERC20Metadata *IERC20MetadataSession) TotalSupply() (*big.Int, error) { - return _IERC20Metadata.Contract.TotalSupply(&_IERC20Metadata.CallOpts) -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_IERC20Metadata *IERC20MetadataCallerSession) TotalSupply() (*big.Int, error) { - return _IERC20Metadata.Contract.TotalSupply(&_IERC20Metadata.CallOpts) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataTransactor) Approve(opts *bind.TransactOpts, spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.contract.Transact(opts, "approve", spender, amount) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataSession) Approve(spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.Contract.Approve(&_IERC20Metadata.TransactOpts, spender, amount) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataTransactorSession) Approve(spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.Contract.Approve(&_IERC20Metadata.TransactOpts, spender, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataTransactor) Transfer(opts *bind.TransactOpts, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.contract.Transact(opts, "transfer", recipient, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataSession) Transfer(recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.Contract.Transfer(&_IERC20Metadata.TransactOpts, recipient, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataTransactorSession) Transfer(recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.Contract.Transfer(&_IERC20Metadata.TransactOpts, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataTransactor) TransferFrom(opts *bind.TransactOpts, sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.contract.Transact(opts, "transferFrom", sender, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataSession) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.Contract.TransferFrom(&_IERC20Metadata.TransactOpts, sender, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataTransactorSession) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.Contract.TransferFrom(&_IERC20Metadata.TransactOpts, sender, recipient, amount) -} - -// IERC20MetadataApprovalIterator is returned from FilterApproval and is used to iterate over the raw logs and unpacked data for Approval events raised by the IERC20Metadata contract. -type IERC20MetadataApprovalIterator struct { - Event *IERC20MetadataApproval // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *IERC20MetadataApprovalIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(IERC20MetadataApproval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(IERC20MetadataApproval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *IERC20MetadataApprovalIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *IERC20MetadataApprovalIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// IERC20MetadataApproval represents a Approval event raised by the IERC20Metadata contract. -type IERC20MetadataApproval struct { - Owner common.Address - Spender common.Address - Value *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterApproval is a free log retrieval operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_IERC20Metadata *IERC20MetadataFilterer) FilterApproval(opts *bind.FilterOpts, owner []common.Address, spender []common.Address) (*IERC20MetadataApprovalIterator, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var spenderRule []interface{} - for _, spenderItem := range spender { - spenderRule = append(spenderRule, spenderItem) - } - - logs, sub, err := _IERC20Metadata.contract.FilterLogs(opts, "Approval", ownerRule, spenderRule) - if err != nil { - return nil, err - } - return &IERC20MetadataApprovalIterator{contract: _IERC20Metadata.contract, event: "Approval", logs: logs, sub: sub}, nil -} - -// WatchApproval is a free log subscription operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_IERC20Metadata *IERC20MetadataFilterer) WatchApproval(opts *bind.WatchOpts, sink chan<- *IERC20MetadataApproval, owner []common.Address, spender []common.Address) (event.Subscription, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var spenderRule []interface{} - for _, spenderItem := range spender { - spenderRule = append(spenderRule, spenderItem) - } - - logs, sub, err := _IERC20Metadata.contract.WatchLogs(opts, "Approval", ownerRule, spenderRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(IERC20MetadataApproval) - if err := _IERC20Metadata.contract.UnpackLog(event, "Approval", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseApproval is a log parse operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_IERC20Metadata *IERC20MetadataFilterer) ParseApproval(log types.Log) (*IERC20MetadataApproval, error) { - event := new(IERC20MetadataApproval) - if err := _IERC20Metadata.contract.UnpackLog(event, "Approval", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// IERC20MetadataTransferIterator is returned from FilterTransfer and is used to iterate over the raw logs and unpacked data for Transfer events raised by the IERC20Metadata contract. -type IERC20MetadataTransferIterator struct { - Event *IERC20MetadataTransfer // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *IERC20MetadataTransferIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(IERC20MetadataTransfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(IERC20MetadataTransfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *IERC20MetadataTransferIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *IERC20MetadataTransferIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// IERC20MetadataTransfer represents a Transfer event raised by the IERC20Metadata contract. -type IERC20MetadataTransfer struct { - From common.Address - To common.Address - Value *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterTransfer is a free log retrieval operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_IERC20Metadata *IERC20MetadataFilterer) FilterTransfer(opts *bind.FilterOpts, from []common.Address, to []common.Address) (*IERC20MetadataTransferIterator, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - logs, sub, err := _IERC20Metadata.contract.FilterLogs(opts, "Transfer", fromRule, toRule) - if err != nil { - return nil, err - } - return &IERC20MetadataTransferIterator{contract: _IERC20Metadata.contract, event: "Transfer", logs: logs, sub: sub}, nil -} - -// WatchTransfer is a free log subscription operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_IERC20Metadata *IERC20MetadataFilterer) WatchTransfer(opts *bind.WatchOpts, sink chan<- *IERC20MetadataTransfer, from []common.Address, to []common.Address) (event.Subscription, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - logs, sub, err := _IERC20Metadata.contract.WatchLogs(opts, "Transfer", fromRule, toRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(IERC20MetadataTransfer) - if err := _IERC20Metadata.contract.UnpackLog(event, "Transfer", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseTransfer is a log parse operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_IERC20Metadata *IERC20MetadataFilterer) ParseTransfer(log types.Log) (*IERC20MetadataTransfer, error) { - event := new(IERC20MetadataTransfer) - if err := _IERC20Metadata.contract.UnpackLog(event, "Transfer", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} diff --git a/zcnswap/contracts/erc20/Context.sol b/zcnswap/contracts/erc20/Context.sol deleted file mode 100755 index 052c09172..000000000 --- a/zcnswap/contracts/erc20/Context.sol +++ /dev/null @@ -1,24 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.3.2 (utils/Context.sol) - -pragma solidity ^0.8.0; - -/** - * @dev Provides information about the current execution context, including the - * sender of the transaction and its data. While these are generally available - * via msg.sender and msg.data, they should not be accessed in such a direct - * manner, since when dealing with meta-transactions the account sending and - * paying for execution may not be the actual sender (as far as an application - * is concerned). - * - * This contract is only required for intermediate, library-like contracts. - */ -abstract contract Context { - function _msgSender() internal view virtual returns (address) { - return msg.sender; - } - - function _msgData() internal view virtual returns (bytes calldata) { - return msg.data; - } -} \ No newline at end of file diff --git a/zcnswap/contracts/erc20/ERC20.sol b/zcnswap/contracts/erc20/ERC20.sol deleted file mode 100755 index 308941e6f..000000000 --- a/zcnswap/contracts/erc20/ERC20.sol +++ /dev/null @@ -1,356 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.3.2 (token/ERC20/ERC20.sol) - -pragma solidity ^0.8.0; - -import "./IERC20.sol"; -import "./IERC20Metadata.sol"; -import "./Context.sol"; - -/** - * @dev Implementation of the {IERC20} interface. - * - * This implementation is agnostic to the way tokens are created. This means - * that a supply mechanism has to be added in a derived contract using {_mint}. - * For a generic mechanism see {ERC20PresetMinterPauser}. - * - * TIP: For a detailed writeup see our guide - * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How - * to implement supply mechanisms]. - * - * We have followed general OpenZeppelin Contracts guidelines: functions revert - * instead returning `false` on failure. This behavior is nonetheless - * conventional and does not conflict with the expectations of ERC20 - * applications. - * - * Additionally, an {Approval} event is emitted on calls to {transferFrom}. - * This allows applications to reconstruct the allowance for all accounts just - * by listening to said events. Other implementations of the EIP may not emit - * these events, as it isn't required by the specification. - * - * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} - * functions have been added to mitigate the well-known issues around setting - * allowances. See {IERC20-approve}. - */ -contract ERC20 is Context, IERC20, IERC20Metadata { - mapping(address => uint256) private _balances; - - mapping(address => mapping(address => uint256)) private _allowances; - - uint256 private _totalSupply; - - string private _name; - string private _symbol; - - /** - * @dev Sets the values for {name} and {symbol}. - * - * The default value of {decimals} is 18. To select a different value for - * {decimals} you should overload it. - * - * All two of these values are immutable: they can only be set once during - * construction. - */ - constructor(string memory name_, string memory symbol_) { - _name = name_; - _symbol = symbol_; - } - - /** - * @dev Returns the name of the token. - */ - function name() public view virtual override returns (string memory) { - return _name; - } - - /** - * @dev Returns the symbol of the token, usually a shorter version of the - * name. - */ - function symbol() public view virtual override returns (string memory) { - return _symbol; - } - - /** - * @dev Returns the number of decimals used to get its user representation. - * For example, if `decimals` equals `2`, a balance of `505` tokens should - * be displayed to a user as `5.05` (`505 / 10 ** 2`). - * - * Tokens usually opt for a value of 18, imitating the relationship between - * Ether and Wei. This is the value {ERC20} uses, unless this function is - * overridden; - * - * NOTE: This information is only used for _display_ purposes: it in - * no way affects any of the arithmetic of the contract, including - * {IERC20-balanceOf} and {IERC20-transfer}. - */ - function decimals() public view virtual override returns (uint8) { - return 18; - } - - /** - * @dev See {IERC20-totalSupply}. - */ - function totalSupply() public view virtual override returns (uint256) { - return _totalSupply; - } - - /** - * @dev See {IERC20-balanceOf}. - */ - function balanceOf(address account) public view virtual override returns (uint256) { - return _balances[account]; - } - - /** - * @dev See {IERC20-transfer}. - * - * Requirements: - * - * - `recipient` cannot be the zero address. - * - the caller must have a balance of at least `amount`. - */ - function transfer(address recipient, uint256 amount) public virtual override returns (bool) { - _transfer(_msgSender(), recipient, amount); - return true; - } - - /** - * @dev See {IERC20-allowance}. - */ - function allowance(address owner, address spender) public view virtual override returns (uint256) { - return _allowances[owner][spender]; - } - - /** - * @dev See {IERC20-approve}. - * - * Requirements: - * - * - `spender` cannot be the zero address. - */ - function approve(address spender, uint256 amount) public virtual override returns (bool) { - _approve(_msgSender(), spender, amount); - return true; - } - - /** - * @dev See {IERC20-transferFrom}. - * - * Emits an {Approval} event indicating the updated allowance. This is not - * required by the EIP. See the note at the beginning of {ERC20}. - * - * Requirements: - * - * - `sender` and `recipient` cannot be the zero address. - * - `sender` must have a balance of at least `amount`. - * - the caller must have allowance for ``sender``'s tokens of at least - * `amount`. - */ - function transferFrom( - address sender, - address recipient, - uint256 amount - ) public virtual override returns (bool) { - _transfer(sender, recipient, amount); - - uint256 currentAllowance = _allowances[sender][_msgSender()]; - require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); - unchecked { - _approve(sender, _msgSender(), currentAllowance - amount); - } - - return true; - } - - /** - * @dev Atomically increases the allowance granted to `spender` by the caller. - * - * This is an alternative to {approve} that can be used as a mitigation for - * problems described in {IERC20-approve}. - * - * Emits an {Approval} event indicating the updated allowance. - * - * Requirements: - * - * - `spender` cannot be the zero address. - */ - function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { - _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); - return true; - } - - /** - * @dev Atomically decreases the allowance granted to `spender` by the caller. - * - * This is an alternative to {approve} that can be used as a mitigation for - * problems described in {IERC20-approve}. - * - * Emits an {Approval} event indicating the updated allowance. - * - * Requirements: - * - * - `spender` cannot be the zero address. - * - `spender` must have allowance for the caller of at least - * `subtractedValue`. - */ - function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { - uint256 currentAllowance = _allowances[_msgSender()][spender]; - require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); - unchecked { - _approve(_msgSender(), spender, currentAllowance - subtractedValue); - } - - return true; - } - - /** - * @dev Moves `amount` of tokens from `sender` to `recipient`. - * - * This internal function is equivalent to {transfer}, and can be used to - * e.g. implement automatic token fees, slashing mechanisms, etc. - * - * Emits a {Transfer} event. - * - * Requirements: - * - * - `sender` cannot be the zero address. - * - `recipient` cannot be the zero address. - * - `sender` must have a balance of at least `amount`. - */ - function _transfer( - address sender, - address recipient, - uint256 amount - ) internal virtual { - require(sender != address(0), "ERC20: transfer from the zero address"); - require(recipient != address(0), "ERC20: transfer to the zero address"); - - _beforeTokenTransfer(sender, recipient, amount); - - uint256 senderBalance = _balances[sender]; - require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); - unchecked { - _balances[sender] = senderBalance - amount; - } - _balances[recipient] += amount; - - emit Transfer(sender, recipient, amount); - - _afterTokenTransfer(sender, recipient, amount); - } - - /** @dev Creates `amount` tokens and assigns them to `account`, increasing - * the total supply. - * - * Emits a {Transfer} event with `from` set to the zero address. - * - * Requirements: - * - * - `account` cannot be the zero address. - */ - function _mint(address account, uint256 amount) internal virtual { - require(account != address(0), "ERC20: mint to the zero address"); - - _beforeTokenTransfer(address(0), account, amount); - - _totalSupply += amount; - _balances[account] += amount; - emit Transfer(address(0), account, amount); - - _afterTokenTransfer(address(0), account, amount); - } - - /** - * @dev Destroys `amount` tokens from `account`, reducing the - * total supply. - * - * Emits a {Transfer} event with `to` set to the zero address. - * - * Requirements: - * - * - `account` cannot be the zero address. - * - `account` must have at least `amount` tokens. - */ - function _burn(address account, uint256 amount) internal virtual { - require(account != address(0), "ERC20: burn from the zero address"); - - _beforeTokenTransfer(account, address(0), amount); - - uint256 accountBalance = _balances[account]; - require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); - unchecked { - _balances[account] = accountBalance - amount; - } - _totalSupply -= amount; - - emit Transfer(account, address(0), amount); - - _afterTokenTransfer(account, address(0), amount); - } - - /** - * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. - * - * This internal function is equivalent to `approve`, and can be used to - * e.g. set automatic allowances for certain subsystems, etc. - * - * Emits an {Approval} event. - * - * Requirements: - * - * - `owner` cannot be the zero address. - * - `spender` cannot be the zero address. - */ - function _approve( - address owner, - address spender, - uint256 amount - ) internal virtual { - require(owner != address(0), "ERC20: approve from the zero address"); - require(spender != address(0), "ERC20: approve to the zero address"); - - _allowances[owner][spender] = amount; - emit Approval(owner, spender, amount); - } - - /** - * @dev Hook that is called before any transfer of tokens. This includes - * minting and burning. - * - * Calling conditions: - * - * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens - * will be transferred to `to`. - * - when `from` is zero, `amount` tokens will be minted for `to`. - * - when `to` is zero, `amount` of ``from``'s tokens will be burned. - * - `from` and `to` are never both zero. - * - * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. - */ - function _beforeTokenTransfer( - address from, - address to, - uint256 amount - ) internal virtual {} - - /** - * @dev Hook that is called after any transfer of tokens. This includes - * minting and burning. - * - * Calling conditions: - * - * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens - * has been transferred to `to`. - * - when `from` is zero, `amount` tokens have been minted for `to`. - * - when `to` is zero, `amount` of ``from``'s tokens have been burned. - * - `from` and `to` are never both zero. - * - * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. - */ - function _afterTokenTransfer( - address from, - address to, - uint256 amount - ) internal virtual {} -} \ No newline at end of file diff --git a/zcnswap/contracts/erc20/IERC20.sol b/zcnswap/contracts/erc20/IERC20.sol deleted file mode 100755 index 014b5706d..000000000 --- a/zcnswap/contracts/erc20/IERC20.sol +++ /dev/null @@ -1,82 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.3.2 (token/ERC20/IERC20.sol) - -pragma solidity ^0.8.0; - -/** - * @dev Interface of the ERC20 standard as defined in the EIP. - */ -interface IERC20 { - /** - * @dev Returns the amount of tokens in existence. - */ - function totalSupply() external view returns (uint256); - - /** - * @dev Returns the amount of tokens owned by `account`. - */ - function balanceOf(address account) external view returns (uint256); - - /** - * @dev Moves `amount` tokens from the caller's account to `recipient`. - * - * Returns a boolean value indicating whether the operation succeeded. - * - * Emits a {Transfer} event. - */ - function transfer(address recipient, uint256 amount) external returns (bool); - - /** - * @dev Returns the remaining number of tokens that `spender` will be - * allowed to spend on behalf of `owner` through {transferFrom}. This is - * zero by default. - * - * This value changes when {approve} or {transferFrom} are called. - */ - function allowance(address owner, address spender) external view returns (uint256); - - /** - * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. - * - * Returns a boolean value indicating whether the operation succeeded. - * - * IMPORTANT: Beware that changing an allowance with this method brings the risk - * that someone may use both the old and the new allowance by unfortunate - * transaction ordering. One possible solution to mitigate this race - * condition is to first reduce the spender's allowance to 0 and set the - * desired value afterwards: - * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 - * - * Emits an {Approval} event. - */ - function approve(address spender, uint256 amount) external returns (bool); - - /** - * @dev Moves `amount` tokens from `sender` to `recipient` using the - * allowance mechanism. `amount` is then deducted from the caller's - * allowance. - * - * Returns a boolean value indicating whether the operation succeeded. - * - * Emits a {Transfer} event. - */ - function transferFrom( - address sender, - address recipient, - uint256 amount - ) external returns (bool); - - /** - * @dev Emitted when `value` tokens are moved from one account (`from`) to - * another (`to`). - * - * Note that `value` may be zero. - */ - event Transfer(address indexed from, address indexed to, uint256 value); - - /** - * @dev Emitted when the allowance of a `spender` for an `owner` is set by - * a call to {approve}. `value` is the new allowance. - */ - event Approval(address indexed owner, address indexed spender, uint256 value); -} \ No newline at end of file diff --git a/zcnswap/contracts/erc20/IERC20Metadata.sol b/zcnswap/contracts/erc20/IERC20Metadata.sol deleted file mode 100755 index 3f8166f0d..000000000 --- a/zcnswap/contracts/erc20/IERC20Metadata.sol +++ /dev/null @@ -1,28 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.3.2 (token/ERC20/extensions/IERC20Metadata.sol) - -pragma solidity ^0.8.0; - -import "./IERC20.sol"; - -/** - * @dev Interface for the optional metadata functions from the ERC20 standard. - * - * _Available since v4.1._ - */ -interface IERC20Metadata is IERC20 { - /** - * @dev Returns the name of the token. - */ - function name() external view returns (string memory); - - /** - * @dev Returns the symbol of the token. - */ - function symbol() external view returns (string memory); - - /** - * @dev Returns the decimals places of the token. - */ - function decimals() external view returns (uint8); -} \ No newline at end of file diff --git a/zcnswap/handler.go b/zcnswap/handler.go deleted file mode 100644 index df555d80d..000000000 --- a/zcnswap/handler.go +++ /dev/null @@ -1,85 +0,0 @@ -package zcnswap - -import ( - "crypto/ecdsa" - "math/big" - - "github.com/0chain/errors" - "github.com/0chain/gosdk/zcncore" - hdwallet "github.com/0chain/gosdk/zcncore/ethhdwallet" - "github.com/0chain/gosdk/zcnswap/config" - "github.com/0chain/gosdk/zcnswap/swapfactory/bancor" - "github.com/0chain/gosdk/zcnswap/swapfactory/erc20" - "github.com/ethereum/go-ethereum/accounts" - cmn "github.com/ethereum/go-ethereum/common" -) - -type ethAccount struct { - PrivateKey *ecdsa.PrivateKey - SourceAddr *cmn.Address - Account *accounts.Account -} - -func Swap(swapAmount int64, tokenSource string) (string, error) { - client, _ := zcncore.GetEthClient() - - ethAccount, err := getWallet() - if err != nil { - return "", err - } - - targetTokenAddress := config.Configuration.ZcnTokenAddress - sourceTokenAddress := tokenSource - - amount := new(big.Int).SetInt64(swapAmount) - - // checking for available funds - balance, err := erc20.TokenBalance(*ethAccount.SourceAddr, - cmn.HexToAddress(sourceTokenAddress), - client) - if err != nil { - return "", err - } - if balance.Cmp(amount) == -1 { - return "", errors.New("500", "Not enough balance") - } - - bancorService := bancor.NewSwapService(client, ethAccount.PrivateKey) - pair, err := bancorService.EstimateRate(sourceTokenAddress, targetTokenAddress, amount) - if err != nil { - return "", err - } - - signedTx, err := bancorService.SwapWithConversionPath(pair, - ethAccount.SourceAddr.Hex()) - if err != nil { - return "", err - } - return signedTx.Hash().String(), nil -} - -func getWallet() (acc *ethAccount, err error) { - walletHd, err := hdwallet.NewFromMnemonic(config.Configuration.WalletMnemonic) - if err != nil { - return nil, err - } - - path := hdwallet.MustParseDerivationPath("m/44'/60'/0'/0/0") - account, err := walletHd.Derive(path, false) - if err != nil { - return nil, err - } - - privateKey, err := walletHd.PrivateKey(account) - if err != nil { - return nil, err - } - sourceAddrHex, _ := walletHd.AddressHex(account) - address := cmn.HexToAddress(sourceAddrHex) - - return ðAccount{ - PrivateKey: privateKey, - SourceAddr: &address, - Account: &account, - }, err -} diff --git a/zcnswap/swapfactory/bancor/bancor.abi b/zcnswap/swapfactory/bancor/bancor.abi deleted file mode 100755 index 99a7e8386..000000000 --- a/zcnswap/swapfactory/bancor/bancor.abi +++ /dev/null @@ -1 +0,0 @@ -[{"constant":false,"inputs":[{"name":"_onlyOwnerCanUpdateRegistry","type":"bool"}],"name":"restrictRegistryUpdate","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_register","type":"bool"}],"name":"registerEtherToken","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_path","type":"address[]"},{"name":"_amount","type":"uint256"}],"name":"getReturnByPath","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_path","type":"address[]"},{"name":"_amount","type":"uint256"},{"name":"_minReturn","type":"uint256"},{"name":"_beneficiary","type":"address"},{"name":"_affiliateAccount","type":"address"},{"name":"_affiliateFee","type":"uint256"}],"name":"claimAndConvertFor2","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"onlyOwnerCanUpdateRegistry","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"updateRegistry","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_path","type":"address[]"},{"name":"_amount","type":"uint256"},{"name":"_minReturn","type":"uint256"},{"name":"_affiliateAccount","type":"address"},{"name":"_affiliateFee","type":"uint256"}],"name":"convert2","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[],"name":"maxAffiliateFee","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_to","type":"address"},{"name":"_amount","type":"uint256"}],"name":"withdrawTokens","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"prevRegistry","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"acceptOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"registry","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_path","type":"address[]"},{"name":"_amount","type":"uint256"}],"name":"rateByPath","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"etherTokens","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_path","type":"address[]"},{"name":"_bancorX","type":"address"},{"name":"_conversionId","type":"uint256"},{"name":"_minReturn","type":"uint256"},{"name":"_beneficiary","type":"address"}],"name":"completeXConversion","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_path","type":"address[]"},{"name":"_amount","type":"uint256"},{"name":"_minReturn","type":"uint256"},{"name":"_beneficiary","type":"address"},{"name":"_affiliateAccount","type":"address"},{"name":"_affiliateFee","type":"uint256"}],"name":"convertFor2","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"name":"_path","type":"address[]"},{"name":"_amount","type":"uint256"},{"name":"_minReturn","type":"uint256"},{"name":"_beneficiary","type":"address"}],"name":"claimAndConvertFor","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"restoreRegistry","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_path","type":"address[]"},{"name":"_amount","type":"uint256"},{"name":"_minReturn","type":"uint256"},{"name":"_beneficiary","type":"address"},{"name":"_affiliateAccount","type":"address"},{"name":"_affiliateFee","type":"uint256"}],"name":"convertByPath","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"name":"_path","type":"address[]"},{"name":"_amount","type":"uint256"},{"name":"_minReturn","type":"uint256"},{"name":"_targetBlockchain","type":"bytes32"},{"name":"_targetAccount","type":"bytes32"},{"name":"_conversionId","type":"uint256"}],"name":"xConvert","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"name":"_path","type":"address[]"},{"name":"_amount","type":"uint256"},{"name":"_minReturn","type":"uint256"}],"name":"claimAndConvert","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_path","type":"address[]"},{"name":"_amount","type":"uint256"},{"name":"_minReturn","type":"uint256"},{"name":"_beneficiary","type":"address"}],"name":"convertFor","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"name":"_path","type":"address[]"},{"name":"_amount","type":"uint256"},{"name":"_minReturn","type":"uint256"},{"name":"_targetBlockchain","type":"bytes32"},{"name":"_targetAccount","type":"bytes32"},{"name":"_conversionId","type":"uint256"},{"name":"_affiliateAccount","type":"address"},{"name":"_affiliateFee","type":"uint256"}],"name":"xConvert2","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[],"name":"newOwner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_sourceToken","type":"address"},{"name":"_targetToken","type":"address"}],"name":"conversionPath","outputs":[{"name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_path","type":"address[]"},{"name":"_amount","type":"uint256"},{"name":"_minReturn","type":"uint256"},{"name":"_affiliateAccount","type":"address"},{"name":"_affiliateFee","type":"uint256"}],"name":"claimAndConvert2","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_path","type":"address[]"},{"name":"_amount","type":"uint256"},{"name":"_minReturn","type":"uint256"}],"name":"convert","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"name":"_maxAffiliateFee","type":"uint256"}],"name":"setMaxAffiliateFee","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"_registry","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_smartToken","type":"address"},{"indexed":true,"name":"_fromToken","type":"address"},{"indexed":true,"name":"_toToken","type":"address"},{"indexed":false,"name":"_fromAmount","type":"uint256"},{"indexed":false,"name":"_toAmount","type":"uint256"},{"indexed":false,"name":"_trader","type":"address"}],"name":"Conversion","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_prevOwner","type":"address"},{"indexed":true,"name":"_newOwner","type":"address"}],"name":"OwnerUpdate","type":"event"}] \ No newline at end of file diff --git a/zcnswap/swapfactory/bancor/service.go b/zcnswap/swapfactory/bancor/service.go deleted file mode 100755 index 61fd6999c..000000000 --- a/zcnswap/swapfactory/bancor/service.go +++ /dev/null @@ -1,236 +0,0 @@ -package bancor - -import ( - "context" - "crypto/ecdsa" - "math/big" - "time" - - "github.com/0chain/errors" - l "github.com/0chain/gosdk/zboxcore/logger" - contractErc20 "github.com/0chain/gosdk/zcnbridge/ethereum/erc20" - "github.com/0chain/gosdk/zcnswap/config" - "github.com/0chain/gosdk/zcnswap/contracts" - "github.com/0chain/gosdk/zcnswap/swapfactory" - "github.com/0chain/gosdk/zcnswap/swapfactory/erc20" - ethutils "github.com/0chain/gosdk/zcnswap/utils" - cmn "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethclient" - "go.uber.org/zap" -) - -type ISwapService interface { - SwapWithConversionPath(pair *swapfactory.ExchangePair, from string) (*types.Transaction, error) - Approve(spender, fromToken, fromAddress cmn.Address, amountIn *big.Int) error - IncreaseAllowance(spender, fromToken, fromAddress cmn.Address, addedValue *big.Int) error - PackConvert(path *[]cmn.Address, amount, minReturn *big.Int, affiliate cmn.Address) ([]byte, error) - EstimateRate(from, to string, amount *big.Int) (*swapfactory.ExchangePair, error) -} - -type swapService struct { - Client *ethclient.Client - PrivateKey *ecdsa.PrivateKey -} - -// func SwapWithConversionPath(path *[]cmn.Address, from string, amountIn, amountOut *big.Int, privateKey *ecdsa.PrivateKey, client *ethclient.Client) (*types.Transaction, error) { -func (s *swapService) SwapWithConversionPath(pair *swapfactory.ExchangePair, from string) (*types.Transaction, error) { - var affiliateAccount = cmn.HexToAddress("0x0000000000000000000000000000000000000000") - - fromAddress := cmn.HexToAddress(from) - spender := cmn.HexToAddress(config.Configuration.BancorAddress) - fromToken := cmn.HexToAddress(config.Configuration.UsdcTokenAddress) - - bancorModule, err := contracts.NewIBancorNetwork(spender, s.Client) - if err != nil { - return nil, err - } - - balance, err := erc20.TokenBalance(fromAddress, fromToken, s.Client) - if err != nil { - return nil, err - } - - if balance.Cmp(pair.AmountIn) != 1 { - return nil, errors.New("500", "Not enough balance") - } - - tokenInfo, err := erc20.TokenInfo(fromToken, s.Client) - if err != nil { - return nil, err - } - - // allowance - aCheckAllowanceResult, err := erc20.CheckAllowance(fromToken, - spender, - fromAddress, - pair.AmountIn, - tokenInfo.TokenSymbol == "ETH", - s.Client) - if err != nil { - l.Logger.Error("Allowance error", zap.Error(err)) - return nil, err - } - - convertPayload, err := s.PackConvert(pair.ConversionPath, pair.AmountIn, pair.AmountOut, affiliateAccount) - if err != nil { - l.Logger.Error("error in PackConvert", zap.Error(err)) - return nil, err - } - - if !aCheckAllowanceResult.IsSatisfied { - err := s.Approve(spender, fromToken, fromAddress, pair.AmountIn) - if err != nil { - l.Logger.Error("Approve error", zap.Error(err)) - return nil, err - } - } - - value := big.NewInt(0) - opts, err := ethutils.NewSignedTransaction(convertPayload, from, spender.Hex(), value, s.PrivateKey, s.Client) - if err != nil { - l.Logger.Error("Signed transaction errorr", zap.Error(err)) - return nil, err - } - - // ropsten test network deployed old contract, hence using old method - //return bancorModule.ConvertByPath2(opts, *path, amountIn, amountOut, affiliateAccount) - return bancorModule.ConvertByPath(opts, *pair.ConversionPath, pair.AmountIn, pair.AmountOut, affiliateAccount, affiliateAccount, big.NewInt(0)) -} - -func (s *swapService) Approve(spender, fromToken, fromAddress cmn.Address, amountIn *big.Int) error { - l.Logger.Info("Approve called", zap.Any("fromToken", fromToken.Hex())) - - ercModule, err := contracts.NewERC20(fromToken, s.Client) - if err != nil { - return err - } - - approvePayload, err := erc20.PackApprove(spender, amountIn) - if err != nil { - return err - } - - value := big.NewInt(0) - opts, err := ethutils.NewSignedTransaction(approvePayload, fromAddress.Hex(), spender.Hex(), value, s.PrivateKey, s.Client) - if err != nil { - return err - } - - trans, err := ercModule.Approve(opts, spender, amountIn) - if err != nil { - return err - } - - l.Logger.Info("Approve tx hash", zap.Any("hash", trans.Hash().Hex())) - - res, err := ethutils.ConfirmEthereumTransaction(trans.Hash().Hex(), 60, time.Minute, s.Client) - if err != nil { - return err - } - if res == ethutils.STATUS_FAIL { - return errors.New("500", "Unable to confirm transaction") - } - - return nil -} - -func (s *swapService) IncreaseAllowance(spender, fromToken, fromAddress cmn.Address, addedValue *big.Int) error { - l.Logger.Info("IncreaseAllowance called", zap.Any("fromToken", fromToken.Hex())) - - abi, err := contractErc20.ERC20MetaData.GetAbi() - if err != nil { - return err - } - - pack, err := abi.Pack("increaseAllowance", spender, addedValue) - if err != nil { - return err - } - - value := big.NewInt(0) - opts, err := ethutils.NewSignedTransaction(pack, fromAddress.Hex(), spender.Hex(), value, s.PrivateKey, s.Client) - if err != nil { - return err - } - - tokenInstance, err := contractErc20.NewERC20(fromToken, s.Client) - if err != nil { - return err - } - trans, err := tokenInstance.IncreaseAllowance(opts, spender, addedValue) - if err != nil { - return err - } - - l.Logger.Info("Allowance transaction", zap.Any("hash", trans.Hash().Hex())) - - res, err := ethutils.ConfirmEthereumTransaction(trans.Hash().Hex(), 60, time.Minute, s.Client) - if err != nil { - return err - } - if res == ethutils.STATUS_FAIL { - return errors.New("500", "Unable to confirm transaction") - } - - return nil -} - -func (s *swapService) PackConvert(path *[]cmn.Address, amount, minReturn *big.Int, affiliate cmn.Address) ([]byte, error) { - abi, err := contracts.IBancorNetworkMetaData.GetAbi() - if err != nil { - return nil, errors.New("500", "No ABI") - } - - // ropsten test network deployed old contract, hence using old method - //pack, err := abi.Pack("convertByPath2", path, amount, minReturn, affiliate) - pack, err := abi.Pack("convertByPath", path, amount, minReturn, affiliate, affiliate, big.NewInt(0)) - if err != nil { - return nil, errors.New("500", "Unable to pack") - } - - return pack, nil -} - -// EstimateRate get token exchange rate based on from amount -func (s *swapService) EstimateRate(from, to string, amount *big.Int) (*swapfactory.ExchangePair, error) { - fromHex := cmn.HexToAddress(from) - toHex := cmn.HexToAddress(to) - bancorAddr := cmn.HexToAddress(config.Configuration.BancorAddress) - - bancorModule, err := contracts.NewIBancorNetwork(bancorAddr, s.Client) - if err != nil { - return nil, err - } - - convertAddrs, err := bancorModule.ConversionPath(nil, fromHex, toHex) - if err != nil { - return nil, err - } - - result, err := bancorModule.RateByPath(nil, convertAddrs, amount) - if err != nil { - return nil, err - } - - gasPriceWei, err := s.Client.SuggestGasPrice(context.Background()) - if err != nil { - return nil, err - } - - return &swapfactory.ExchangePair{ - ContractName: "Bancor", - AmountIn: amount, - AmountOut: result, - TxFee: gasPriceWei, - ConversionPath: &convertAddrs, - }, nil -} - -// NewSwapService - creating repository -func NewSwapService(client *ethclient.Client, privateKey *ecdsa.PrivateKey) ISwapService { - return &swapService{ - Client: client, - PrivateKey: privateKey, - } -} diff --git a/zcnswap/swapfactory/erc20/allowance.go b/zcnswap/swapfactory/erc20/allowance.go deleted file mode 100755 index b4a5e3e0b..000000000 --- a/zcnswap/swapfactory/erc20/allowance.go +++ /dev/null @@ -1,49 +0,0 @@ -package erc20 - -import ( - "math/big" - - "github.com/0chain/gosdk/zcnswap/contracts" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/ethclient" - - "github.com/ethereum/go-ethereum/common" -) - -func GetAllowance(tokenAddr, spender, userAddr common.Address, client *ethclient.Client) (*big.Int, error) { - erc20Module, err := contracts.NewERC20(tokenAddr, client) - if err != nil { - return nil, err - } - - return erc20Module.Allowance(&bind.CallOpts{}, userAddr, spender) -} - -// func (fromToken, data.Bancor, userAddr, amount) (Allowance, AllowanceSatisfied, AllowanceData, error) -type CheckAllowanceResult struct { - AllowanceAmount *big.Int `json:"allowanceAmount"` - IsSatisfied bool `json:"isSatisfied"` - AllowanceData []byte `json:"allowanceData"` -} - -// CheckAllowance Cannot use this to check ETH -func CheckAllowance(fromToken, spender, userAddr common.Address, amount *big.Int, fromIsETH bool, client *ethclient.Client) (*CheckAllowanceResult, error) { - if fromIsETH { - return &CheckAllowanceResult{ - AllowanceAmount: amount, - IsSatisfied: true, - AllowanceData: []byte(""), - }, nil - } - - fromTokenAllowance, err := GetAllowance(fromToken, spender, userAddr, client) - if err != nil { - return nil, err - } - - return &CheckAllowanceResult{ - AllowanceAmount: amount, - IsSatisfied: fromTokenAllowance.Cmp(amount) >= 0, - //AllowanceData: callData, - }, nil -} diff --git a/zcnswap/swapfactory/erc20/erc20.abi b/zcnswap/swapfactory/erc20/erc20.abi deleted file mode 100755 index 668d6979f..000000000 --- a/zcnswap/swapfactory/erc20/erc20.abi +++ /dev/null @@ -1,222 +0,0 @@ -[ - { - "constant": true, - "inputs": [], - "name": "name", - "outputs": [ - { - "name": "", - "type": "string" - } - ], - "payable": false, - "stateMutability": "view", - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "_spender", - "type": "address" - }, - { - "name": "_value", - "type": "uint256" - } - ], - "name": "approve", - "outputs": [ - { - "name": "", - "type": "bool" - } - ], - "payable": false, - "stateMutability": "nonpayable", - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "totalSupply", - "outputs": [ - { - "name": "", - "type": "uint256" - } - ], - "payable": false, - "stateMutability": "view", - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "_from", - "type": "address" - }, - { - "name": "_to", - "type": "address" - }, - { - "name": "_value", - "type": "uint256" - } - ], - "name": "transferFrom", - "outputs": [ - { - "name": "", - "type": "bool" - } - ], - "payable": false, - "stateMutability": "nonpayable", - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "decimals", - "outputs": [ - { - "name": "", - "type": "uint8" - } - ], - "payable": false, - "stateMutability": "view", - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "_owner", - "type": "address" - } - ], - "name": "balanceOf", - "outputs": [ - { - "name": "balance", - "type": "uint256" - } - ], - "payable": false, - "stateMutability": "view", - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "symbol", - "outputs": [ - { - "name": "", - "type": "string" - } - ], - "payable": false, - "stateMutability": "view", - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "_to", - "type": "address" - }, - { - "name": "_value", - "type": "uint256" - } - ], - "name": "transfer", - "outputs": [ - { - "name": "", - "type": "bool" - } - ], - "payable": false, - "stateMutability": "nonpayable", - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "_owner", - "type": "address" - }, - { - "name": "_spender", - "type": "address" - } - ], - "name": "allowance", - "outputs": [ - { - "name": "", - "type": "uint256" - } - ], - "payable": false, - "stateMutability": "view", - "type": "function" - }, - { - "payable": true, - "stateMutability": "payable", - "type": "fallback" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "owner", - "type": "address" - }, - { - "indexed": true, - "name": "spender", - "type": "address" - }, - { - "indexed": false, - "name": "value", - "type": "uint256" - } - ], - "name": "Approval", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "from", - "type": "address" - }, - { - "indexed": true, - "name": "to", - "type": "address" - }, - { - "indexed": false, - "name": "value", - "type": "uint256" - } - ], - "name": "Transfer", - "type": "event" - } -] \ No newline at end of file diff --git a/zcnswap/swapfactory/erc20/service.go b/zcnswap/swapfactory/erc20/service.go deleted file mode 100755 index 16dfd7986..000000000 --- a/zcnswap/swapfactory/erc20/service.go +++ /dev/null @@ -1,78 +0,0 @@ -package erc20 - -import ( - "math/big" - - "github.com/0chain/gosdk/zcnbridge/ethereum/erc20" - "github.com/0chain/gosdk/zcnswap/contracts" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/ethclient" - - cmn "github.com/0chain/errors" - "github.com/ethereum/go-ethereum/common" -) - -var erc20Info = map[common.Address]Info{} - -type Info struct { - TokenAddr common.Address - TokenName string - TokenSymbol string - Decimals uint8 -} - -// PackApprove - pack approve payload from ABI contract -func PackApprove(spender common.Address, amount *big.Int) ([]byte, error) { - abi, err := erc20.ERC20MetaData.GetAbi() - if err != nil { - return nil, cmn.New("500", "No ABI") - } - - pack, err := abi.Pack("approve", spender, amount) - if err != nil { - return nil, cmn.New("500", "Unable to pack") - } - - return pack, nil -} - -// TokenBalance - return balance by selected token contract -func TokenBalance(userAddr, tokenAddr common.Address, client *ethclient.Client) (*big.Int, error) { - erc20Module, err := contracts.NewERC20(tokenAddr, client) - if err != nil { - return nil, err - } - return erc20Module.BalanceOf(&bind.CallOpts{}, userAddr) -} - -func TokenInfo(tokenAddr common.Address, client *ethclient.Client) (Info, error) { - ret := Info{} - if out, ok := erc20Info[tokenAddr]; ok { - return out, nil - } - - erc20Module, err := contracts.NewERC20(tokenAddr, client) - if err != nil { - return ret, err - } - decimals, err := erc20Module.Decimals(nil) - if err != nil { - return ret, err - } - tokenName, err := erc20Module.Symbol(nil) - if err != nil { - return ret, err - } - tokenSymbol, err := erc20Module.Name(nil) - if err != nil { - return ret, err - } - - ret.TokenAddr = tokenAddr - ret.TokenName = tokenName - ret.TokenSymbol = tokenSymbol - ret.Decimals = decimals - - erc20Info[tokenAddr] = ret - return ret, nil -} diff --git a/zcnswap/swapfactory/models.go b/zcnswap/swapfactory/models.go deleted file mode 100755 index 162620519..000000000 --- a/zcnswap/swapfactory/models.go +++ /dev/null @@ -1,122 +0,0 @@ -package swapfactory - -import ( - "encoding/json" - "math/big" - "strings" - - cmn "github.com/ethereum/go-ethereum/common" - - "github.com/labstack/echo" -) - -type EchoContext struct { - echo.Context -} - -type Token struct { - Name string `json:"name"` - Address string `json:"address"` - Symbol string `json:"symbol"` - Decimals int `json:"decimals"` - LogoURI string `json:"logoURI"` -} - -type Tokens []Token - -func (t Tokens) Len() int { return len(t) } -func (t Tokens) Less(i, j int) bool { - cmp := strings.Compare(t[i].Symbol, t[j].Symbol) - return cmp == -1 -} -func (t Tokens) Swap(i, j int) { t[i], t[j] = t[j], t[i] } - -type Exchange struct { - Name string `json:"name"` - APIAddress string `json:"api_address"` - Decimals int `json:"decimals"` -} - -type ExchangeResult struct { - FromName string `json:"from_name,omitempty"` - ToName string `json:"to_name,omitempty"` - FromAddr string `json:"from_addr,omitempty"` - ToAddr string `json:"to_addr,omitempty"` - ExchangePairs ExchangePairList `json:"exchange_pairs,omitempty"` -} - -type ExchangePair struct { - ContractName string `json:"contract_name,omitempty"` - AmountIn *big.Int `json:"amount_in,omitempty"` - AmountOut *big.Int `json:"amount_out,omitempty"` - ExchangeRatio *big.Int `json:"exchange_ratio,omitempty"` - TxFee *big.Int `json:"tx_fee,omitempty"` - SupportSwap bool `json:"support_swap,omitempty"` - ConversionPath *[]cmn.Address `json:"coversion_path,omitempty"` -} - -func (e *ExchangePair) MarshalJSON() ([]byte, error) { - return json.Marshal(&struct { - ContractName string `json:"contract_name"` - AmountIn string `json:"amount_in"` - AmountOut string `json:"amount_out"` - ExchangeRatio string `json:"exchange_ratio"` - TxFee string `json:"tx_fee"` - SupportSwap bool `json:"support_swap"` - }{ - ContractName: e.ContractName, - AmountIn: e.AmountIn.String(), - AmountOut: e.AmountOut.String(), - ExchangeRatio: e.ExchangeRatio.String(), - TxFee: e.TxFee.String(), - SupportSwap: e.SupportSwap, - }) -} - -type ExchangePairList []ExchangePair - -func (p ExchangePairList) Len() int { return len(p) } -func (p ExchangePairList) Less(i, j int) bool { - - return p[i].AmountOut.Cmp(p[j].AmountOut) == 1 -} -func (p ExchangePairList) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -type PoolToken struct { - Address string `json:"address"` - Name string `json:"name"` - Symbol string `json:"symbol"` - Logo string `json:"logo,omitempty"` - Decimals int `json:"decimals,omitempty"` - DenormWeight string `json:"denormWeight,omitempty"` - Balance string `json:"balance,omitempty"` -} - -type PoolInfo struct { - Address string `json:"address,omitempty"` - Platform string `json:"platform,omitempty"` - Liquidity string `json:"liquidity,omitempty"` - Reserves []string `json:"reserves,omitempty"` - TokenPrices []string `json:"tokenprices,omitempty"` - Volumes []string `json:"volumes,omitempty"` - ReserveUSD string `json:"reserveUSD,omitempty"` - ReserveETH string `json:"reserveETH,omitempty"` - TotalSupply string `json:"totalSupply,omitempty"` - VolumeUSD string `json:"volumeUSD,omitempty"` - Tokens []PoolToken `json:"tokens,omitempty"` - SwapFee string `json:"swapFee,omitempty"` - TotalWeight string `json:"totalWeight,omitempty"` -} - -type SwapTx struct { - Data string `json:"data"` - TxFee string `json:"tx_fee"` - ContractAddr string `json:"contract_addr"` - FromTokenAmount string `json:"from_token_amount"` - ToTokenAmount string `json:"to_token_amount"` - ExchangeRatio string `json:"exchange_ratio"` - FromTokenAddr string `json:"from_token_addr"` - Allowance string `json:"allowance"` - AllowanceSatisfied bool `json:"allowance_satisfied"` - AllowanceData string `json:"allowance_data"` -} diff --git a/zcnswap/utils/ethconvert.go b/zcnswap/utils/ethconvert.go deleted file mode 100755 index 6d72af703..000000000 --- a/zcnswap/utils/ethconvert.go +++ /dev/null @@ -1,56 +0,0 @@ -package utils - -import ( - "fmt" - - "github.com/shopspring/decimal" -) - -// ErrInvalidUnit is returned when the given unit is not supported. -var ErrInvalidUnit = fmt.Errorf("invalid unit") - -func init() { - // set the decimal precision to 18 - decimal.DivisionPrecision = 18 -} - -// Convert converts the given amount from the given unit to the given unit. -func Convert(input decimal.Decimal, inputUnit string, outputUnit string) (decimal.Decimal, error) { - wei, err := ToWei(input, inputUnit) - if err != nil { - return decimal.Zero, err - } - return FromWei(wei, outputUnit) -} - -// ToWei converts the given amount to Wei. -func ToWei(amount decimal.Decimal, unit string) (decimal.Decimal, error) { - if unit == Wei { - return amount.RoundDown(0), nil - } - value, err := getUnitValue(unit) - if err != nil { - return decimal.Zero, err - } - return amount.Mul(value).RoundDown(0), nil -} - -// FromWei converts the given amount from Wei to the given unit. -func FromWei(amount decimal.Decimal, unit string) (decimal.Decimal, error) { - if unit == Wei { - return amount.RoundDown(0), nil - } - value, err := getUnitValue(unit) - if err != nil { - return decimal.Zero, err - } - return amount.Div(value), nil -} - -func getUnitValue(unit string) (decimal.Decimal, error) { - value, ok := units[unit] - if !ok { - return decimal.Zero, ErrInvalidUnit - } - return decimal.NewFromString(value) -} diff --git a/zcnswap/utils/ethutils.go b/zcnswap/utils/ethutils.go deleted file mode 100755 index 7157d844d..000000000 --- a/zcnswap/utils/ethutils.go +++ /dev/null @@ -1,169 +0,0 @@ -package utils - -import ( - "context" - "crypto/ecdsa" - "math/big" - "time" - - "github.com/0chain/errors" - l "github.com/0chain/gosdk/zboxcore/logger" - hdwallet "github.com/0chain/gosdk/zcncore/ethhdwallet" - eth "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - cmn "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethclient" - "github.com/ethereum/go-ethereum/params" - "github.com/tyler-smith/go-bip39" - "go.uber.org/zap" -) - -const ( - STATUS_FAIL = 1 - STATUS_SUCCESS = 0 -) - -// createSignedTransaction creates basic Ethereum transaction. -func createSignedTransaction( - chainID *big.Int, - client *ethclient.Client, - fromAddress common.Address, - privateKey *ecdsa.PrivateKey, - gasLimitUnits uint64, -) (*bind.TransactOpts, error) { - nonce, err := client.PendingNonceAt(context.Background(), fromAddress) - if err != nil { - return nil, err - } - - gasPriceWei, err := client.SuggestGasPrice(context.Background()) - if err != nil { - return nil, err - } - - opts, err := bind.NewKeyedTransactorWithChainID(privateKey, chainID) - if err != nil { - return nil, err - } - - valueWei := new(big.Int).Mul(big.NewInt(0), big.NewInt(params.Wei)) - - opts.Nonce = big.NewInt(int64(nonce)) - opts.Value = valueWei // in wei - opts.GasLimit = gasLimitUnits // in units - opts.GasPrice = gasPriceWei // wei - - return opts, nil -} - -func ConfirmEthereumTransaction(hash string, times int, duration time.Duration, client *ethclient.Client) (int, error) { - var ( - res = 0 - ) - - if hash == "" { - return -1, errors.New("500", "transaction hash should not be empty") - } - - l.Logger.Info("Start transaction check", zap.Any("hash", hash)) - for i := 0; i < times; i++ { - res := CheckEthHashStatus(hash, client) - if res == STATUS_SUCCESS || res == STATUS_FAIL { - break - } - time.Sleep(duration) - } - return res, nil -} - -// CheckEthHashStatus - checking the status of ETH transaction -// possible values 0 (fail) or 1 (success) -func CheckEthHashStatus(hash string, client *ethclient.Client) int { - txHash := cmn.HexToHash(hash) - - tx, err := client.TransactionReceipt(context.Background(), txHash) - if err != nil { - return -1 - } - return int(tx.Status) -} - -func NewSignedTransaction(pack []byte, from, to string, value *big.Int, privateKey *ecdsa.PrivateKey, client *ethclient.Client) (*bind.TransactOpts, error) { - fromAddress := cmn.HexToAddress(from) - toAddress := cmn.HexToAddress(to) - gasLimitUnits, err := client.EstimateGas(context.Background(), eth.CallMsg{ - From: fromAddress, - To: &toAddress, - Data: pack, - }) - if err != nil { - return nil, err - } - - nonce, err := client.PendingNonceAt(context.Background(), fromAddress) - if err != nil { - return nil, err - } - - gasPriceWei, err := client.SuggestGasPrice(context.Background()) - if err != nil { - return nil, err - } - - chainID, err := client.ChainID(context.Background()) - if err != nil { - return nil, err - } - - opts, err := createSignedTransaction(chainID, client, fromAddress, privateKey, gasLimitUnits) - if err != nil { - return nil, err - } - - valueWei := new(big.Int).Mul(value, big.NewInt(params.Wei)) - - opts.Nonce = big.NewInt(int64(nonce)) - opts.Value = valueWei // in wei - opts.GasLimit = gasLimitUnits // in units - opts.GasPrice = gasPriceWei // wei - - return opts, nil -} - -func AddPercents(gasLimitUnits uint64, percents int) *big.Int { - gasLimitBig := big.NewInt(int64(gasLimitUnits)) - factorBig := big.NewInt(int64(percents)) - deltaBig := gasLimitBig.Div(gasLimitBig, factorBig) - - origin := big.NewInt(int64(gasLimitUnits)) - gasLimitBig = origin.Add(origin, deltaBig) - - return gasLimitBig -} - -func CreateHDWallet() (*accounts.Account, string, error) { - entropy, err := bip39.NewEntropy(256) - if err != nil { - return nil, "", err - } - - mnemonic, err := bip39.NewMnemonic(entropy) - if err != nil { - return nil, "", err - } - - walletHd, err := hdwallet.NewFromMnemonic(mnemonic) - if err != nil { - return nil, "", err - } - - path := hdwallet.MustParseDerivationPath("m/44'/60'/0'/0/0") - account, err := walletHd.Derive(path, false) - if err != nil { - return nil, "", err - } - - return &account, mnemonic, err -} diff --git a/zcnswap/utils/ethutils_test.go b/zcnswap/utils/ethutils_test.go deleted file mode 100755 index d2c55b038..000000000 --- a/zcnswap/utils/ethutils_test.go +++ /dev/null @@ -1,16 +0,0 @@ -package utils - -import ( - "math/big" - "testing" - - "github.com/stretchr/testify/require" -) - -func TestEthUtils(t *testing.T) { - t.Run("Correct percentage", func(t *testing.T) { - value := new(big.Int).SetInt64(int64(2100)) - res := AddPercents(value.Uint64(), 10) - require.Equal(t, 2310, int(res.Int64())) - }) -} diff --git a/zcnswap/utils/units.go b/zcnswap/utils/units.go deleted file mode 100755 index d164c8ee5..000000000 --- a/zcnswap/utils/units.go +++ /dev/null @@ -1,29 +0,0 @@ -package utils - -const ( - Wei = "wei" - Kwei = "kwei" - Mwei = "mwei" - Gwei = "gwei" - Szabo = "szabo" - Finney = "finney" - Ether = "ether" - Kether = "kether" - Mether = "mether" - Gether = "gether" - Tether = "tether" -) - -var units = map[string]string{ - Wei: "1", - Kwei: "1000", - Mwei: "1000000", - Gwei: "1000000000", - Szabo: "1000000000000", - Finney: "1000000000000000", - Ether: "1000000000000000000", - Kether: "1000000000000000000000", - Mether: "1000000000000000000000000", - Gether: "1000000000000000000000000000", - Tether: "1000000000000000000000000000000", -} diff --git a/znft/example/go.sum b/znft/example/go.sum index bd59e42b3..6bdb94e8b 100644 --- a/znft/example/go.sum +++ b/znft/example/go.sum @@ -162,8 +162,6 @@ golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= -golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba h1:O8mE0/t419eoIwhTFpKVkHiTs/Igowgfkj25AcZrtiE= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -173,16 +171,12 @@ google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQ google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= -gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce h1:+JknDZhAj8YMt7GC73Ei8pv4MzjDUNPHgQWJdtMAaDU= gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce/go.mod h1:5AcXVHNjg+BDxry382+8OKon8SEWiKktQR07RKPsv1c= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= 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= From e99291168a4f5024943bf4d171ec7eae3221a09c Mon Sep 17 00:00:00 2001 From: Lz Date: Fri, 27 Oct 2023 11:40:08 +0800 Subject: [PATCH 071/134] Feat/exposed cli methods in winsdk (#1248) * feat(winsdk): added CreateWallet * feat(winsdk): added RecoverWallet * feat(winsdk): added logging in CreateWallet and RecoverWallet * feat(winsdk): split InitSDK into InitZCNSDK and InitWallets * feat(winsdk): fixed zboxApiClient initialization issue * feat(winsdk): renamed init sdks * feat(winsdk): fixed init zboxApiClient issue * fix(winsdk): fixed RecoverWallet naming * fix(winsdk): fixed file name issue in GetUploadStatus for transcode feature * feat(winsdk): added GetFileContentType in winsdk * feat(winsdk): added ListAllocations * feat(winsdk): added CreateFreeAllocation * feat(winsdk): added allocation methods * fix(winsdk): added logs * feat(zboxapi): added GetFreeStorage * feat(zboxapi): also send X-App-ID-Token in header * fix(winsdk): skip TestGetFreeStorage * fix(winsdk): added getAllocationWith * fix(zboxapi): used local signHash instead of sys.SignFunc * fix(zboxapi): fixed token issue in GetFreeStorage * fix(list): exported ThumbnailHash and ThumbnailSize in ListResult * fix(0box): fixed GetFreeStorage/CreateFreeAllocation * fix(winsdk): renamed jwtToken with token in CreateFreeAllocation * fix(winsdk): renamed jwtToken with token in CreateFreeAllocation * feat(winsdk): added GetFreeMarker * feat(winsdk): added AddSharedInfo/DeleteSharedInfo/GetSharedToMe/GetSharedByMe * feat(winsdk): added CreateAuthTicket/DeleteAuthTicket * feat(winsdk): fixed GetSharedToMe/GetSharedByMe * feat(winsdk): fixed GetSharedToMe/GetSharedByMe * feat(winsdk): exported CreateAuthTicket/DeleteAuthTicket/CreateSharedInfo/DeleteSharedInfo/GetSharedByMe/GetSharedByPublic/GetSharedToMe --- core/version/version.go | 4 +- winsdk/allocation.go | 83 +++++++ winsdk/browser.go | 138 ++++++++++++ winsdk/cache.go | 22 +- winsdk/helper.go | 15 +- winsdk/sdk.go | 99 ++++++-- winsdk/status.go | 1 + winsdk/storage.go | 124 +++++++++-- winsdk/wallet.go | 75 +++++++ winsdk/zboxapi.go | 153 ++++++++++++- zboxapi/response.go | 84 +++++++ zboxapi/sdk.go | 223 ++++++++++++++++++- zboxapi/sdk_test.go | 163 +++++++++++++- zboxcore/fileref/fileref.go | 2 + zboxcore/sdk/chunked_upload_web_streaming.go | 6 +- zboxcore/sdk/listworker.go | 42 ++-- 16 files changed, 1160 insertions(+), 74 deletions(-) create mode 100644 winsdk/allocation.go create mode 100644 winsdk/browser.go create mode 100644 winsdk/wallet.go diff --git a/core/version/version.go b/core/version/version.go index df2e0f3e8..4248cbdc4 100644 --- a/core/version/version.go +++ b/core/version/version.go @@ -1,4 +1,6 @@ + //====== THIS IS AUTOGENERATED FILE. DO NOT MODIFY ======== package version -const VERSIONSTR = "v1.10.0-70-g7f7e89b4" +const VERSIONSTR = "v1.10.0-120-ga72a4ee1" + diff --git a/winsdk/allocation.go b/winsdk/allocation.go new file mode 100644 index 000000000..0f21029eb --- /dev/null +++ b/winsdk/allocation.go @@ -0,0 +1,83 @@ +package main + +/* +#include +*/ +import ( + "C" +) +import ( + "encoding/json" + + "github.com/0chain/gosdk/zboxapi" + "github.com/0chain/gosdk/zboxcore/sdk" + "github.com/0chain/gosdk/zcncore" +) + +// GetAllocation get allocation info +// ## Inputs +// - allocationID +// +// ## Output +// +// { +// "error":"", +// "result":"{}", +// } +// +//export GetAllocation +func GetAllocation(allocationID *C.char) *C.char { + allocID := C.GoString(allocationID) + return WithJSON(getAllocation(allocID)) +} + +// ListAllocations get allocation list +// ## Output +// +// { +// "error":"", +// "result":"[{},{}]", +// } +// +//export ListAllocations +func ListAllocations() *C.char { + items, err := sdk.GetAllocations() + if err != nil { + log.Error("win: ", err) + return WithJSON("", err) + } + + return WithJSON(items, nil) +} + +// CreateFreeAllocation create a free allocation +// ## Inputs +// - freeMarker +// return +// { +// "error":"", +// "result":"id", +// } +// +//export CreateFreeAllocation +func CreateFreeAllocation(freemarker *C.char) *C.char { + + marker := &zboxapi.FreeMarker{} + js := C.GoString(freemarker) + err := json.Unmarshal([]byte(js), marker) + if err != nil { + log.Error("win: ", err) + return WithJSON("", err) + } + + lock := zcncore.ConvertToValue(marker.FreeTokens) + + allocationID, _, err := sdk.CreateFreeAllocation(js, lock) + + if err != nil { + log.Error("win: ", err, "lock: ", lock, " marker:", js) + return WithJSON("", err) + } + + return WithJSON(allocationID, nil) +} diff --git a/winsdk/browser.go b/winsdk/browser.go new file mode 100644 index 000000000..0822210f5 --- /dev/null +++ b/winsdk/browser.go @@ -0,0 +1,138 @@ +package main + +/* +#include +*/ +import ( + "C" +) + +import ( + "errors" + "strings" + + "github.com/0chain/gosdk/zboxcore/sdk" +) + +type RemoteFile struct { + sdk.FileInfo + Name string `json:"name"` + Path string `json:"path"` +} + +// ListAll - list all files from blobbers +// ## Inputs +// - allocationID +// +// ## Outputs +// +// { +// "error":"", +// "result":[{},{}]", +// } +// +//export ListAll +func ListAll(allocationID *C.char) *C.char { + alloc, err := getAllocation(C.GoString(allocationID)) + if err != nil { + log.Error("win: ", err) + return WithJSON("", err) + } + + ref, err := alloc.GetRemoteFileMap(nil, "/") + if err != nil { + log.Error("win: ", err) + return WithJSON("", err) + } + + files := make([]RemoteFile, 0) + for path, data := range ref { + paths := strings.SplitAfter(path, "/") + var f = RemoteFile{ + Name: paths[len(paths)-1], + Path: path, + FileInfo: data, + } + files = append(files, f) + } + + return WithJSON(files, nil) +} + +// List - list files from blobbers +// ## Inputs +// - allocationID +// - remotePath +// +// - authTicket +// - lookupHash +// +// ## Outputs +// +// { +// "error":"", +// "result":[{},{}]", +// } +// +//export List +func List(allocationID, remotePath, authTicket, lookupHash *C.char) *C.char { + + allocID := C.GoString(allocationID) + remotepath := C.GoString(remotePath) + authticket := C.GoString(authTicket) + lookuphash := C.GoString(lookupHash) + + if len(remotepath) == 0 && len(authticket) == 0 { + return WithJSON("[]", errors.New("Error: remotepath / authticket flag is missing")) + } + + if len(remotepath) > 0 { + if len(allocID) == 0 { + return WithJSON("[]", errors.New("Error: allocationID is missing")) + } + + allocationObj, err := getAllocation(allocID) + if err != nil { + log.Error("win: ", err) + return WithJSON("[]", err) + } + + ref, err := allocationObj.ListDir(remotepath) + if err != nil { + if err != nil { + log.Error("win: ", err) + return WithJSON("[]", err) + } + } + + return WithJSON(ref.Children, nil) + } + if len(authticket) > 0 { + + if len(lookuphash) == 0 { + return WithJSON("[]", errors.New("Error: lookuphash flag is missing")) + } + + allocationObj, err := getAllocationWith(authticket) + if err != nil { + log.Error("win: ", err) + return WithJSON("[]", err) + } + + at := sdk.InitAuthTicket(authticket) + lookuphash, err = at.GetLookupHash() + if err != nil { + log.Error("win: ", err) + return WithJSON("[]", err) + } + + ref, err := allocationObj.ListDirFromAuthTicket(authticket, lookuphash) + if err != nil { + log.Error("win: ", err) + return WithJSON("[]", err) + } + + return WithJSON(ref.Children, nil) + } + return WithJSON("[]", nil) +} diff --git a/winsdk/cache.go b/winsdk/cache.go index 493868e98..70d490c4b 100644 --- a/winsdk/cache.go +++ b/winsdk/cache.go @@ -1,8 +1,12 @@ package main import ( + "encoding/base64" + "encoding/json" + "errors" "time" + "github.com/0chain/gosdk/zboxcore/marker" "github.com/0chain/gosdk/zboxcore/sdk" lru "github.com/hashicorp/golang-lru/v2" ) @@ -40,7 +44,7 @@ func getAllocation(allocationID string) (*sdk.Allocation, error) { it = &cachedAllocation{ Allocation: a, - CacheExpiresAt: time.Now().Add(5 * time.Minute), + CacheExpiresAt: time.Now().Add(30 * time.Minute), } cachedAllocations.Add(allocationID, it) @@ -48,6 +52,20 @@ func getAllocation(allocationID string) (*sdk.Allocation, error) { return it.Allocation, nil } +func getAllocationWith(authTicket string) (*sdk.Allocation, error) { + + sEnc, err := base64.StdEncoding.DecodeString(authTicket) + if err != nil { + return nil, errors.New("Error decoding the auth ticket." + err.Error()) + } + at := &marker.AuthTicket{} + err = json.Unmarshal(sEnc, at) + if err != nil { + return nil, errors.New("Error unmarshaling the auth ticket." + err.Error()) + } + return getAllocation(at.AllocationID) +} + func getFileMeta(allocationID, remotePath string) (*sdk.ConsolidatedFileMeta, error) { var it *cachedFileMeta @@ -71,7 +89,7 @@ func getFileMeta(allocationID, remotePath string) (*sdk.ConsolidatedFileMeta, er it = &cachedFileMeta{ FileMeta: f, - CacheExpiresAt: time.Now().Add(5 * time.Minute), + CacheExpiresAt: time.Now().Add(30 * time.Minute), } cachedFileMetas.Add(allocationID, it) diff --git a/winsdk/helper.go b/winsdk/helper.go index 1dbae6aa2..09b05fdfd 100644 --- a/winsdk/helper.go +++ b/winsdk/helper.go @@ -9,16 +9,25 @@ import ( import ( "encoding/json" "os" + "path/filepath" "github.com/0chain/gosdk/core/encryption" "github.com/0chain/gosdk/zboxcore/marker" "github.com/0chain/gosdk/zboxcore/sdk" ) -func getHomeDir() string { - dir, _ := os.UserHomeDir() +func getZcnWorkDir() (string, error) { + d, err := os.UserHomeDir() + if err != nil { + return "", err + } + + z := filepath.Join(d, ".zcn") + + // create ~/.zcn folder if it doesn't exists + os.MkdirAll(z, 0766) //nolint: errcheck - return dir + return z, nil } type JsonResult struct { diff --git a/winsdk/sdk.go b/winsdk/sdk.go index 71f5e1153..3a55576aa 100644 --- a/winsdk/sdk.go +++ b/winsdk/sdk.go @@ -52,27 +52,16 @@ func SetLogFile(file *C.char) *C.char { zboxutil.GetLogger().SetLevel(logger.DEBUG) zboxutil.GetLogger().SetLogFile(f, true) + zboxapi.GetLogger().SetLevel(logger.DEBUG) + zboxapi.GetLogger().SetLogFile(f, true) + log.SetLogFile(f, true) log.SetLevel(logger.DEBUG) return WithJSON(true, nil) } -// InitSDK - init zbox/zcn sdk from config -// - clientJson -// { -// "client_id":"8f6ce6457fc04cfb4eb67b5ce3162fe2b85f66ef81db9d1a9eaa4ffe1d2359e0", -// "client_key":"c8c88854822a1039c5a74bdb8c025081a64b17f52edd463fbecb9d4a42d15608f93b5434e926d67a828b88e63293b6aedbaf0042c7020d0a96d2e2f17d3779a4", -// "keys":[ -// { -// "public_key":"c8c88854822a1039c5a74bdb8c025081a64b17f52edd463fbecb9d4a42d15608f93b5434e926d67a828b88e63293b6aedbaf0042c7020d0a96d2e2f17d3779a4", -// "private_key":"72f480d4b1e7fb76e04327b7c2348a99a64f0ff2c5ebc3334a002aa2e66e8506" -// }], -// "mnemonics":"abandon mercy into make powder fashion butter ignore blade vanish plastic shock learn nephew matrix indoor surge document motor group barely offer pottery antenna", -// "version":"1.0", -// "date_created":"1668667145", -// "nonce":0 -// } +// InitSDKs - init zcncore sdk and zboxapi client from config // - configJson // { // "block_worker": "https://dev.0chain.net/dns", @@ -90,13 +79,12 @@ func SetLogFile(file *C.char) *C.char { // "sharder_consensous": 2, // } // -//export InitSDK -func InitSDK(configJson *C.char, clientJson *C.char) *C.char { +//export InitSDKs +func InitSDKs(configJson *C.char) *C.char { - l.Logger.Info("Start InitStorageSDK") + l.Logger.Info("Start InitSDKs") configJs := C.GoString(configJson) - clientJs := C.GoString(clientJson) configObj := &conf.Config{} @@ -120,7 +108,7 @@ func InitSDK(configJson *C.char, clientJson *C.char) *C.char { return nil }) if err != nil { - l.Logger.Error(err, configJs, clientJs) + l.Logger.Error(err, configJs) return WithJSON(false, err) } @@ -130,15 +118,52 @@ func InitSDK(configJson *C.char, clientJson *C.char) *C.char { l.Logger.Info(configObj.SignatureScheme) l.Logger.Info(configObj.PreferredBlobbers) + if zboxApiClient == nil { + zboxApiClient = zboxapi.NewClient() + } + + zboxApiClient.SetRequest(configObj.ZboxHost, configObj.ZboxAppType) + l.Logger.Info("Init ZBoxAPI Client success") + + return WithJSON(true, nil) +} + +// InitWallet - init wallet for storage sdk and zboxapi client +// - clientJson +// { +// "client_id":"8f6ce6457fc04cfb4eb67b5ce3162fe2b85f66ef81db9d1a9eaa4ffe1d2359e0", +// "client_key":"c8c88854822a1039c5a74bdb8c025081a64b17f52edd463fbecb9d4a42d15608f93b5434e926d67a828b88e63293b6aedbaf0042c7020d0a96d2e2f17d3779a4", +// "keys":[ +// { +// "public_key":"c8c88854822a1039c5a74bdb8c025081a64b17f52edd463fbecb9d4a42d15608f93b5434e926d67a828b88e63293b6aedbaf0042c7020d0a96d2e2f17d3779a4", +// "private_key":"72f480d4b1e7fb76e04327b7c2348a99a64f0ff2c5ebc3334a002aa2e66e8506" +// }], +// "mnemonics":"abandon mercy into make powder fashion butter ignore blade vanish plastic shock learn nephew matrix indoor surge document motor group barely offer pottery antenna", +// "version":"1.0", +// "date_created":"1668667145", +// "nonce":0 +// } +// +//export InitWallet +func InitWallet(clientJson *C.char) *C.char { + + l.Logger.Info("Start InitStorageSDK") + + clientJs := C.GoString(clientJson) + + configObj, err := conf.GetClientConfig() + if err != nil { + l.Logger.Error(err) + return WithJSON(false, err) + } + err = sdk.InitStorageSDK(clientJs, configObj.BlockWorker, configObj.ChainID, configObj.SignatureScheme, configObj.PreferredBlobbers, 0) if err != nil { - l.Logger.Error(err, configJs, clientJs) + l.Logger.Error(err, clientJs) return WithJSON(false, err) } l.Logger.Info("InitStorageSDK success") - zboxApiClient = zboxapi.NewClient() - zboxApiClient.SetRequest(configObj.ZboxHost, configObj.ZboxAppType) c := client.GetClient() if c != nil { zboxApiClient.SetWallet(client.GetClientID(), client.GetClientPrivateKey(), client.GetClientPublicKey()) @@ -147,7 +172,7 @@ func InitSDK(configJson *C.char, clientJson *C.char) *C.char { l.Logger.Info("InitZboxApiClient skipped") } - l.Logger.Info("Init successful") + l.Logger.Info("InitSDKs successful") return WithJSON(true, nil) } @@ -280,3 +305,29 @@ func SetFFmpeg(fullFileName *C.char) *C.char { sdk.CmdFFmpeg = C.GoString(fullFileName) return WithJSON(true, nil) } + +// GetFileContentType get content/MIME type of file +// ## Inputs: +// - fullFileName +// return +// { +// "error":"", +// "result":true, +// } +// +//export GetFileContentType +func GetFileContentType(file *C.char) *C.char { + f, err := os.Open(C.GoString(file)) + if err != nil { + log.Error("win: ", err) + return WithJSON("", err) + } + defer f.Close() + + mime, err := zboxutil.GetFileContentType(f) + if err != nil { + return WithJSON("", err) + } + + return WithJSON(mime, nil) +} diff --git a/winsdk/status.go b/winsdk/status.go index 836608ed4..265f02ee3 100644 --- a/winsdk/status.go +++ b/winsdk/status.go @@ -9,6 +9,7 @@ import ( var ( statusUpload, _ = lru.New[string, *Status](1000) statusDownload, _ = lru.New[string, *Status](1000) + transcodeFiles, _ = lru.New[string, string](1000) ) type Status struct { diff --git a/winsdk/storage.go b/winsdk/storage.go index fd9a411d3..f8bbc55f3 100644 --- a/winsdk/storage.go +++ b/winsdk/storage.go @@ -12,7 +12,9 @@ import ( "errors" "fmt" "os" + "time" + "github.com/0chain/gosdk/core/common" "github.com/0chain/gosdk/zboxcore/sdk" ) @@ -57,20 +59,6 @@ func GetFileStats(allocationID, remotePath *C.char) *C.char { return WithJSON(result, nil) } -// GetAllocation get allocation info -// -// return -// { -// "error":"", -// "result":"{}", -// } -// -//export GetAllocation -func GetAllocation(allocationID *C.char) *C.char { - allocID := C.GoString(allocationID) - return WithJSON(getAllocation(allocID)) -} - // Delete delete path // // return @@ -229,7 +217,17 @@ func BulkUpload(allocationID, files *C.char) *C.char { isUpdates[idx] = option.IsUpdate isWebstreaming[idx] = option.IsWebstreaming encrypts[idx] = option.Encrypt - statusUpload.Add(getLookupHash(allocID, option.RemotePath+option.Name), &Status{}) + if option.IsWebstreaming { + originalLookupHash := getLookupHash(allocID, option.RemotePath+option.Name) + _, transcodeRemotePath := sdk.GetTranscodeFile(option.RemotePath + option.Name) + transcodeLookupHash := getLookupHash(allocID, transcodeRemotePath) + transcodeFiles.Add(originalLookupHash, transcodeLookupHash) + statusUpload.Add(transcodeLookupHash, &Status{}) + + } else { + statusUpload.Add(getLookupHash(allocID, option.RemotePath+option.Name), &Status{}) + } + } a, err := getAllocation(allocID) @@ -257,8 +255,15 @@ func BulkUpload(allocationID, files *C.char) *C.char { // //export GetUploadStatus func GetUploadStatus(lookupHash *C.char) *C.char { + h := C.GoString(lookupHash) + + h2, ok := transcodeFiles.Get(h) + + if ok { + h = h2 + } - s, ok := statusUpload.Get(C.GoString(lookupHash)) + s, ok := statusUpload.Get(h) if !ok { s = &Status{} @@ -553,3 +558,90 @@ func GetDownloadStatus(key *C.char, isThumbnail bool) *C.char { return WithJSON(s, nil) } + +// CreateAuthTicket - create AuthTicket for sharing +// ## Inputs +// - allocationID +// - remotePath +// - refereeClientID +// - refereePublicEncryptionKey +// - availableAfter +// - expirationSeconds +// +// ## Outputs +// +// { +// "error":"", +// "result":"{}", +// } +// +//export CreateAuthTicket +func CreateAuthTicket(allocationID, remotePath, refereeClientID, refereePublicEncryptionKey, availableAfter *C.char, expirationSeconds int64) *C.char { + alloc, err := getAllocation(C.GoString(allocationID)) + if err != nil { + log.Error("win: ", err) + return WithJSON(nil, err) + } + + rPath := C.GoString(remotePath) + + fileMeta, err := alloc.GetFileMeta(rPath) + if err != nil { + log.Error("win: ", err) + return WithJSON(nil, err) + } + + af := time.Now() + availableAfterString := C.GoString(availableAfter) + + if len(availableAfterString) > 0 { + aa, err := common.ParseTime(af, availableAfterString) + if err != nil { + log.Error("win: ", err) + return WithJSON(nil, err) + } + af = *aa + } + + at, err := alloc.GetAuthTicket(rPath, fileMeta.Name, fileMeta.Type, C.GoString(refereeClientID), C.GoString(refereePublicEncryptionKey), expirationSeconds, &af) + if err != nil { + log.Error("win: ", err) + return WithJSON(nil, err) + } + + return WithJSON(at, nil) + +} + +// DeleteAuthTicket - delete AuthTicket +// ## Inputs +// - allocationID +// - remotePath +// - refereeClientID +// +// ## Outputs +// +// { +// "error":"", +// "result":"true", +// } +// +//export DeleteAuthTicket +func DeleteAuthTicket(allocationID, remotePath, refereeClientID *C.char) *C.char { + alloc, err := getAllocation(C.GoString(allocationID)) + if err != nil { + log.Error("win: ", err) + return WithJSON(false, err) + } + + rPath := C.GoString(remotePath) + + err = alloc.RevokeShare(rPath, C.GoString(refereeClientID)) + if err != nil { + log.Error("win: ", err) + return WithJSON(false, err) + } + + return WithJSON(true, nil) + +} diff --git a/winsdk/wallet.go b/winsdk/wallet.go new file mode 100644 index 000000000..e9106ef09 --- /dev/null +++ b/winsdk/wallet.go @@ -0,0 +1,75 @@ +package main + +/* +#include +*/ +import ( + "C" +) + +import ( + "os" + "path/filepath" + + "github.com/0chain/gosdk/zcncore" +) + +// CreateWallet - create a new wallet, and save it to ~/.zcn/wallet.json +// ## Outputs +// +// { +// "error":"", +// "result":\"{}\"", +// } +// +//export CreateWallet +func CreateWallet() *C.char { + w, err := zcncore.CreateWalletOffline() + if err != nil { + log.Error("win: ", err) + return WithJSON("", err) + } + + d, err := getZcnWorkDir() + if err != nil { + log.Error("win: ", err) + return WithJSON("", err) + } + + if err = os.WriteFile(filepath.Join(d, "wallet.json"), []byte(w), 0644); err != nil { + log.Error("win: ", err) + return WithJSON("", err) + } + + return WithJSON(w, nil) +} + +// RecoverWallet - recover the wallet, and save it to ~/.zcn/wallet.json +// ## Outputs +// +// { +// "error":"", +// "result":\"{}\"", +// } +// +//export RecoverWallet +func RecoverWallet(mnemonic *C.char) *C.char { + w, err := zcncore.RecoverOfflineWallet(C.GoString(mnemonic)) + if err != nil { + log.Error("win: ", err) + return WithJSON("", err) + } + + d, err := getZcnWorkDir() + if err != nil { + log.Error("win: ", err) + return WithJSON("", err) + } + + if err = os.WriteFile(filepath.Join(d, "wallet.json"), []byte(w), 0644); err != nil { + log.Error("win: ", err) + return WithJSON("", err) + } + + return WithJSON(w, nil) +} diff --git a/winsdk/zboxapi.go b/winsdk/zboxapi.go index e7ac10b03..d41c8d874 100644 --- a/winsdk/zboxapi.go +++ b/winsdk/zboxapi.go @@ -10,6 +10,7 @@ import ( import ( "context" + "encoding/json" "errors" "github.com/0chain/gosdk/core/logger" @@ -28,8 +29,10 @@ var ( // //export InitZBox func InitZBox(zboxHost, zboxAppType *C.char) { + if zboxApiClient == nil { + zboxApiClient = zboxapi.NewClient() + } - zboxApiClient = zboxapi.NewClient() zboxApiClient.SetRequest(C.GoString(zboxHost), C.GoString(zboxAppType)) c := client.GetClient() @@ -129,3 +132,151 @@ func RefreshJwtToken(phoneNumber, token *C.char) *C.char { } return WithJSON(zboxApiClient.RefreshJwtToken(context.TODO(), C.GoString(phoneNumber), C.GoString(token))) } + +// GetFreeMarker create a free storage marker +// ## Inputs +// - phoneNumber +// - token +// return +// { +// "error":"", +// "result":"{}", +// } +// +//export GetFreeMarker +func GetFreeMarker(phoneNumber, token *C.char) *C.char { + marker, err := zboxApiClient.GetFreeStorage(context.TODO(), C.GoString(phoneNumber), C.GoString(token)) + if err != nil { + log.Error("win: ", err) + return WithJSON("", err) + } + + return WithJSON(marker, nil) +} + +// CreateSharedInfo create a shareInfo on 0box db +// ## Inputs +// - phoneNumber +// - token +// - sharedInfo +// +// ## Output +// +// { +// "error":"", +// "result":true, +// } +// +//export CreateSharedInfo +func CreateSharedInfo(phoneNumber, token, sharedInfo *C.char) *C.char { + js := C.GoString(sharedInfo) + + s := zboxapi.SharedInfo{} + err := json.Unmarshal([]byte(js), &s) + if err != nil { + log.Error("win: ", js, err) + return WithJSON(false, err) + } + + err = zboxApiClient.CreateSharedInfo(context.TODO(), C.GoString(phoneNumber), C.GoString(token), s) + if err != nil { + log.Error("win: ", err) + return WithJSON(false, err) + } + + return WithJSON(true, nil) +} + +// DeleteSharedInfo create a shareInfo on 0box db +// ## Inputs +// - phoneNumber +// - token +// - authTicket +// - lookupHash +// +// ## Output +// +// { +// "error":"", +// "result":true, +// } +// +//export DeleteSharedInfo +func DeleteSharedInfo(phoneNumber, token, authTicket, lookupHash *C.char) *C.char { + err := zboxApiClient.DeleteSharedInfo(context.TODO(), C.GoString(phoneNumber), C.GoString(token), C.GoString(authTicket), C.GoString(lookupHash)) + if err != nil { + log.Error("win: ", err) + return WithJSON(false, err) + } + + return WithJSON(true, nil) +} + +// GetSharedByMe get file list that is shared by me privatly +// ## Inputs +// - phoneNumber +// - token +// +// ## Output +// +// { +// "error":"", +// "result":[{},{}], +// } +// +//export GetSharedByMe +func GetSharedByMe(phoneNumber, token *C.char) *C.char { + list, err := zboxApiClient.GetSharedByMe(context.TODO(), C.GoString(phoneNumber), C.GoString(token)) + if err != nil { + log.Error("win: ", err) + return WithJSON(nil, err) + } + + return WithJSON(list, nil) +} + +// GetSharedByPublic get file list that is clicked by me +// ## Inputs +// - phoneNumber +// - token +// +// ## Output +// +// { +// "error":"", +// "result":[{},{}], +// } +// +//export GetSharedByPublic +func GetSharedByPublic(phoneNumber, token *C.char) *C.char { + list, err := zboxApiClient.GetSharedByPublic(context.TODO(), C.GoString(phoneNumber), C.GoString(token)) + if err != nil { + log.Error("win: ", err) + return WithJSON(nil, err) + } + + return WithJSON(list, nil) +} + +// GetSharedToMe get file list that is shared to me +// ## Inputs +// - phoneNumber +// - token +// +// ## Output +// +// { +// "error":"", +// "result":[{},{}], +// } +// +//export GetSharedToMe +func GetSharedToMe(phoneNumber, token *C.char) *C.char { + list, err := zboxApiClient.GetSharedToMe(context.TODO(), C.GoString(phoneNumber), C.GoString(token)) + if err != nil { + log.Error("win: ", err) + return WithJSON(nil, err) + } + + return WithJSON(list, nil) +} diff --git a/zboxapi/response.go b/zboxapi/response.go index 9daa193fb..66a2662c4 100644 --- a/zboxapi/response.go +++ b/zboxapi/response.go @@ -1,6 +1,7 @@ package zboxapi import ( + "encoding/base64" "encoding/json" "errors" ) @@ -20,3 +21,86 @@ type CsrfTokenResponse struct { type JwtTokenResponse struct { Token string `json:"jwt_token"` } + +type FreeStorageResponse struct { + Data string `json:"marker"` + FundingID int `json:"funding_id"` +} + +type MarkerData struct { + Marker string `json:"marker"` + RecipientPublicKey string `json:"recipient_public_key"` +} + +func (fs *FreeStorageResponse) ToMarker() (*FreeMarker, error) { + + buf, err := base64.StdEncoding.DecodeString(fs.Data) + + if err != nil { + return nil, err + } + + data := &MarkerData{} + err = json.Unmarshal(buf, &data) + if err != nil { + return nil, err + } + + buf, err = base64.StdEncoding.DecodeString(data.Marker) + if err != nil { + return nil, err + } + + fm := &FreeMarker{} + + err = json.Unmarshal(buf, fm) + if err != nil { + return nil, err + } + + return fm, nil +} + +type FreeMarker struct { + Assigner string `json:"assigner"` + Recipient string `json:"recipient"` + FreeTokens float64 `json:"free_tokens"` + Nonce int64 `json:"nonce"` + Signature string `json:"signature"` +} + +type JsonResult[T any] struct { + Message string `json:"message"` + Error string `json:"error"` + Data []T `json:"data"` +} + +type SharedInfo struct { + AuthTicket string `json:"auth_ticket"` + Message string `json:"message"` + ShareInfoType string `json:"share_info_type"` + Link string `json:"link"` +} + +type SharedInfoSent struct { + AuthTicket string `json:"auth_ticket"` + Message string `json:"message"` + ShareInfoType string `json:"share_info_type"` + Receiver string `json:"receiver_client_id"` + Link string `json:"link"` + ReceiverName string `json:"receiver_name"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` +} + +type SharedInfoReceived struct { + AuthTicket string `json:"auth_ticket"` + Message string `json:"message"` + ShareInfoType string `json:"share_info_type"` + ClientID string `json:"client_id"` + Receiver string `json:"receiver_client_id"` + LookupHash string `json:"lookup_hash"` + SenderName string `json:"sender_name"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` +} diff --git a/zboxapi/sdk.go b/zboxapi/sdk.go index 14a6b3edc..c091df59a 100644 --- a/zboxapi/sdk.go +++ b/zboxapi/sdk.go @@ -1,6 +1,7 @@ package zboxapi import ( + "bytes" "context" "encoding/json" "errors" @@ -11,10 +12,39 @@ import ( thrown "github.com/0chain/errors" "github.com/0chain/gosdk/core/encryption" + "github.com/0chain/gosdk/core/logger" "github.com/0chain/gosdk/core/resty" "github.com/0chain/gosdk/core/sys" + "github.com/0chain/gosdk/core/zcncrypto" ) +var log logger.Logger + +func GetLogger() *logger.Logger { + return &log +} + +func signHash(hash string, signatureScheme string, keys []sys.KeyPair) (string, error) { + retSignature := "" + for _, kv := range keys { + ss := zcncrypto.NewSignatureScheme(signatureScheme) + err := ss.SetPrivateKey(kv.PrivateKey) + if err != nil { + return "", err + } + + if len(retSignature) == 0 { + retSignature, err = ss.Sign(hash) + } else { + retSignature, err = ss.Add(retSignature, hash) + } + if err != nil { + return "", err + } + } + return retSignature, nil +} + type Client struct { baseUrl string appType string @@ -41,7 +71,7 @@ func (c *Client) SetWallet(clientID, clientPrivateKey, clientPublicKey string) { } func (c *Client) parseResponse(resp *http.Response, respBody []byte, result interface{}) error { - if resp.StatusCode == http.StatusOK { + if resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusCreated { if err := json.Unmarshal(respBody, result); err != nil { return thrown.Throw(ErrInvalidJsonResponse, string(respBody)) } @@ -90,7 +120,7 @@ func (c *Client) createResty(ctx context.Context, csrfToken, phoneNumber string, if c.clientPrivateKey != "" { data := fmt.Sprintf("%v:%v:%v", c.clientID, phoneNumber, c.clientPublicKey) hash := encryption.Hash(data) - sign, err := sys.Sign(hash, "bls0chain", []sys.KeyPair{{ + sign, err := signHash(hash, "bls0chain", []sys.KeyPair{{ PrivateKey: c.clientPrivateKey, }}) if err != nil { @@ -209,3 +239,192 @@ func (c *Client) RefreshJwtToken(ctx context.Context, phoneNumber string, token return result.Token, nil } + +func (c *Client) GetFreeStorage(ctx context.Context, phoneNumber, token string) (*FreeMarker, error) { + csrfToken, err := c.GetCsrfToken(ctx) + if err != nil { + return nil, err + } + headers := map[string]string{ + "X-App-ID-Token": token, + } + + r, err := c.createResty(ctx, csrfToken, phoneNumber, headers) + + if err != nil { + return nil, err + } + + result := &FreeStorageResponse{} + r.DoGet(ctx, c.baseUrl+"/v2/freestorage"). + Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { + if err != nil { + return err + } + + log.Info("zboxapi: ", string(respBody)) + return c.parseResponse(resp, respBody, result) + }) + + if errs := r.Wait(); len(errs) > 0 { + return nil, errs[0] + } + + return result.ToMarker() + +} + +func (c *Client) CreateSharedInfo(ctx context.Context, phoneNumber, token string, s SharedInfo) error { + csrfToken, err := c.GetCsrfToken(ctx) + if err != nil { + return err + } + headers := map[string]string{ + "X-App-ID-Token": token, + "Content-Type": "application/json", + } + + r, err := c.createResty(ctx, csrfToken, phoneNumber, headers) + + if err != nil { + return err + } + + buf, err := json.Marshal(s) + if err != nil { + return err + } + + result := &JsonResult[string]{} + r.DoPost(ctx, bytes.NewReader(buf), c.baseUrl+"/v2/shareinfo"). + Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { + if err != nil { + return err + } + + log.Info("zboxapi: ", string(respBody)) + return c.parseResponse(resp, respBody, &result) + }) + + if errs := r.Wait(); len(errs) > 0 { + return errs[0] + } + + return nil +} + +func (c *Client) DeleteSharedInfo(ctx context.Context, phoneNumber, token, authTicket string, lookupHash string) error { + csrfToken, err := c.GetCsrfToken(ctx) + if err != nil { + return err + } + headers := map[string]string{ + "X-App-ID-Token": token, + } + + r, err := c.createResty(ctx, csrfToken, phoneNumber, headers) + + if err != nil { + return err + } + + result := &JsonResult[string]{} + r.DoDelete(ctx, c.baseUrl+"/v2/shareinfo?auth_ticket="+authTicket+"&lookup_hash="+lookupHash). + Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { + if err != nil { + return err + } + + log.Info("zboxapi: ", string(respBody)) + return c.parseResponse(resp, respBody, &result) + }) + + if errs := r.Wait(); len(errs) > 0 { + return errs[0] + } + + return nil +} + +func (c *Client) GetSharedByPublic(ctx context.Context, phoneNumber, token string) ([]SharedInfoSent, error) { + return c.getShared(ctx, phoneNumber, token, false) +} + +func (c *Client) GetSharedByMe(ctx context.Context, phoneNumber, token string) ([]SharedInfoSent, error) { + return c.getShared(ctx, phoneNumber, token, true) +} + +func (c *Client) getShared(ctx context.Context, phoneNumber, token string, isPrivate bool) ([]SharedInfoSent, error) { + csrfToken, err := c.GetCsrfToken(ctx) + if err != nil { + return nil, err + } + headers := map[string]string{ + "X-App-ID-Token": token, + } + + r, err := c.createResty(ctx, csrfToken, phoneNumber, headers) + + if err != nil { + return nil, err + } + + shareInfoType := "public" + if isPrivate { + shareInfoType = "private" + } + + result := &JsonResult[SharedInfoSent]{} + r.DoGet(ctx, c.baseUrl+"/v2/shareinfo/shared?share_info_type="+shareInfoType). + Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { + if err != nil { + return err + } + + log.Info("zboxapi: ", string(respBody)) + + return c.parseResponse(resp, respBody, &result) + }) + + if errs := r.Wait(); len(errs) > 0 { + return nil, errs[0] + } + + return result.Data, nil + +} + +func (c *Client) GetSharedToMe(ctx context.Context, phoneNumber, token string) ([]SharedInfoReceived, error) { + csrfToken, err := c.GetCsrfToken(ctx) + if err != nil { + return nil, err + } + headers := map[string]string{ + "X-App-ID-Token": token, + } + + r, err := c.createResty(ctx, csrfToken, phoneNumber, headers) + + if err != nil { + return nil, err + } + + result := &JsonResult[SharedInfoReceived]{} + r.DoGet(ctx, c.baseUrl+"/v2/shareinfo/received?share_info_type=private"). + Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { + if err != nil { + return err + } + + log.Info("zboxapi: ", string(respBody)) + + return c.parseResponse(resp, respBody, &result) + }) + + if errs := r.Wait(); len(errs) > 0 { + return nil, errs[0] + } + + return result.Data, nil + +} diff --git a/zboxapi/sdk_test.go b/zboxapi/sdk_test.go index 39c70d376..2b54496ca 100644 --- a/zboxapi/sdk_test.go +++ b/zboxapi/sdk_test.go @@ -2,18 +2,20 @@ package zboxapi import ( "context" + "encoding/base64" + "encoding/json" "testing" "github.com/stretchr/testify/require" ) var ( - BaseURL = "https://0box.demo.zus.network" + BaseURL = "https://0box.dev.zus.network" AppType = "vult" - ClientID = "8f6ce6457fc04cfb4eb67b5ce3162fe2b85f66ef81db9d1a9eaa4ffe1d2359e0" - ClientPublicKey = "c8c88854822a1039c5a74bdb8c025081a64b17f52edd463fbecb9d4a42d15608f93b5434e926d67a828b88e63293b6aedbaf0042c7020d0a96d2e2f17d3779a4" - ClientPrivateKey = "72f480d4b1e7fb76e04327b7c2348a99a64f0ff2c5ebc3334a002aa2e66e8506" - PhoneNumber = "+917777777777" + ClientID = "70e1318a9709786cf975f15ca941bee73d0f422305ecd78b0f358870ec17f41d" + ClientPublicKey = "4ec4b4dfb8c9ceb8fb6e84ef46e503c3445a0c6d770986a019cdbef4bc47b70dfadd5441f708f0df47df14e5cd6a0aa94ec31ca66e337692d9a92599d9456a81" + ClientPrivateKey = "982801f352e886eaaf61196d83373b4cc09e9a598ffe1f49bf5adf905174cb0c" + PhoneNumber = "+16026666666" ) func TestGetCsrfToken(t *testing.T) { @@ -49,5 +51,156 @@ func TestJwtToken(t *testing.T) { require.Nil(t, err) require.NotEmpty(t, refreshedToken) require.NotEqual(t, token, refreshedToken) +} + +func TestGetFreeStorage(t *testing.T) { + t.Skip("Only for local debugging") + + c := NewClient() + c.SetRequest(BaseURL, AppType) + c.SetWallet(ClientID, ClientPrivateKey, ClientPublicKey) + sessionID, err := c.CreateJwtSession(context.TODO(), PhoneNumber) + + require.Nil(t, err) + require.GreaterOrEqual(t, sessionID, int64(0)) + + token, err := c.CreateJwtToken(context.TODO(), PhoneNumber, sessionID, "000000") //any otp works on test phone number + + require.Nil(t, err) + require.NotEmpty(t, token) + + marker, err := c.GetFreeStorage(context.TODO(), PhoneNumber, "jwt-"+token) + + require.NoError(t, err) + require.NotEmpty(t, marker.Assigner) + require.Equal(t, ClientID, marker.Recipient) +} + +var testShareInfo = SharedInfo{ + AuthTicket: "eyJjbGllbnRfaWQiOiIiLCJvd25lcl9pZCI6IjcwZTEzMThhOTcwOTc4NmNmOTc1ZjE1Y2E5NDFiZWU3M2QwZjQyMjMwNWVjZDc4YjBmMzU4ODcwZWMxN2Y0MWQiLCJhbGxvY2F0aW9uX2lkIjoiZjQ0OTUxZDkwODRiMTExZGMxNDliMmNkN2E5Nzg5YmU5MDVlYjFiMWRhNzdjMjYxNDZiMWNkY2IxNzE3NTI0NiIsImZpbGVfcGF0aF9oYXNoIjoiM2RlOWQ1ZTMzYWJlNWI3ZjhhNzM2OGY0ZmE4N2QwMmY1MjI1YzIzMzhmM2Q3YWI0MGQxNDczM2NiYmI4ZTc1YiIsImFjdHVhbF9maWxlX2hhc2giOiJkYTJjMzIxZmFiN2RkNmYyZDVlZTAzZWQwNDk2OGJlMTA0YjdjNmY2MTYyYTVmY2ZjNDFmZTEyZTY3ZDBkNjUzIiwiZmlsZV9uYW1lIjoiUVHlm77niYcyMDIxMDkzMDEyMDM1Ny5qcGciLCJyZWZlcmVuY2VfdHlwZSI6ImYiLCJleHBpcmF0aW9uIjowLCJ0aW1lc3RhbXAiOjE2OTgyODY5MjcsImVuY3J5cHRlZCI6ZmFsc2UsInNpZ25hdHVyZSI6ImRkMzg4NzI2YTcwYzBjN2Y5NDZkMTQwMTRjMjhhZTg1MjM4ZTliNmJkMmExMzRjMWUxOGE3MTE5NDViYzg4MGYifQ==", + Message: "shared by unit test", + ShareInfoType: "public", + Link: "https://0box.page.link/cnfFExcvKKRaFzyE9", +} + +func TestCreateSharedInfo(t *testing.T) { + t.Skip("Only for local debugging") + + c := NewClient() + c.SetRequest(BaseURL, AppType) + c.SetWallet(ClientID, ClientPrivateKey, ClientPublicKey) + sessionID, err := c.CreateJwtSession(context.TODO(), PhoneNumber) + + require.Nil(t, err) + require.GreaterOrEqual(t, sessionID, int64(0)) + + token, err := c.CreateJwtToken(context.TODO(), PhoneNumber, sessionID, "000000") //any otp works on test phone number + + require.Nil(t, err) + require.NotEmpty(t, token) + + err = c.CreateSharedInfo(context.TODO(), PhoneNumber, "jwt-"+token, testShareInfo) + + require.NoError(t, err) + +} + +func TestGetSharedToMe(t *testing.T) { + t.Skip("Only for local debugging") + + c := NewClient() + c.SetRequest(BaseURL, AppType) + c.SetWallet(ClientID, ClientPrivateKey, ClientPublicKey) + sessionID, err := c.CreateJwtSession(context.TODO(), PhoneNumber) + + require.Nil(t, err) + require.GreaterOrEqual(t, sessionID, int64(0)) + + token, err := c.CreateJwtToken(context.TODO(), PhoneNumber, sessionID, "000000") //any otp works on test phone number + + require.Nil(t, err) + require.NotEmpty(t, token) + + list, err := c.GetSharedToMe(context.TODO(), PhoneNumber, "jwt-"+token) + + require.NoError(t, err) + require.Greater(t, len(list), 0) + // require.NotEmpty(t, marker.Assigner) + // require.Equal(t, ClientID, marker.Recipient) +} + +func TestGetSharedByMe(t *testing.T) { + t.Skip("Only for local debugging") + + c := NewClient() + c.SetRequest(BaseURL, AppType) + c.SetWallet(ClientID, ClientPrivateKey, ClientPublicKey) + sessionID, err := c.CreateJwtSession(context.TODO(), PhoneNumber) + + require.Nil(t, err) + require.GreaterOrEqual(t, sessionID, int64(0)) + + token, err := c.CreateJwtToken(context.TODO(), PhoneNumber, sessionID, "000000") //any otp works on test phone number + + require.Nil(t, err) + require.NotEmpty(t, token) + + list, err := c.GetSharedByMe(context.TODO(), PhoneNumber, "jwt-"+token) + + require.NoError(t, err) + require.Greater(t, len(list), 0) + +} + +func TestGetSharedByPublic(t *testing.T) { + t.Skip("Only for local debugging") + + c := NewClient() + c.SetRequest(BaseURL, AppType) + c.SetWallet(ClientID, ClientPrivateKey, ClientPublicKey) + sessionID, err := c.CreateJwtSession(context.TODO(), PhoneNumber) + + require.Nil(t, err) + require.GreaterOrEqual(t, sessionID, int64(0)) + + token, err := c.CreateJwtToken(context.TODO(), PhoneNumber, sessionID, "000000") //any otp works on test phone number + + require.Nil(t, err) + require.NotEmpty(t, token) + + list, err := c.GetSharedByPublic(context.TODO(), PhoneNumber, "jwt-"+token) + + require.NoError(t, err) + require.Greater(t, len(list), 0) + +} + +func TestDeleteSharedInfo(t *testing.T) { + t.Skip("Only for local debugging") + + c := NewClient() + c.SetRequest(BaseURL, AppType) + c.SetWallet(ClientID, ClientPrivateKey, ClientPublicKey) + sessionID, err := c.CreateJwtSession(context.TODO(), PhoneNumber) + + require.Nil(t, err) + require.GreaterOrEqual(t, sessionID, int64(0)) + + token, err := c.CreateJwtToken(context.TODO(), PhoneNumber, sessionID, "000000") //any otp works on test phone number + + require.Nil(t, err) + require.NotEmpty(t, token) + + buf, _ := base64.StdEncoding.DecodeString(testShareInfo.AuthTicket) + + items := make(map[string]any) + + json.Unmarshal(buf, &items) + + lookupHash := items["file_path_hash"].(string) + + err = c.DeleteSharedInfo(context.TODO(), PhoneNumber, "jwt-"+token, testShareInfo.AuthTicket, lookupHash) + + require.NoError(t, err) } diff --git a/zboxcore/fileref/fileref.go b/zboxcore/fileref/fileref.go index ad18b5583..eae303752 100644 --- a/zboxcore/fileref/fileref.go +++ b/zboxcore/fileref/fileref.go @@ -73,6 +73,8 @@ type Ref struct { LookupHash string `json:"lookup_hash" mapstructure:"lookup_hash"` FileID string `json:"file_id" mapstructure:"file_id"` FileMetaHash string `json:"file_meta_hash" mapstructure:"file_meta_hash"` + ThumbnailHash string `json:"thumbnail_hash" mapstructure:"thumbnail_hash"` + ThumbnailSize int64 `json:"thumbnail_size" mapstructure:"thumbnail_size"` HashToBeComputed bool ChildrenLoaded bool Children []RefEntity `json:"-" mapstructure:"-"` diff --git a/zboxcore/sdk/chunked_upload_web_streaming.go b/zboxcore/sdk/chunked_upload_web_streaming.go index ca12a64e5..ea09ae558 100644 --- a/zboxcore/sdk/chunked_upload_web_streaming.go +++ b/zboxcore/sdk/chunked_upload_web_streaming.go @@ -22,10 +22,10 @@ func TranscodeWebStreaming(workdir string, fileReader io.Reader, fileMeta FileMe // create ./zcn/transcode folder if it doesn't exists os.MkdirAll(outDir, 0766) //nolint: errcheck - remoteName, remotePath := getRemoteNameAndRemotePath(fileMeta.RemoteName, fileMeta.RemotePath) + remoteName, remotePath := GetTranscodeFile(fileMeta.RemotePath) fileName := filepath.Join(outDir, remoteName) - + logger.Logger.Info("transcode: start ", fileName) args := []string{"-i", fileMeta.Path, "-f", "mp4", "-movflags", "frag_keyframe+empty_moov+default_base_moof", fileName, "-y"} @@ -76,7 +76,7 @@ func TranscodeWebStreaming(workdir string, fileReader io.Reader, fileMeta FileMe return r, fm, fileName, nil } -func getRemoteNameAndRemotePath(remoteName string, remotePath string) (string, string) { +func GetTranscodeFile(remotePath string) (string, string) { newRemotePath, newRemoteName := path.Split(remotePath) newRemoteNameSlice := strings.Split(newRemoteName, ".") if len(newRemoteNameSlice) > 0 { diff --git a/zboxcore/sdk/listworker.go b/zboxcore/sdk/listworker.go index f4167044c..b803a81c4 100644 --- a/zboxcore/sdk/listworker.go +++ b/zboxcore/sdk/listworker.go @@ -44,23 +44,26 @@ type listResponse struct { } type ListResult struct { - Name string `json:"name"` - Path string `json:"path,omitempty"` - Type string `json:"type"` - Size int64 `json:"size"` - Hash string `json:"hash,omitempty"` - FileMetaHash string `json:"file_meta_hash,omitempty"` - MimeType string `json:"mimetype,omitempty"` - NumBlocks int64 `json:"num_blocks"` - LookupHash string `json:"lookup_hash"` - EncryptionKey string `json:"encryption_key"` - ActualSize int64 `json:"actual_size"` - ActualNumBlocks int64 `json:"actual_num_blocks"` - CreatedAt common.Timestamp `json:"created_at"` - UpdatedAt common.Timestamp `json:"updated_at"` - Children []*ListResult `json:"list"` - Consensus `json:"-"` - deleteMask zboxutil.Uint128 `json:"-"` + Name string `json:"name"` + Path string `json:"path,omitempty"` + Type string `json:"type"` + Size int64 `json:"size"` + Hash string `json:"hash,omitempty"` + FileMetaHash string `json:"file_meta_hash,omitempty"` + MimeType string `json:"mimetype,omitempty"` + NumBlocks int64 `json:"num_blocks"` + LookupHash string `json:"lookup_hash"` + EncryptionKey string `json:"encryption_key"` + ActualSize int64 `json:"actual_size"` + ActualNumBlocks int64 `json:"actual_num_blocks"` + ThumbnailHash string `json:"thumbnail_hash"` + ThumbnailSize int64 `json:"thumbnail_size"` + + CreatedAt common.Timestamp `json:"created_at"` + UpdatedAt common.Timestamp `json:"updated_at"` + Children []*ListResult `json:"list"` + Consensus `json:"-"` + deleteMask zboxutil.Uint128 `json:"-"` } func (req *ListRequest) getListInfoFromBlobber(blobber *blockchain.StorageNode, blobberIdx int, rspCh chan<- *listResponse) { @@ -215,6 +218,9 @@ func (req *ListRequest) GetListFromBlobbers() (*ListResult, error) { result.LookupHash = ti.ref.LookupHash result.FileMetaHash = ti.ref.FileMetaHash result.ActualSize = ti.ref.ActualSize + result.ThumbnailHash = ti.ref.ThumbnailHash + result.ThumbnailSize = ti.ref.ThumbnailSize + if ti.ref.ActualSize > 0 { result.ActualNumBlocks = (ti.ref.ActualSize + CHUNK_SIZE - 1) / CHUNK_SIZE } @@ -271,6 +277,8 @@ func (lr *ListResult) populateChildren(children []fileref.RefEntity, childResult childResult.MimeType = (child.(*fileref.FileRef)).MimeType childResult.EncryptionKey = (child.(*fileref.FileRef)).EncryptedKey childResult.ActualSize = (child.(*fileref.FileRef)).ActualFileSize + childResult.ThumbnailHash = (child.(*fileref.FileRef)).ThumbnailHash + childResult.ThumbnailSize = (child.(*fileref.FileRef)).ThumbnailSize } else { childResult.ActualSize = (child.(*fileref.Ref)).ActualSize } From 39776e7bef0ee3b1efb23551c8f7fdde69e11e23 Mon Sep 17 00:00:00 2001 From: Yury Date: Sun, 29 Oct 2023 12:22:49 +0200 Subject: [PATCH 072/134] Fix/fail shardedr on bad code (#1264) * Fix/remove path (#1221) * feature: added more test cases * fix: fixed existing test cases * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * feature: added more test cases * feature: added more test cases * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * feature: added mocks * fix: fixed bugs * fix: fixed mocks * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: made components internal * Add webstreaming to multiupload (#1190) * add webstreaming * fix typos * add webstreaming to wasm multiupload * fix typo * fix dup upload consensus (#1195) * Fix multiupload completed callback (#1172) * remove unnecessary print * fix delete and createdir * return major error * add webstreaming * fix typos * add webstreaming to wasm multiupload * fix typo * cleanup * fix completed callback * Feat/update methods in WinSDK (#1198) * delete dir in repair (#1196) * delete dir in repair * replace ioutil * fix unit test * fix list worker test * fix rename dir error * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * Add NFT Config contract (#1212) * Silent the zcnbridge http request when --silent (#1207) * Change the return type of downloadBlocks to []byte in wasm (#1218) * change the order of exchanges to get the ZCN prices (#1216) * Deprecate non multi-operation functions (#1214) * remove CreateDir, Rename, Copy, Move * use docker build wasm * use @v4 version of git action * Revert "use @v4 version of git action" This reverts commit fbb93f25a6ca63d6e205eac418d031bba428eb29. * Updated self hosted macos runner (#1219) * Updated self hosted macos runner * fixed runner name build-sdks.yml * remove path header, fix ws tag --------- Co-authored-by: YarikRevich Co-authored-by: Yaroslav Svitlytskyi <53532703+YarikRevich@users.noreply.github.com> Co-authored-by: Dinmukhammed Kambarov <52813950+din-mukhammed@users.noreply.github.com> Co-authored-by: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Co-authored-by: Lz Co-authored-by: Yaroslav Svitlytskyi Co-authored-by: peterlimg <54137706+peterlimg@users.noreply.github.com> Co-authored-by: Kishan Dhakan <42718091+Kishan-Dhakan@users.noreply.github.com> Co-authored-by: Manohar Reddy Co-authored-by: shahnawaz-creator <117025384+shahnawaz-creator@users.noreply.github.com> Co-authored-by: din-mukhammed * Revert "Fix/remove path (#1221)" (#1222) This reverts commit 464260aa3c2be34fdc0aca58582b27247528333b. * remove path header, fix ws tag (#1223) * remove path header, fix ws tag * fixed broken build --------- Co-authored-by: din-mukhammed * Updated self hosted macos runner (#1219) * Updated self hosted macos runner * fixed runner name build-sdks.yml (cherry picked from commit 1c9f143fe842e6c88fec1a6bc5fa0ced2ca84682) * updated wasm binary build fix. * README grammar and formatting tweaks. * Merge remote-tracking branch 'origin/feature/sharder-keep-list' into feature/sharder-keep-list --------- Co-authored-by: YarikRevich Co-authored-by: Yaroslav Svitlytskyi <53532703+YarikRevich@users.noreply.github.com> Co-authored-by: Dinmukhammed Kambarov <52813950+din-mukhammed@users.noreply.github.com> Co-authored-by: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Co-authored-by: Lz Co-authored-by: Yaroslav Svitlytskyi Co-authored-by: peterlimg <54137706+peterlimg@users.noreply.github.com> Co-authored-by: Kishan Dhakan <42718091+Kishan-Dhakan@users.noreply.github.com> Co-authored-by: Manohar Reddy Co-authored-by: shahnawaz-creator <117025384+shahnawaz-creator@users.noreply.github.com> Co-authored-by: din-mukhammed Co-authored-by: shahnawaz-creator Co-authored-by: UncertainBadg3r <139782199+UncertainBadg3r@users.noreply.github.com> --- README.md | 44 ++++++++++++++++++------------------- wasmsdk/blobber.go | 46 +++++++++++++++++++++++++++++++++++++++ zboxcore/zboxutil/http.go | 5 +++++ 3 files changed, 73 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index 898bb5ccd..eb441e652 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ This repository currently supports the following platforms: ### Instructions - Go is required to build gosdk code. Instructions can be found [here](https://go.dev/doc/install) - 1. Save below code as sdkversion.go + 1. Save below code as `sdkversion.go` package main @@ -64,18 +64,18 @@ This repository currently supports the following platforms: ## Mobile Builds -- gosdk can be build to use on Mobile platforms iOS and Android using gomobile. -- Xcode Command Line Tools is required to build SDK for iOS. -- Android studio with NDK is required to build SDK for Android. +- gosdk can be built for iOS and Android using gomobile. +- Xcode Command Line Tools is required to build the SDK for iOS. +- Android studio with NDK is required to build the SDK for Android. - See [FAQ](#faq) for installing Go, gomobile Xcode or Android Studio. Steps: -1. Run below command for the first time to setup gomobile environment +1. Run the command below for the first time to setup the gomobile environment: make setup-gomobile -2. In case Go package not found in golang.org/x/mobile/bind, run the command +2. In case the Go package is not found in `golang.org/x/mobile/bind`, run: `go get golang.org/x/mobile/bind` -3. Use below commands in the root folder of the repo to build Mobile SDK +3. Run below commands in the root folder of the repo to build the Mobile SDK: For iOS only: make build-ios @@ -84,14 +84,14 @@ Steps: ## Expose a gosdk function to mobilesdk Examples: -* `mobilesdk/sdk/common.go` which exports the functions in `core/encryption/hash.go`. +* `mobilesdk/sdk/common.go`, which exports the functions in `core/encryption/hash.go`. Steps: 1. If you are exposing: - - a new function from an existing file like `zboxcore/sdk/allocation.go`, you should add a function to `mobilesdksdk/zbox/allocation.go` which should call the gosdk function you intend to expose. - - a function from a new file, you should create a new `.go` file for it, in the same style as `mobilesdksdk/zbox/allocation.go` & in the file created, you should call the gosdk function you intend to expose. + - a new function from an existing file, such as `zboxcore/sdk/allocation.go`, you should add a function to `mobilesdksdk/zbox/allocation.go`. This new function should call the gosdk function you intend to expose. + - a function from a new file, you should create a new `.go` file for it. This should follow the same style as `mobilesdksdk/zbox/allocation.go`. In the new file, call the gosdk function you intend to expose. 2. Build the Mobile SDK as mentioned in the 'Mobile Builds' section of this file to build the aar file used in the mobile application you are developing. @@ -123,7 +123,7 @@ Steps: ### An important note regarding export of an async function -If your golang function requires to be run asynchronously, you need to add more wrapper code where you are returning a Promise object. +If your golang function needs to suport asynchronous execution, you need to add more wrapper code where you are returning a Promise object. See "InitZCNSDK" example: @@ -157,18 +157,18 @@ func InitZCNSDK(this js.Value, p []js.Value) interface{} { ### BLS unit test -It's advisable to put GOPATH as $TOP/../go, to avoid conflicts with this command: `go build ./...` +It's advisable to put GOPATH as `$TOP/../go`, to avoid conflicts with this command: `go build ./...` -To run all the unit tests in `gosdk`: go test github.com/0chain/gosdk/zboxcore/sdk -v` +To run all the unit tests in `gosdk`: `go test github.com/0chain/gosdk/zboxcore/sdk -v` ```bash $ go test ./... ``` To run all the unit tests in `bls0chain_test.go`, run this command from $TOP: `go test github.com/0chain/gosdk/core/zcncrypto -v` -To run a specific unit test in `bls0chain_test.go` such as `TestSignatureScheme`, run this: `go test github.com/0chain/gosdk/core/zcncrypto -v -run TestSignatureScheme` +To run a specific unit test in `bls0chain_test.go`, such as `TestSignatureScheme`, run: `go test github.com/0chain/gosdk/core/zcncrypto -v -run TestSignatureScheme` -To run the coverage test in `gosdk: +To run the coverage test in `gosdk`: ```bash $ go test -coverprofile=coverage.out $ go tool cover -html=coverage.out @@ -180,32 +180,32 @@ $ go tool cover -html=coverage.out 1. You need to install nodejs first, see [this page](https://nodejs.org/en/download/) for further instructions -2. Add `/path/to/go/misc/wasm` to your `$PATH` environment variable (so that "go test" can find "go_js_wasm_exec"). For example in ubuntu, run `$export PATH=$PATH:/usr/local/go/misc/wasm/`. +2. Add `/path/to/go/misc/wasm` to your `$PATH` environment variable (so that `go test` can find `go_js_wasm_exec`). For example in Ubuntu, run `$export PATH=$PATH:/usr/local/go/misc/wasm/`. 3. You can then run the test by following the [BLS unit test](#bls-unit-test) above by adding the prefix environment `GOOS=js CGO_ENABLED=0 GOARCH=wasm`: - ``` + ```bash go test -tags test -v github.com/0chain/gosdk/wasmsdk ``` #### Test in the client -1. After you successfully [export the wasm package to proxy.wasm](#how-to-export-a-gosdk-function-to-webassembly), now you can test that `proxy.wasm`. +1. After you successfully [export the wasm package to proxy.wasm](#how-to-export-a-gosdk-function-to-webassembly), you can test the exported `proxy.wasm`. 2. We currently have a test page going at the js-client-sdk repo: `https://github.com/0chain/js-client-sdk/blob/gosdk/test/index.html` 3. You can replace the proxy.wasm at `https://github.com/0chain/js-client-sdk/blob/gosdk/test/proxy.wasm` -4. You need to startup a special test server in order to stream WASM files. Use this command from js-client-sdk $TOP: `sudo php -S localhost:82 test/server.php` +4. You need to start a special test server in order to stream WASM files. Use the following command from js-client-sdk $TOP: `sudo php -S localhost:82 test/server.php` -5. See "testethwallet" function in index.html for how the testing for ethwallet.go is done +5. See "testethwallet" function in index.html for how the testing for ethwallet.go is done. 6. To test the function you exported, it's probably as simple as calling "HelloWorld()". It should be a 1-liner. ### How to install `ffmpeg` -### On linux ubuntu +#### On Ubuntu Linux -``` +```bash sudo apt-get install ffmpeg sudo apt-get install v4l-utils ``` diff --git a/wasmsdk/blobber.go b/wasmsdk/blobber.go index 9de0de825..c0b23d83f 100644 --- a/wasmsdk/blobber.go +++ b/wasmsdk/blobber.go @@ -510,6 +510,52 @@ func MultiOperation(allocationID string, jsonMultiUploadOptions string) error { return allocationObj.DoMultiOperation(operations) } +func bulkUpload(jsonBulkUploadOptions string) ([]BulkUploadResult, error) { + var options []BulkUploadOption + err := json.Unmarshal([]byte(jsonBulkUploadOptions), &options) + if err != nil { + return nil, err + } + + n := len(options) + wait := make(chan BulkUploadResult, 1) + + for _, option := range options { + go func(o BulkUploadOption) { + result := BulkUploadResult{ + RemotePath: o.RemotePath, + } + defer func() { wait <- result }() + + ok, err := uploadWithJsFuncs(o.AllocationID, o.RemotePath, + o.ReadChunkFuncName, + o.FileSize, + o.ThumbnailBytes.Buffer, + o.IsWebstreaming, + o.Encrypt, + o.IsUpdate, + o.IsRepair, + o.NumBlocks, + o.CallbackFuncName) + result.Success = ok + if err != nil { + result.Error = err.Error() + result.Success = false + } + + }(option) + + } + + results := make([]BulkUploadResult, 0, n) + for i := 0; i < n; i++ { + result := <-wait + results = append(results, result) + } + + return results, nil +} + func multiUpload(jsonBulkUploadOptions string) (MultiUploadResult, error) { var options []BulkUploadOption result := MultiUploadResult{} diff --git a/zboxcore/zboxutil/http.go b/zboxcore/zboxutil/http.go index 4a1ef8098..c8480322b 100644 --- a/zboxcore/zboxutil/http.go +++ b/zboxcore/zboxutil/http.go @@ -838,6 +838,11 @@ func MakeSCRestAPICall(scAddress string, relativePath string, params map[string] defer response.Body.Close() entityBytes, _ := ioutil.ReadAll(response.Body) mu.Lock() + if response.StatusCode > http.StatusBadRequest { + blockchain.Sharders.Fail(sharder) + } else { + blockchain.Sharders.Success(sharder) + } responses[response.StatusCode]++ if responses[response.StatusCode] > maxCount { maxCount = responses[response.StatusCode] From 23d979994dbaebdd22120ce1b9e290192077dfaa Mon Sep 17 00:00:00 2001 From: Yury Date: Sun, 29 Oct 2023 12:23:06 +0200 Subject: [PATCH 073/134] Fix/roll logs (#1266) * Added lumberjack logger * Added lumberjack logger --- zboxcore/sdk/sdk.go | 15 ++++++++++----- zcnbridge/bridge.go | 26 ++++++++++++++++---------- zcnbridge/http/rest.go | 26 +++++++++++++++++--------- zcnbridge/wallet/wallet.go | 16 +++++++++------- zcncore/wallet_base.go | 27 +++++++++++++++++++-------- 5 files changed, 71 insertions(+), 39 deletions(-) diff --git a/zboxcore/sdk/sdk.go b/zboxcore/sdk/sdk.go index 33c2ca481..2174b4b03 100644 --- a/zboxcore/sdk/sdk.go +++ b/zboxcore/sdk/sdk.go @@ -8,7 +8,6 @@ import ( "io/ioutil" "math" "net/http" - "os" "strconv" "time" @@ -19,6 +18,7 @@ import ( "github.com/0chain/gosdk/core/node" "github.com/0chain/gosdk/core/sys" "go.uber.org/zap" + "gopkg.in/natefinch/lumberjack.v2" "github.com/0chain/gosdk/core/common" "github.com/0chain/gosdk/core/transaction" @@ -71,11 +71,16 @@ func SetLogLevel(lvl int) { // logFile - Log file // verbose - true - console output; false - no console output func SetLogFile(logFile string, verbose bool) { - f, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) - if err != nil { - return + var ioWriter = &lumberjack.Logger{ + Filename: logFile, + MaxSize: 100, // MB + MaxBackups: 5, // number of backups + MaxAge: 28, //days + LocalTime: false, + Compress: false, // disabled by default } - l.Logger.SetLogFile(f, verbose) + + l.Logger.SetLogFile(ioWriter, verbose) l.Logger.Info("******* Storage SDK Version: ", version.VERSIONSTR, " *******") } diff --git a/zcnbridge/bridge.go b/zcnbridge/bridge.go index 00d18bf5b..e66a61ae5 100644 --- a/zcnbridge/bridge.go +++ b/zcnbridge/bridge.go @@ -5,17 +5,19 @@ import ( "encoding/hex" "encoding/json" "fmt" + "io" + "math/big" + "strconv" + "time" + "github.com/0chain/common/core/currency" "github.com/0chain/gosdk/zcnbridge/ethereum/bancor" "github.com/0chain/gosdk/zcnbridge/ethereum/token" h "github.com/0chain/gosdk/zcnbridge/http" hdw "github.com/0chain/gosdk/zcncore/ethhdwallet" "github.com/spf13/viper" - "io" - "math/big" - "os" - "strconv" - "time" + + "gopkg.in/natefinch/lumberjack.v2" "github.com/0chain/gosdk/core/logger" "github.com/0chain/gosdk/zcnbridge/ethereum" @@ -45,11 +47,15 @@ func init() { Logger.Init(defaultLogLevel, "zcnbridge-sdk") Logger.SetLevel(logger.DEBUG) - f, err := os.OpenFile("bridge.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) - if err != nil { - return - } - Logger.SetLogFile(f, true) + ioWriter := &lumberjack.Logger{ + Filename: "bridge.log", + MaxSize: 100, // MB + MaxBackups: 5, // number of backups + MaxAge: 28, //days + LocalTime: false, + Compress: false, // disabled by default + } + Logger.SetLogFile(ioWriter, true) } var ( diff --git a/zcnbridge/http/rest.go b/zcnbridge/http/rest.go index 9c6071362..87bfee4f9 100644 --- a/zcnbridge/http/rest.go +++ b/zcnbridge/http/rest.go @@ -8,10 +8,10 @@ import ( "io/ioutil" "net/http" "net/url" - "os" "sync" "go.uber.org/zap" + "gopkg.in/natefinch/lumberjack.v2" "github.com/0chain/gosdk/core/logger" "github.com/0chain/gosdk/core/util" @@ -38,23 +38,31 @@ func init() { Logger.Init(defaultLogLevel, "zcnbridge-http-sdk") Logger.SetLevel(logger.DEBUG) - f, err := os.OpenFile("bridge.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) - if err != nil { - return + ioWriter := &lumberjack.Logger{ + Filename: "bridge.log", + MaxSize: 100, // MB + MaxBackups: 5, // number of backups + MaxAge: 28, //days + LocalTime: false, + Compress: false, // disabled by default } - Logger.SetLogFile(f, true) + Logger.SetLogFile(ioWriter, true) } func SetLogFile(logFile string, verbose bool) { Logger.Init(defaultLogLevel, "zcnbridge-sdk") Logger.SetLevel(logger.DEBUG) - f, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) - if err != nil { - return + ioWriter := &lumberjack.Logger{ + Filename: logFile, + MaxSize: 100, // MB + MaxBackups: 5, // number of backups + MaxAge: 28, //days + LocalTime: false, + Compress: false, // disabled by default } logVerbose = verbose - Logger.SetLogFile(f, logVerbose) + Logger.SetLogFile(ioWriter, logVerbose) } // MakeSCRestAPICall calls smart contract with provided address diff --git a/zcnbridge/wallet/wallet.go b/zcnbridge/wallet/wallet.go index b6fd10c1e..74168b313 100644 --- a/zcnbridge/wallet/wallet.go +++ b/zcnbridge/wallet/wallet.go @@ -1,10 +1,8 @@ package wallet import ( - //"github.com/0chain/gosdk/zcnbridge/log" - "os" - "github.com/0chain/gosdk/core/logger" + "gopkg.in/natefinch/lumberjack.v2" ) const ( @@ -23,9 +21,13 @@ func init() { Logger.Init(defaultLogLevel, "zcnbridge-wallet-sdk") Logger.SetLevel(logger.DEBUG) - f, err := os.OpenFile("bridge.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) - if err != nil { - return + ioWriter := &lumberjack.Logger{ + Filename: "bridge.log", + MaxSize: 100, // MB + MaxBackups: 5, // number of backups + MaxAge: 28, //days + LocalTime: false, + Compress: false, // disabled by default } - Logger.SetLogFile(f, true) + Logger.SetLogFile(ioWriter, true) } diff --git a/zcncore/wallet_base.go b/zcncore/wallet_base.go index 4dc2c74a9..af4720b7f 100644 --- a/zcncore/wallet_base.go +++ b/zcncore/wallet_base.go @@ -8,7 +8,6 @@ import ( "math" "net/http" "net/url" - "os" "strconv" "strings" "sync" @@ -27,6 +26,7 @@ import ( "github.com/0chain/gosdk/zboxcore/encryption" "github.com/0chain/gosdk/zboxcore/zboxutil" openssl "github.com/Luzifer/go-openssl/v3" + "gopkg.in/natefinch/lumberjack.v2" ) const ( @@ -319,11 +319,15 @@ func SetLogLevel(lvl int) { // SetLogFile - sets file path to write log // verbose - true - console output; false - no console output func SetLogFile(logFile string, verbose bool) { - f, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) - if err != nil { - return - } - logging.SetLogFile(f, verbose) + ioWriter := &lumberjack.Logger{ + Filename: logFile, + MaxSize: 100, // MB + MaxBackups: 5, // number of backups + MaxAge: 28, //days + LocalTime: false, + Compress: false, // disabled by default + } + logging.SetLogFile(ioWriter, verbose) logging.Info("******* Wallet SDK Version:", version.VERSIONSTR, " ******* (SetLogFile)") } @@ -1278,7 +1282,7 @@ func Decrypt(key, text string) (string, error) { func CryptoJsEncrypt(passphrase, message string) (string, error) { o := openssl.New() - enc, err := o.EncryptBytes(passphrase, []byte(message), openssl.DigestMD5Sum) + enc, err := o.EncryptBytes(pad(passphrase, 32, ","), []byte(message), openssl.DigestMD5Sum) if err != nil { return "", err } @@ -1286,9 +1290,16 @@ func CryptoJsEncrypt(passphrase, message string) (string, error) { return string(enc), nil } +func pad(passphrase string, i int, symbol string) string { + if len(passphrase) < i { + return passphrase + strings.Repeat(symbol, i-len(passphrase)) + } + return passphrase +} + func CryptoJsDecrypt(passphrase, encryptedMessage string) (string, error) { o := openssl.New() - dec, err := o.DecryptBytes(passphrase, []byte(encryptedMessage), openssl.DigestMD5Sum) + dec, err := o.DecryptBytes(pad(passphrase, 32, ","), []byte(encryptedMessage), openssl.DigestMD5Sum) if err != nil { return "", err } From f9e9aab24355d134ebee10a2f4ced2acbae91087 Mon Sep 17 00:00:00 2001 From: Lz Date: Mon, 30 Oct 2023 15:28:25 +0800 Subject: [PATCH 074/134] fix:download file/thumbnail by authticket in winsdk (#1265) --- winsdk/allocation.go | 16 ++++- winsdk/browser.go | 13 +++- winsdk/cache.go | 9 +-- winsdk/helper.go | 14 ++++- winsdk/sdk.go | 57 ++++++++++++++++- winsdk/storage.go | 119 ++++++++++++++++++++++++++++++++---- winsdk/zboxapi.go | 60 ++++++++++++++++++ zboxapi/sdk.go | 9 +-- zboxcore/fileref/fileref.go | 42 +++++++------ zboxcore/sdk/allocation.go | 10 ++- zboxcore/sdk/listworker.go | 34 ++++++----- 11 files changed, 317 insertions(+), 66 deletions(-) diff --git a/winsdk/allocation.go b/winsdk/allocation.go index 0f21029eb..f121c2a1f 100644 --- a/winsdk/allocation.go +++ b/winsdk/allocation.go @@ -27,6 +27,11 @@ import ( // //export GetAllocation func GetAllocation(allocationID *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() allocID := C.GoString(allocationID) return WithJSON(getAllocation(allocID)) } @@ -41,6 +46,11 @@ func GetAllocation(allocationID *C.char) *C.char { // //export ListAllocations func ListAllocations() *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() items, err := sdk.GetAllocations() if err != nil { log.Error("win: ", err) @@ -61,7 +71,11 @@ func ListAllocations() *C.char { // //export CreateFreeAllocation func CreateFreeAllocation(freemarker *C.char) *C.char { - + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() marker := &zboxapi.FreeMarker{} js := C.GoString(freemarker) err := json.Unmarshal([]byte(js), marker) diff --git a/winsdk/browser.go b/winsdk/browser.go index 0822210f5..8f4dca987 100644 --- a/winsdk/browser.go +++ b/winsdk/browser.go @@ -33,6 +33,11 @@ type RemoteFile struct { // //export ListAll func ListAll(allocationID *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() alloc, err := getAllocation(C.GoString(allocationID)) if err != nil { log.Error("win: ", err) @@ -76,7 +81,11 @@ func ListAll(allocationID *C.char) *C.char { // //export List func List(allocationID, remotePath, authTicket, lookupHash *C.char) *C.char { - + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() allocID := C.GoString(allocationID) remotepath := C.GoString(remotePath) authticket := C.GoString(authTicket) @@ -113,7 +122,7 @@ func List(allocationID, remotePath, authTicket, lookupHash *C.char) *C.char { return WithJSON("[]", errors.New("Error: lookuphash flag is missing")) } - allocationObj, err := getAllocationWith(authticket) + allocationObj, _, err := getAllocationWith(authticket) if err != nil { log.Error("win: ", err) return WithJSON("[]", err) diff --git a/winsdk/cache.go b/winsdk/cache.go index 70d490c4b..b5d4c918f 100644 --- a/winsdk/cache.go +++ b/winsdk/cache.go @@ -52,18 +52,19 @@ func getAllocation(allocationID string) (*sdk.Allocation, error) { return it.Allocation, nil } -func getAllocationWith(authTicket string) (*sdk.Allocation, error) { +func getAllocationWith(authTicket string) (*sdk.Allocation, *marker.AuthTicket, error) { sEnc, err := base64.StdEncoding.DecodeString(authTicket) if err != nil { - return nil, errors.New("Error decoding the auth ticket." + err.Error()) + return nil, nil, errors.New("Error decoding the auth ticket." + err.Error()) } at := &marker.AuthTicket{} err = json.Unmarshal(sEnc, at) if err != nil { - return nil, errors.New("Error unmarshaling the auth ticket." + err.Error()) + return nil, nil, errors.New("Error unmarshaling the auth ticket." + err.Error()) } - return getAllocation(at.AllocationID) + alloc, err := getAllocation(at.AllocationID) + return alloc, at, err } func getFileMeta(allocationID, remotePath string) (*sdk.ConsolidatedFileMeta, error) { diff --git a/winsdk/helper.go b/winsdk/helper.go index 09b05fdfd..867ab2677 100644 --- a/winsdk/helper.go +++ b/winsdk/helper.go @@ -7,13 +7,13 @@ import ( "C" ) import ( + "encoding/base64" "encoding/json" "os" "path/filepath" "github.com/0chain/gosdk/core/encryption" "github.com/0chain/gosdk/zboxcore/marker" - "github.com/0chain/gosdk/zboxcore/sdk" ) func getZcnWorkDir() (string, error) { @@ -57,9 +57,17 @@ func getLookupHash(allocationID, path string) string { return encryption.Hash(allocationID + ":" + path) } -func getAuthTicket(authTicket *C.char) (*marker.AuthTicket, string, error) { +func decodeAuthTicket(authTicket *C.char) (*marker.AuthTicket, string, error) { at := C.GoString(authTicket) - t, err := sdk.InitAuthTicket(at).Unmarshall() + buf, err := base64.StdEncoding.DecodeString(at) + if err != nil { + return nil, at, err + } + t := &marker.AuthTicket{} + err = json.Unmarshal(buf, t) + if err != nil { + return nil, at, err + } return t, at, err } diff --git a/winsdk/sdk.go b/winsdk/sdk.go index 3a55576aa..667da05a3 100644 --- a/winsdk/sdk.go +++ b/winsdk/sdk.go @@ -37,6 +37,11 @@ func main() { // //export SetLogFile func SetLogFile(file *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() f, err := os.OpenFile(C.GoString(file), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { @@ -81,6 +86,11 @@ func SetLogFile(file *C.char) *C.char { // //export InitSDKs func InitSDKs(configJson *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() l.Logger.Info("Start InitSDKs") @@ -146,7 +156,11 @@ func InitSDKs(configJson *C.char) *C.char { // //export InitWallet func InitWallet(clientJson *C.char) *C.char { - + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() l.Logger.Info("Start InitStorageSDK") clientJs := C.GoString(clientJson) @@ -188,6 +202,11 @@ var ErrInvalidSignatureScheme = errors.New("invalid_signature_scheme") // //export SignRequest func SignRequest(privateKey, signatureScheme, data *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() key := C.GoString(privateKey) scheme := C.GoString(signatureScheme) d := C.GoString(data) @@ -209,7 +228,11 @@ func SignRequest(privateKey, signatureScheme, data *C.char) *C.char { // //export VerifySignature func VerifySignature(publicKey, signatureScheme string, data string, signature string) *C.char { - + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() hash := encryption.Hash(data) signScheme := zcncrypto.NewSignatureScheme(signatureScheme) @@ -233,6 +256,11 @@ func VerifySignature(publicKey, signatureScheme string, data string, signature s // //export CryptoJsEncrypt func CryptoJsEncrypt(passphrase, message *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() pass := C.GoString(passphrase) msg := C.GoString(message) @@ -249,6 +277,11 @@ func CryptoJsEncrypt(passphrase, message *C.char) *C.char { // //export CryptoJsDecrypt func CryptoJsDecrypt(passphrase, encryptedMessage *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() pass := C.GoString(passphrase) msg := C.GoString(encryptedMessage) @@ -265,6 +298,11 @@ func CryptoJsDecrypt(passphrase, encryptedMessage *C.char) *C.char { // //export GetPublicEncryptionKey func GetPublicEncryptionKey(mnemonics *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() m := C.GoString(mnemonics) return WithJSON(zcncore.GetPublicEncryptionKey(m)) } @@ -281,6 +319,11 @@ func GetPublicEncryptionKey(mnemonics *C.char) *C.char { // //export GetLookupHash func GetLookupHash(allocationID *C.char, path *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() hash := getLookupHash(C.GoString(allocationID), C.GoString(path)) return WithJSON(hash, nil) } @@ -296,6 +339,11 @@ func GetLookupHash(allocationID *C.char, path *C.char) *C.char { // //export SetFFmpeg func SetFFmpeg(fullFileName *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() f := C.GoString(fullFileName) _, err := os.Stat(f) @@ -317,6 +365,11 @@ func SetFFmpeg(fullFileName *C.char) *C.char { // //export GetFileContentType func GetFileContentType(file *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() f, err := os.Open(C.GoString(file)) if err != nil { log.Error("win: ", err) diff --git a/winsdk/storage.go b/winsdk/storage.go index f8bbc55f3..fc5bcd5f2 100644 --- a/winsdk/storage.go +++ b/winsdk/storage.go @@ -15,6 +15,7 @@ import ( "time" "github.com/0chain/gosdk/core/common" + "github.com/0chain/gosdk/zboxcore/marker" "github.com/0chain/gosdk/zboxcore/sdk" ) @@ -28,6 +29,12 @@ import ( // //export GetFileStats func GetFileStats(allocationID, remotePath *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() + allocID := C.GoString(allocationID) path := C.GoString(remotePath) @@ -69,6 +76,12 @@ func GetFileStats(allocationID, remotePath *C.char) *C.char { // //export Delete func Delete(allocationID, path *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() + allocID := C.GoString(allocationID) alloc, err := getAllocation(allocID) @@ -108,6 +121,11 @@ type MultiOperationOption struct { // //export MultiOperation func MultiOperation(_allocationID, _jsonMultiOperationOptions *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() allocationID := C.GoString(_allocationID) jsonMultiOperationOptions := C.GoString(_jsonMultiOperationOptions) if allocationID == "" { @@ -144,6 +162,12 @@ func MultiOperation(_allocationID, _jsonMultiOperationOptions *C.char) *C.char { } // GetFileMeta get metadata by path +// ## Inputs +// - allocationID +// - path +// - authTicket +// +// ## Outputs // // return // { @@ -152,19 +176,43 @@ func MultiOperation(_allocationID, _jsonMultiOperationOptions *C.char) *C.char { // } // //export GetFileMeta -func GetFileMeta(allocationID, path *C.char) *C.char { +func GetFileMeta(allocationID, path, authTicket *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() allocID := C.GoString(allocationID) - alloc, err := getAllocation(allocID) + t := C.GoString(authTicket) + + var ticket *marker.AuthTicket + + var alloc *sdk.Allocation + var err error + isShared := len(t) > 0 + if isShared { + alloc, ticket, err = getAllocationWith(t) + } else { + alloc, err = getAllocation(allocID) + } + if err != nil { + log.Error("win: ", err) return WithJSON(nil, err) } s := C.GoString(path) - f, err := alloc.GetFileMeta(s) + var f *sdk.ConsolidatedFileMeta + if isShared { + f, err = alloc.GetFileMetaFromAuthTicket(t, ticket.FilePathHash) + } else { + f, err = alloc.GetFileMeta(s) + } if err != nil { + log.Error("win: ", err, " authTicket=", t, " path=", s) return WithJSON(nil, err) } @@ -185,7 +233,7 @@ func GetFileMeta(allocationID, path *C.char) *C.char { func BulkUpload(allocationID, files *C.char) *C.char { defer func() { if r := recover(); r != nil { - log.Error("win: ", r) + log.Error("win: crash ", r) } }() allocID := C.GoString(allocationID) @@ -255,6 +303,11 @@ func BulkUpload(allocationID, files *C.char) *C.char { // //export GetUploadStatus func GetUploadStatus(lookupHash *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() h := C.GoString(lookupHash) h2, ok := transcodeFiles.Get(h) @@ -305,6 +358,11 @@ func SetNumBlockDownloads(num int) { // //export DownloadFile func DownloadFile(allocationID, localPath, remotePath *C.char, verifyDownload, isFinal bool) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() allocID := C.GoString(allocationID) alloc, err := getAllocation(allocID) @@ -341,7 +399,7 @@ func DownloadFile(allocationID, localPath, remotePath *C.char, verifyDownload, i func DownloadThumbnail(allocationID, localPath, remotePath *C.char, verifyDownload bool, isFinal bool) *C.char { defer func() { if r := recover(); r != nil { - log.Error("win: DownloadThumbnail ", r) + log.Error("win: crash ", r) } }() allocID := C.GoString(allocationID) @@ -380,8 +438,13 @@ func DownloadThumbnail(allocationID, localPath, remotePath *C.char, verifyDownlo // //export DownloadSharedFile func DownloadSharedFile(localPath, authTicket *C.char, verifyDownload bool, isFinal bool) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() info := &SharedInfo{} - t, at, err := getAuthTicket(authTicket) + t, at, err := decodeAuthTicket(authTicket) if err != nil { return WithJSON(info, err) } @@ -420,9 +483,15 @@ func DownloadSharedFile(localPath, authTicket *C.char, verifyDownload bool, isFi // //export DownloadSharedThumbnail func DownloadSharedThumbnail(localPath, authTicket *C.char, verifyDownload bool, isFinal bool) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() info := &SharedInfo{} - t, at, err := getAuthTicket(authTicket) + t, at, err := decodeAuthTicket(authTicket) if err != nil { + log.Error("win: ", err, " authTicket=", at) return WithJSON(info, err) } info.AllocationID = t.AllocationID @@ -430,6 +499,7 @@ func DownloadSharedThumbnail(localPath, authTicket *C.char, verifyDownload bool, alloc, err := getAllocation(t.AllocationID) if err != nil { + log.Error("win: ", err, " authTicket=", at) return WithJSON(info, err) } @@ -437,6 +507,7 @@ func DownloadSharedThumbnail(localPath, authTicket *C.char, verifyDownload bool, err = alloc.DownloadThumbnailFromAuthTicket(C.GoString(localPath), at, t.FilePathHash, t.FileName, verifyDownload, statusBar, isFinal) if err != nil { + log.Error("win: ", err, " authTicket=", at, " lookuphash=", t.FilePathHash) return WithJSON(info, err) } @@ -465,6 +536,12 @@ func DownloadSharedThumbnail(localPath, authTicket *C.char, verifyDownload bool, func DownloadFileBlocks(allocationID, localPath, remotePath *C.char, startBlock int64, endBlock int64, numBlocks int, verifyDownload bool, isFinal bool) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() + allocID := C.GoString(allocationID) alloc, err := getAllocation(allocID) @@ -487,7 +564,6 @@ func DownloadFileBlocks(allocationID, // DownloadSharedFileBlocks - downalod shared file blocks // ## Inputs -// - allocationID // - localPath // - remotePath // - startBlock @@ -504,12 +580,16 @@ func DownloadFileBlocks(allocationID, // } // //export DownloadSharedFileBlocks -func DownloadSharedFileBlocks(allocationID, - localPath, authTicket *C.char, startBlock int64, endBlock int64, +func DownloadSharedFileBlocks(localPath, authTicket *C.char, startBlock int64, endBlock int64, numBlocks int, verifyDownload bool, isFinal bool) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() info := &SharedInfo{} - t, at, err := getAuthTicket(authTicket) + t, at, err := decodeAuthTicket(authTicket) if err != nil { return WithJSON(info, err) } @@ -544,7 +624,11 @@ func DownloadSharedFileBlocks(allocationID, // //export GetDownloadStatus func GetDownloadStatus(key *C.char, isThumbnail bool) *C.char { - + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() k := C.GoString(key) if isThumbnail { k += ":thumbnail" @@ -577,7 +661,13 @@ func GetDownloadStatus(key *C.char, isThumbnail bool) *C.char { // //export CreateAuthTicket func CreateAuthTicket(allocationID, remotePath, refereeClientID, refereePublicEncryptionKey, availableAfter *C.char, expirationSeconds int64) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() alloc, err := getAllocation(C.GoString(allocationID)) + if err != nil { log.Error("win: ", err) return WithJSON(nil, err) @@ -628,6 +718,11 @@ func CreateAuthTicket(allocationID, remotePath, refereeClientID, refereePublicEn // //export DeleteAuthTicket func DeleteAuthTicket(allocationID, remotePath, refereeClientID *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() alloc, err := getAllocation(C.GoString(allocationID)) if err != nil { log.Error("win: ", err) diff --git a/winsdk/zboxapi.go b/winsdk/zboxapi.go index d41c8d874..0a8c5a628 100644 --- a/winsdk/zboxapi.go +++ b/winsdk/zboxapi.go @@ -29,6 +29,11 @@ var ( // //export InitZBox func InitZBox(zboxHost, zboxAppType *C.char) { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() if zboxApiClient == nil { zboxApiClient = zboxapi.NewClient() } @@ -53,6 +58,11 @@ func InitZBox(zboxHost, zboxAppType *C.char) { // //export SetZBoxWallet func SetZBoxWallet(clientID, clientPrivateKey, clientPublicKey *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() if zboxApiClient == nil { return WithJSON(false, ErrZboxApiNotInitialized) } @@ -78,6 +88,11 @@ func SetZBoxWallet(clientID, clientPrivateKey, clientPublicKey *C.char) *C.char // //export GetCsrfToken func GetCsrfToken() *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() if zboxApiClient == nil { return WithJSON(0, ErrZboxApiNotInitialized) } @@ -95,6 +110,11 @@ func GetCsrfToken() *C.char { // //export CreateJwtSession func CreateJwtSession(phoneNumber *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() if zboxApiClient == nil { return WithJSON(0, ErrZboxApiNotInitialized) } @@ -111,6 +131,11 @@ func CreateJwtSession(phoneNumber *C.char) *C.char { // //export CreateJwtToken func CreateJwtToken(phoneNumber *C.char, jwtSessionID int64, otp *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() if zboxApiClient == nil { return WithJSON("", ErrZboxApiNotInitialized) } @@ -127,6 +152,11 @@ func CreateJwtToken(phoneNumber *C.char, jwtSessionID int64, otp *C.char) *C.cha // //export RefreshJwtToken func RefreshJwtToken(phoneNumber, token *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() if zboxApiClient == nil { return WithJSON("", ErrZboxApiNotInitialized) } @@ -145,6 +175,11 @@ func RefreshJwtToken(phoneNumber, token *C.char) *C.char { // //export GetFreeMarker func GetFreeMarker(phoneNumber, token *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() marker, err := zboxApiClient.GetFreeStorage(context.TODO(), C.GoString(phoneNumber), C.GoString(token)) if err != nil { log.Error("win: ", err) @@ -169,6 +204,11 @@ func GetFreeMarker(phoneNumber, token *C.char) *C.char { // //export CreateSharedInfo func CreateSharedInfo(phoneNumber, token, sharedInfo *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() js := C.GoString(sharedInfo) s := zboxapi.SharedInfo{} @@ -203,6 +243,11 @@ func CreateSharedInfo(phoneNumber, token, sharedInfo *C.char) *C.char { // //export DeleteSharedInfo func DeleteSharedInfo(phoneNumber, token, authTicket, lookupHash *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() err := zboxApiClient.DeleteSharedInfo(context.TODO(), C.GoString(phoneNumber), C.GoString(token), C.GoString(authTicket), C.GoString(lookupHash)) if err != nil { log.Error("win: ", err) @@ -226,6 +271,11 @@ func DeleteSharedInfo(phoneNumber, token, authTicket, lookupHash *C.char) *C.cha // //export GetSharedByMe func GetSharedByMe(phoneNumber, token *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() list, err := zboxApiClient.GetSharedByMe(context.TODO(), C.GoString(phoneNumber), C.GoString(token)) if err != nil { log.Error("win: ", err) @@ -249,6 +299,11 @@ func GetSharedByMe(phoneNumber, token *C.char) *C.char { // //export GetSharedByPublic func GetSharedByPublic(phoneNumber, token *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() list, err := zboxApiClient.GetSharedByPublic(context.TODO(), C.GoString(phoneNumber), C.GoString(token)) if err != nil { log.Error("win: ", err) @@ -272,6 +327,11 @@ func GetSharedByPublic(phoneNumber, token *C.char) *C.char { // //export GetSharedToMe func GetSharedToMe(phoneNumber, token *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() list, err := zboxApiClient.GetSharedToMe(context.TODO(), C.GoString(phoneNumber), C.GoString(token)) if err != nil { log.Error("win: ", err) diff --git a/zboxapi/sdk.go b/zboxapi/sdk.go index c091df59a..dee51560a 100644 --- a/zboxapi/sdk.go +++ b/zboxapi/sdk.go @@ -71,6 +71,8 @@ func (c *Client) SetWallet(clientID, clientPrivateKey, clientPublicKey string) { } func (c *Client) parseResponse(resp *http.Response, respBody []byte, result interface{}) error { + + log.Info("zboxapi: ", resp.StatusCode, " ", string(respBody)) if resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusCreated { if err := json.Unmarshal(respBody, result); err != nil { return thrown.Throw(ErrInvalidJsonResponse, string(respBody)) @@ -262,7 +264,6 @@ func (c *Client) GetFreeStorage(ctx context.Context, phoneNumber, token string) return err } - log.Info("zboxapi: ", string(respBody)) return c.parseResponse(resp, respBody, result) }) @@ -302,7 +303,6 @@ func (c *Client) CreateSharedInfo(ctx context.Context, phoneNumber, token string return err } - log.Info("zboxapi: ", string(respBody)) return c.parseResponse(resp, respBody, &result) }) @@ -335,7 +335,6 @@ func (c *Client) DeleteSharedInfo(ctx context.Context, phoneNumber, token, authT return err } - log.Info("zboxapi: ", string(respBody)) return c.parseResponse(resp, respBody, &result) }) @@ -381,8 +380,6 @@ func (c *Client) getShared(ctx context.Context, phoneNumber, token string, isPri return err } - log.Info("zboxapi: ", string(respBody)) - return c.parseResponse(resp, respBody, &result) }) @@ -416,8 +413,6 @@ func (c *Client) GetSharedToMe(ctx context.Context, phoneNumber, token string) ( return err } - log.Info("zboxapi: ", string(respBody)) - return c.parseResponse(resp, respBody, &result) }) diff --git a/zboxcore/fileref/fileref.go b/zboxcore/fileref/fileref.go index eae303752..df821c5f0 100644 --- a/zboxcore/fileref/fileref.go +++ b/zboxcore/fileref/fileref.go @@ -60,26 +60,28 @@ type RefEntity interface { } type Ref struct { - Type string `json:"type" mapstructure:"type"` - AllocationID string `json:"allocation_id" mapstructure:"allocation_id"` - Name string `json:"name" mapstructure:"name"` - Path string `json:"path" mapstructure:"path"` - Size int64 `json:"size" mapstructure:"size"` - ActualSize int64 `json:"actual_file_size" mapstructure:"actual_file_size"` - Hash string `json:"hash" mapstructure:"hash"` - ChunkSize int64 `json:"chunk_size" mapstructure:"chunk_size"` - NumBlocks int64 `json:"num_of_blocks" mapstructure:"num_of_blocks"` - PathHash string `json:"path_hash" mapstructure:"path_hash"` - LookupHash string `json:"lookup_hash" mapstructure:"lookup_hash"` - FileID string `json:"file_id" mapstructure:"file_id"` - FileMetaHash string `json:"file_meta_hash" mapstructure:"file_meta_hash"` - ThumbnailHash string `json:"thumbnail_hash" mapstructure:"thumbnail_hash"` - ThumbnailSize int64 `json:"thumbnail_size" mapstructure:"thumbnail_size"` - HashToBeComputed bool - ChildrenLoaded bool - Children []RefEntity `json:"-" mapstructure:"-"` - CreatedAt common.Timestamp `json:"created_at" mapstructure:"created_at"` - UpdatedAt common.Timestamp `json:"updated_at" mapstructure:"updated_at"` + Type string `json:"type" mapstructure:"type"` + AllocationID string `json:"allocation_id" mapstructure:"allocation_id"` + Name string `json:"name" mapstructure:"name"` + Path string `json:"path" mapstructure:"path"` + Size int64 `json:"size" mapstructure:"size"` + ActualSize int64 `json:"actual_file_size" mapstructure:"actual_file_size"` + Hash string `json:"hash" mapstructure:"hash"` + ChunkSize int64 `json:"chunk_size" mapstructure:"chunk_size"` + NumBlocks int64 `json:"num_of_blocks" mapstructure:"num_of_blocks"` + PathHash string `json:"path_hash" mapstructure:"path_hash"` + LookupHash string `json:"lookup_hash" mapstructure:"lookup_hash"` + FileID string `json:"file_id" mapstructure:"file_id"` + FileMetaHash string `json:"file_meta_hash" mapstructure:"file_meta_hash"` + ThumbnailHash string `json:"thumbnail_hash" mapstructure:"thumbnail_hash"` + ThumbnailSize int64 `json:"thumbnail_size" mapstructure:"thumbnail_size"` + ActualThumbnailHash string `json:"actual_thumbnail_hash" mapstructure:"actual_thumbnail_hash"` + ActualThumbnailSize int64 `json:"actual_thumbnail_size" mapstructure:"actual_thumbnail_size"` + HashToBeComputed bool + ChildrenLoaded bool + Children []RefEntity `json:"-" mapstructure:"-"` + CreatedAt common.Timestamp `json:"created_at" mapstructure:"created_at"` + UpdatedAt common.Timestamp `json:"updated_at" mapstructure:"updated_at"` } func GetReferenceLookup(allocationID string, path string) string { diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 252538f17..704a72ddc 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -104,7 +104,11 @@ type ConsolidatedFileMeta struct { ActualFileSize int64 ActualNumBlocks int64 EncryptedKey string - Collaborators []fileref.Collaborator + + ActualThumbnailSize int64 + ActualThumbnailHash string + + Collaborators []fileref.Collaborator } type AllocationStats struct { @@ -1489,6 +1493,8 @@ func (a *Allocation) GetFileMeta(path string) (*ConsolidatedFileMeta, error) { result.EncryptedKey = ref.EncryptedKey result.Collaborators = ref.Collaborators result.ActualFileSize = ref.ActualFileSize + result.ActualThumbnailHash = ref.ActualThumbnailHash + result.ActualThumbnailSize = ref.ActualThumbnailSize if result.ActualFileSize > 0 { result.ActualNumBlocks = (ref.ActualFileSize + CHUNK_SIZE - 1) / CHUNK_SIZE } @@ -1544,6 +1550,8 @@ func (a *Allocation) GetFileMetaFromAuthTicket(authTicket string, lookupHash str result.Size = ref.Size result.NumBlocks = ref.NumBlocks result.ActualFileSize = ref.ActualFileSize + result.ActualThumbnailHash = ref.ActualThumbnailHash + result.ActualThumbnailSize = ref.ActualThumbnailSize if result.ActualFileSize > 0 { result.ActualNumBlocks = (result.ActualFileSize + CHUNK_SIZE - 1) / CHUNK_SIZE } diff --git a/zboxcore/sdk/listworker.go b/zboxcore/sdk/listworker.go index b803a81c4..3c1c063e0 100644 --- a/zboxcore/sdk/listworker.go +++ b/zboxcore/sdk/listworker.go @@ -44,20 +44,22 @@ type listResponse struct { } type ListResult struct { - Name string `json:"name"` - Path string `json:"path,omitempty"` - Type string `json:"type"` - Size int64 `json:"size"` - Hash string `json:"hash,omitempty"` - FileMetaHash string `json:"file_meta_hash,omitempty"` - MimeType string `json:"mimetype,omitempty"` - NumBlocks int64 `json:"num_blocks"` - LookupHash string `json:"lookup_hash"` - EncryptionKey string `json:"encryption_key"` - ActualSize int64 `json:"actual_size"` - ActualNumBlocks int64 `json:"actual_num_blocks"` - ThumbnailHash string `json:"thumbnail_hash"` - ThumbnailSize int64 `json:"thumbnail_size"` + Name string `json:"name"` + Path string `json:"path,omitempty"` + Type string `json:"type"` + Size int64 `json:"size"` + Hash string `json:"hash,omitempty"` + FileMetaHash string `json:"file_meta_hash,omitempty"` + MimeType string `json:"mimetype,omitempty"` + NumBlocks int64 `json:"num_blocks"` + LookupHash string `json:"lookup_hash"` + EncryptionKey string `json:"encryption_key"` + ActualSize int64 `json:"actual_size"` + ActualNumBlocks int64 `json:"actual_num_blocks"` + ThumbnailHash string `json:"thumbnail_hash"` + ThumbnailSize int64 `json:"thumbnail_size"` + ActualThumbnailHash string `json:"actual_thumbnail_hash"` + ActualThumbnailSize int64 `json:"actual_thumbnail_size"` CreatedAt common.Timestamp `json:"created_at"` UpdatedAt common.Timestamp `json:"updated_at"` @@ -220,6 +222,8 @@ func (req *ListRequest) GetListFromBlobbers() (*ListResult, error) { result.ActualSize = ti.ref.ActualSize result.ThumbnailHash = ti.ref.ThumbnailHash result.ThumbnailSize = ti.ref.ThumbnailSize + result.ActualThumbnailHash = ti.ref.ActualThumbnailHash + result.ActualThumbnailSize = ti.ref.ActualThumbnailSize if ti.ref.ActualSize > 0 { result.ActualNumBlocks = (ti.ref.ActualSize + CHUNK_SIZE - 1) / CHUNK_SIZE @@ -279,6 +283,8 @@ func (lr *ListResult) populateChildren(children []fileref.RefEntity, childResult childResult.ActualSize = (child.(*fileref.FileRef)).ActualFileSize childResult.ThumbnailHash = (child.(*fileref.FileRef)).ThumbnailHash childResult.ThumbnailSize = (child.(*fileref.FileRef)).ThumbnailSize + childResult.ActualThumbnailHash = (child.(*fileref.FileRef)).ActualThumbnailHash + childResult.ActualThumbnailSize = (child.(*fileref.FileRef)).ActualThumbnailSize } else { childResult.ActualSize = (child.(*fileref.Ref)).ActualSize } From 5a85b2b91102426b3e1234820b69b9bd472c729d Mon Sep 17 00:00:00 2001 From: Lz Date: Tue, 31 Oct 2023 14:22:18 +0800 Subject: [PATCH 075/134] feat(winsdk): added GetWalletBalance (#1267) --- winsdk/wallet.go | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/winsdk/wallet.go b/winsdk/wallet.go index e9106ef09..2c5eaeec6 100644 --- a/winsdk/wallet.go +++ b/winsdk/wallet.go @@ -73,3 +73,24 @@ func RecoverWallet(mnemonic *C.char) *C.char { return WithJSON(w, nil) } + +// GetWalletBalance - get wallet balance +// ## Inputs +// - clientID +// ## Outputs +// +// { +// "error":"", +// "result":\"0.00\"", +// } +// +//export GetWalletBalance +func GetWalletBalance(clientID *C.char) *C.char { + b, err := zcncore.GetWalletBalance(C.GoString(clientID)) + if err != nil { + log.Error("win: ", err) + return WithJSON(0, err) + } + + return WithJSON(b.ToToken()) +} From 201b8bdc4f94b2aeb5eda3ce16f91b4327023654 Mon Sep 17 00:00:00 2001 From: shahnawaz-creator <117025384+shahnawaz-creator@users.noreply.github.com> Date: Thu, 2 Nov 2023 00:07:37 +0530 Subject: [PATCH 076/134] enabled gosdk update for sprint branches (#1268) --- .github/workflows/sdk-release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/sdk-release.yml b/.github/workflows/sdk-release.yml index a1db6e2b4..43c3f9d13 100644 --- a/.github/workflows/sdk-release.yml +++ b/.github/workflows/sdk-release.yml @@ -6,7 +6,7 @@ concurrency: on: push: - branches: [ master, staging, qa ] + branches: [ master, staging, sprint-* ] tags: - 'v*.*.*' pull_request: From a356c00d06245156d2c7fe7c047a2e5812e30760 Mon Sep 17 00:00:00 2001 From: shahnawaz-creator <117025384+shahnawaz-creator@users.noreply.github.com> Date: Thu, 2 Nov 2023 00:25:01 +0530 Subject: [PATCH 077/134] Revert "enabled gosdk update for sprint branches (#1268)" (#1269) This reverts commit 201b8bdc4f94b2aeb5eda3ce16f91b4327023654. --- .github/workflows/sdk-release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/sdk-release.yml b/.github/workflows/sdk-release.yml index 43c3f9d13..a1db6e2b4 100644 --- a/.github/workflows/sdk-release.yml +++ b/.github/workflows/sdk-release.yml @@ -6,7 +6,7 @@ concurrency: on: push: - branches: [ master, staging, sprint-* ] + branches: [ master, staging, qa ] tags: - 'v*.*.*' pull_request: From d3c786ac98c706178ad4613ba6bbb70fe565107a Mon Sep 17 00:00:00 2001 From: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Date: Sat, 4 Nov 2023 20:30:15 +0530 Subject: [PATCH 078/134] fix in progress callback (#1270) --- zboxcore/sdk/chunked_upload.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zboxcore/sdk/chunked_upload.go b/zboxcore/sdk/chunked_upload.go index 795e1a4cd..edb45e995 100644 --- a/zboxcore/sdk/chunked_upload.go +++ b/zboxcore/sdk/chunked_upload.go @@ -463,7 +463,7 @@ func (su *ChunkedUpload) process() error { // last chunk might 0 with io.EOF // https://stackoverflow.com/questions/41208359/how-to-test-eof-on-io-reader-in-go - if chunks.totalReadSize > 0 && chunks.chunkEndIndex > su.progress.ChunkIndex { + if chunks.totalReadSize > 0 && chunks.chunkEndIndex >= su.progress.ChunkIndex { if su.statusCallback != nil { su.statusCallback.InProgress(su.allocationObj.ID, su.fileMeta.RemotePath, su.opCode, int(su.progress.UploadLength)-alreadyUploadedData, nil) } From f7075dc7d69f210a1bccadc4bf2d976244aec14e Mon Sep 17 00:00:00 2001 From: Jayash Satolia <73050737+Jayashsatolia403@users.noreply.github.com> Date: Wed, 8 Nov 2023 03:07:32 +0530 Subject: [PATCH 079/134] Cleanup update terms from update allocation (#1274) --- mobilesdk/sdk/sdk.go | 2 +- wasmsdk/README.md | 4 ++-- wasmsdk/allocation.go | 15 +++++---------- zboxcore/sdk/allocation.go | 3 +-- zboxcore/sdk/sdk.go | 4 ---- 5 files changed, 9 insertions(+), 19 deletions(-) diff --git a/mobilesdk/sdk/sdk.go b/mobilesdk/sdk/sdk.go index 98a459286..3a18186f0 100644 --- a/mobilesdk/sdk/sdk.go +++ b/mobilesdk/sdk/sdk.go @@ -346,7 +346,7 @@ func (s *StorageSDK) UpdateAllocation(size int64, extend bool, allocationID stri return "", errors.Errorf("int64 overflow in lock") } - hash, _, err = sdk.UpdateAllocation(size, extend, allocationID, lock, true, "", "", false, &sdk.FileOptionsParameters{}) + hash, _, err = sdk.UpdateAllocation(size, extend, allocationID, lock, "", "", false, &sdk.FileOptionsParameters{}) return hash, err } diff --git a/wasmsdk/README.md b/wasmsdk/README.md index a1dc459c2..7f7adbaec 100644 --- a/wasmsdk/README.md +++ b/wasmsdk/README.md @@ -223,7 +223,7 @@ updates allocation settings **Input**: -> allocationId string, name string,size int64, extend bool,lock int64,setImmutable, updateTerms bool,addBlobberId, removeBlobberId string, setThirdPartyExtendable bool +> allocationId string, name string,size int64, extend bool,lock int64,setImmutable,addBlobberId, removeBlobberId string, setThirdPartyExtendable bool **Output**: @@ -595,7 +595,7 @@ create folder from blobbers **Input**: -> allocationID string, size int, extend bool, updateTerms bool, addBlobberId string, removeBlobberId string +> allocationID string, size int, extend bool, addBlobberId string, removeBlobberId string **Output**: diff --git a/wasmsdk/allocation.go b/wasmsdk/allocation.go index f102af7cf..276ccd3dc 100644 --- a/wasmsdk/allocation.go +++ b/wasmsdk/allocation.go @@ -76,8 +76,8 @@ func createAllocation(datashards, parityshards int, size int64, Min: uint64(minWritePrice), Max: uint64(maxWritePrice), }, - Lock: uint64(lock), - BlobberIds: blobberIds, + Lock: uint64(lock), + BlobberIds: blobberIds, ThirdPartyExtendable: setThirdPartyExtendable, } @@ -121,7 +121,6 @@ func UpdateForbidAllocation(allocationID string, forbidupload, forbiddelete, for false, //extend, allocationID, // allocID, 0, //lock, - false, //updateTerms, "", //addBlobberId, "", //removeBlobberId, false, //thirdPartyExtendable, @@ -146,7 +145,6 @@ func freezeAllocation(allocationID string) (string, error) { false, //extend, allocationID, // allocID, 0, //lock, - false, //updateTerms, "", //addBlobberId, "", //removeBlobberId, false, //thirdPartyExtendable, @@ -182,7 +180,6 @@ func updateAllocationWithRepair(allocationID string, size int64, extend bool, lock int64, - updateTerms bool, addBlobberId, removeBlobberId string) (string, error) { sdk.SetWasm() allocationObj, err := sdk.GetAllocation(allocationID) @@ -194,7 +191,7 @@ func updateAllocationWithRepair(allocationID string, statusBar := &StatusBar{wg: wg, isRepair: true} wg.Add(1) - hash, err := allocationObj.UpdateWithRepair(size, extend, uint64(lock), updateTerms, addBlobberId, removeBlobberId, false, &sdk.FileOptionsParameters{}, statusBar) + hash, err := allocationObj.UpdateWithRepair(size, extend, uint64(lock), addBlobberId, removeBlobberId, false, &sdk.FileOptionsParameters{}, statusBar) if err == nil { clearAllocation(allocationID) } @@ -205,9 +202,8 @@ func updateAllocationWithRepair(allocationID string, func updateAllocation(allocationID string, size int64, extend bool, lock int64, - updateTerms bool, addBlobberId, removeBlobberId string, setThirdPartyExtendable bool) (string, error) { - hash, _, err := sdk.UpdateAllocation(size, extend, allocationID, uint64(lock), updateTerms, addBlobberId, removeBlobberId, setThirdPartyExtendable, &sdk.FileOptionsParameters{}) + hash, _, err := sdk.UpdateAllocation(size, extend, allocationID, uint64(lock), addBlobberId, removeBlobberId, setThirdPartyExtendable, &sdk.FileOptionsParameters{}) if err == nil { clearAllocation(allocationID) @@ -236,9 +232,8 @@ func getUpdateAllocationMinLock( allocationID string, size int64, extend bool, - updateTerms bool, addBlobberId, removeBlobberId string) (int64, error) { - return sdk.GetUpdateAllocationMinLock(allocationID, size, extend, updateTerms, addBlobberId, removeBlobberId) + return sdk.GetUpdateAllocationMinLock(allocationID, size, extend, addBlobberId, removeBlobberId) } func getRemoteFileMap(allocationID string) ([]*fileResp, error) { diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 704a72ddc..2c0b25422 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -2376,7 +2376,6 @@ func (a *Allocation) UpdateWithRepair( size int64, extend bool, lock uint64, - updateTerms bool, addBlobberId, removeBlobberId string, setThirdPartyExtendable bool, fileOptionsParams *FileOptionsParameters, statusCB StatusCallback, @@ -2386,7 +2385,7 @@ func (a *Allocation) UpdateWithRepair( } l.Logger.Info("Updating allocation") - hash, _, err := UpdateAllocation(size, extend, a.ID, lock, updateTerms, addBlobberId, removeBlobberId, setThirdPartyExtendable, fileOptionsParams) + hash, _, err := UpdateAllocation(size, extend, a.ID, lock, addBlobberId, removeBlobberId, setThirdPartyExtendable, fileOptionsParams) if err != nil { return "", err } diff --git a/zboxcore/sdk/sdk.go b/zboxcore/sdk/sdk.go index 2174b4b03..9783043e1 100644 --- a/zboxcore/sdk/sdk.go +++ b/zboxcore/sdk/sdk.go @@ -1185,7 +1185,6 @@ func UpdateAllocation( extend bool, allocationID string, lock uint64, - updateTerms bool, addBlobberId, removeBlobberId string, setThirdPartyExtendable bool, fileOptionsParams *FileOptionsParameters, ) (hash string, nonce int64, err error) { @@ -1209,7 +1208,6 @@ func UpdateAllocation( updateAllocationRequest["id"] = allocationID updateAllocationRequest["size"] = size updateAllocationRequest["extend"] = extend - updateAllocationRequest["update_terms"] = updateTerms updateAllocationRequest["add_blobber_id"] = addBlobberId updateAllocationRequest["remove_blobber_id"] = removeBlobberId updateAllocationRequest["set_third_party_extendable"] = setThirdPartyExtendable @@ -1600,7 +1598,6 @@ func GetUpdateAllocationMinLock( allocationID string, size int64, extend bool, - updateTerms bool, addBlobberId, removeBlobberId string) (int64, error) { updateAllocationRequest := make(map[string]interface{}) @@ -1609,7 +1606,6 @@ func GetUpdateAllocationMinLock( updateAllocationRequest["id"] = allocationID updateAllocationRequest["size"] = size updateAllocationRequest["extend"] = extend - updateAllocationRequest["update_terms"] = updateTerms updateAllocationRequest["add_blobber_id"] = addBlobberId updateAllocationRequest["remove_blobber_id"] = removeBlobberId From 7c8549873ea54630a113dfcc492d33f6b9fff0a1 Mon Sep 17 00:00:00 2001 From: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Date: Thu, 9 Nov 2023 20:55:15 +0530 Subject: [PATCH 080/134] Improve download performance (#1271) * improve download performance * add read buffer size * add hash option * fix lint test * set default to true * log for data * fix read --- zboxcore/sdk/blockdownloadworker.go | 59 +++++++++++++++++++++++++---- zboxcore/sdk/downloadworker.go | 2 +- zboxcore/sdk/sdk.go | 7 +++- zboxcore/zboxutil/transport.go | 2 + 4 files changed, 60 insertions(+), 10 deletions(-) diff --git a/zboxcore/sdk/blockdownloadworker.go b/zboxcore/sdk/blockdownloadworker.go index 5d496ad70..d79715cd7 100644 --- a/zboxcore/sdk/blockdownloadworker.go +++ b/zboxcore/sdk/blockdownloadworker.go @@ -4,8 +4,9 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" + "strconv" "sync" "time" @@ -151,11 +152,30 @@ func (req *BlockDownloadRequest) downloadBlobberBlock() { if resp.Body != nil { defer resp.Body.Close() } - + if req.chunkSize == 0 { + req.chunkSize = CHUNK_SIZE + } var rspData downloadBlock - respBody, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err + respLen := resp.Header.Get("Content-Length") + var respBody []byte + if respLen != "" { + len, err := strconv.Atoi(respLen) + zlogger.Logger.Info("respLen", len) + if err != nil { + zlogger.Logger.Error("respLen convert error: ", err) + return err + } + respBody, err = readBody(resp.Body, len) + if err != nil { + zlogger.Logger.Error("respBody read error: ", err) + return err + } + } else { + respBody, err = readBody(resp.Body, int(req.numBlocks)*req.chunkSize) + if err != nil { + zlogger.Logger.Error("respBody read error: ", err) + return err + } } if resp.StatusCode != http.StatusOK { zlogger.Logger.Debug(fmt.Sprintf("downloadBlobberBlock FAIL - blobberID: %v, clientID: %v, blockNum: %d, retry: %d, response: %v", req.blobber.ID, client.GetClientID(), header.BlockNum, retry, string(respBody))) @@ -166,9 +186,14 @@ func (req *BlockDownloadRequest) downloadBlobberBlock() { } dR := downloadResponse{} - err = json.Unmarshal(respBody, &dR) - if err != nil { - return err + contentType := resp.Header.Get("Content-Type") + if contentType == "application/json" { + err = json.Unmarshal(respBody, &dR) + if err != nil { + return err + } + } else { + dR.Data = respBody } if req.contentMode == DOWNLOAD_CONTENT_FULL && req.shouldVerify { @@ -232,3 +257,21 @@ func (req *BlockDownloadRequest) downloadBlobberBlock() { func AddBlockDownloadReq(req *BlockDownloadRequest) { downloadBlockChan[req.blobber.ID] <- req } + +func readBody(r io.Reader, size int) ([]byte, error) { + b := make([]byte, 0, size) + for { + if len(b) == cap(b) { + // Add more capacity (let append pick how much). + b = append(b, 0)[:len(b)] + } + n, err := r.Read(b[len(b):cap(b)]) + b = b[:len(b)+n] + if err != nil { + if err == io.EOF { + err = nil + } + return b, err + } + } +} diff --git a/zboxcore/sdk/downloadworker.go b/zboxcore/sdk/downloadworker.go index 05a39254d..99bf1bd57 100644 --- a/zboxcore/sdk/downloadworker.go +++ b/zboxcore/sdk/downloadworker.go @@ -415,7 +415,7 @@ func (req *DownloadRequest) processDownload(ctx context.Context) { } var actualFileHasher hash.Hash var isPREAndWholeFile bool - if !req.shouldVerify && (startBlock == 0 && endBlock == chunksPerShard) { + if !req.shouldVerify && (startBlock == 0 && endBlock == chunksPerShard) && shouldVerifyHash { actualFileHasher = sha3.New256() isPREAndWholeFile = true } diff --git a/zboxcore/sdk/sdk.go b/zboxcore/sdk/sdk.go index 9783043e1..c4464e312 100644 --- a/zboxcore/sdk/sdk.go +++ b/zboxcore/sdk/sdk.go @@ -55,6 +55,7 @@ type StatusCallback interface { var numBlockDownloads = 10 var sdkInitialized = false var networkWorkerTimerInHours = 1 +var shouldVerifyHash = true // GetVersion - returns version string func GetVersion() string { @@ -891,11 +892,15 @@ func GetAllocationUpdates(allocation *Allocation) error { } func SetNumBlockDownloads(num int) { - if num > 0 && num <= 100 { + if num > 0 && num <= 500 { numBlockDownloads = num } } +func SetVerifyHash(verify bool) { + shouldVerifyHash = verify +} + func GetAllocations() ([]*Allocation, error) { return GetAllocationsForClient(client.GetClientID()) } diff --git a/zboxcore/zboxutil/transport.go b/zboxcore/zboxutil/transport.go index 829c2888a..0a2bf81be 100644 --- a/zboxcore/zboxutil/transport.go +++ b/zboxcore/zboxutil/transport.go @@ -21,4 +21,6 @@ var DefaultTransport = &http.Transport{ TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, MaxIdleConnsPerHost: 100, + ReadBufferSize: 34 * 1024 * 1024, + WriteBufferSize: 34 * 1024 * 1024, } From f3a75f7991a267df64d125b3c51abde6bf467498 Mon Sep 17 00:00:00 2001 From: Yaroslav Svitlytskyi <53532703+YarikRevich@users.noreply.github.com> Date: Fri, 10 Nov 2023 22:20:12 +0100 Subject: [PATCH 081/134] feature: add reset nonce for bridge (#1279) --- zcnbridge/bridge.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/zcnbridge/bridge.go b/zcnbridge/bridge.go index e66a61ae5..9bf79bf1a 100644 --- a/zcnbridge/bridge.go +++ b/zcnbridge/bridge.go @@ -463,6 +463,28 @@ func (b *BridgeClient) GetUserNonceMinted(ctx context.Context, rawEthereumAddres return nonce, err } +// ResetUserNonceMinted Resets nonce for a specified Ethereum address +func (b *BridgeClient) ResetUserNonceMinted(ctx context.Context) (*types.Transaction, error) { + bridgeInstance, transactOpts, err := b.prepareBridge(ctx, b.EthereumAddress, "resetUserNonceMinted") + if err != nil { + return nil, errors.Wrap(err, "failed to prepare bridge") + } + + tran, err := bridgeInstance.ResetUserNonceMinted(transactOpts) + if err != nil { + Logger.Error("ResetUserNonceMinted FAILED", zap.Error(err)) + msg := "failed to execute ResetUserNonceMinted call, ethereumAddress = %s" + return nil, errors.Wrapf(err, msg, b.EthereumAddress) + } + + Logger.Info( + "Posted ResetUserMintedNonce", + zap.String("ethereumWallet", b.EthereumAddress), + ) + + return tran, err +} + // MintWZCN Mint ZCN tokens on behalf of the 0ZCN client // payload: received from authorizers func (b *BridgeClient) MintWZCN(ctx context.Context, payload *ethereum.MintPayload) (*types.Transaction, error) { From 78290c5dbb9d21bc915a42f167b6a494565745e8 Mon Sep 17 00:00:00 2001 From: peterlimg <54137706+peterlimg@users.noreply.github.com> Date: Sun, 12 Nov 2023 01:25:26 +1100 Subject: [PATCH 082/134] Add registerAuthorizer to wasm (#1275) --- core/version/version.go | 2 +- wasmsdk/auth_txn.go | 55 ++++++++++++++++++++++++++++++++++++++++ wasmsdk/demo/index.html | 21 ++++++++++++++- wasmsdk/jsbridge/func.go | 15 ++++++----- wasmsdk/proxy.go | 8 +++--- 5 files changed, 90 insertions(+), 11 deletions(-) create mode 100644 wasmsdk/auth_txn.go diff --git a/core/version/version.go b/core/version/version.go index 4248cbdc4..b102958cb 100644 --- a/core/version/version.go +++ b/core/version/version.go @@ -2,5 +2,5 @@ //====== THIS IS AUTOGENERATED FILE. DO NOT MODIFY ======== package version -const VERSIONSTR = "v1.10.0-120-ga72a4ee1" +const VERSIONSTR = "v1.10.0-93-gf7075dc7" diff --git a/wasmsdk/auth_txn.go b/wasmsdk/auth_txn.go new file mode 100644 index 000000000..1530c862f --- /dev/null +++ b/wasmsdk/auth_txn.go @@ -0,0 +1,55 @@ +//go:build js && wasm +// +build js,wasm + +package main + +import ( + "fmt" + "syscall/js" + + "github.com/0chain/gosdk/core/sys" +) + +// Declare a type for the callback function +type AuthCallbackFunc func(msg string) string + +// Variable to store the callback function +var authCallback AuthCallbackFunc + +// Register the callback function +func registerAuthorizer(this js.Value, args []js.Value) interface{} { + // Store the callback function + authCallback = parseAuthorizerCallback(args[0]) + + sys.Authorize = func(msg string) (string, error) { + return authCallback(msg), nil + } + + return nil +} + +// Use the stored callback function +func callAuth(this js.Value, args []js.Value) interface{} { + fmt.Println("callAuth is called") + if len(args) == 0 { + return nil + } + + if authCallback != nil { + msg := args[0].String() + result, _ := sys.Authorize(msg) + fmt.Println("auth is called, result:", result) + return js.ValueOf(result) + } + + return nil +} + +// Parse the JavaScript callback function into Go AuthorizerCallback type +func parseAuthorizerCallback(jsCallback js.Value) AuthCallbackFunc { + return func(msg string) string { + // Call the JavaScript callback function from Go + result := jsCallback.Invoke(msg) + return result.String() + } +} diff --git a/wasmsdk/demo/index.html b/wasmsdk/demo/index.html index c00658fb9..64d16ecd1 100644 --- a/wasmsdk/demo/index.html +++ b/wasmsdk/demo/index.html @@ -159,6 +159,7 @@

please download zcn.wasm from https://github.com/0chain/gosdk/releases/lates +
@@ -276,7 +277,7 @@

please download zcn.wasm from https://github.com/0chain/gosdk/releases/lates alert(e) } }) - + let allocations = [] let blobbers = [] let files = [] @@ -898,5 +899,23 @@

please download zcn.wasm from https://github.com/0chain/gosdk/releases/lates } }) + onClick('btnRegAuth', async () => { + // Define the callback function in JavaScript + const authCallback = function (msg) { + return `Authorized: ${msg}`; + }; + + // Register the callback function from JavaScript to Go + const registerAuthorizer = goWasm.sdk.registerAuthorizer; + registerAuthorizer(authCallback); + + + // call the callAuth to see if the auth is set properly + // Use the stored callback function from Go + const message = "Hello, World!"; + const result = goWasm.sdk.callAuth(message); + console.log(result); // Output: "Authorized: Hello, World!" + }) + \ No newline at end of file diff --git a/wasmsdk/jsbridge/func.go b/wasmsdk/jsbridge/func.go index 7e520dd7d..cd29aabd9 100644 --- a/wasmsdk/jsbridge/func.go +++ b/wasmsdk/jsbridge/func.go @@ -31,15 +31,18 @@ func BindFunc(global js.Value, jsFuncName string, fn interface{}) error { func BindAsyncFuncs(global js.Value, fnList map[string]interface{}) { for jsFuncName, fn := range fnList { - jsFunc, err := promise(fn) + if jsFuncName == "registerAuthorizer" || jsFuncName == "callAuth" { + global.Set(jsFuncName, fn) + } else { + jsFunc, err := promise(fn) - if err != nil { - log.Println(jsFuncName, err) - } + if err != nil { + log.Println("bridge promise failed:", jsFuncName, err) + } - global.Set(jsFuncName, jsFunc) + global.Set(jsFuncName, jsFunc) + } } - } func BindFuncs(global js.Value, fnList map[string]interface{}) { diff --git a/wasmsdk/proxy.go b/wasmsdk/proxy.go index 24486694d..9e5dc98cc 100644 --- a/wasmsdk/proxy.go +++ b/wasmsdk/proxy.go @@ -242,9 +242,11 @@ func main() { "refreshJwtToken": refreshJwtToken, //split key - "splitKeys": splitKeys, - "setWalletInfo": setWalletInfo, - "setAuthUrl": setAuthUrl, + "splitKeys": splitKeys, + "setWalletInfo": setWalletInfo, + "setAuthUrl": setAuthUrl, + "registerAuthorizer": js.FuncOf(registerAuthorizer), + "callAuth": js.FuncOf(callAuth), }) fmt.Println("__wasm_initialized__ = true;") From 840f5ed483dca3fe056cb76c48f193716a7fbda6 Mon Sep 17 00:00:00 2001 From: Yury Date: Sat, 11 Nov 2023 16:26:04 +0200 Subject: [PATCH 083/134] Hotfix/parse hostname error (#1241) * Fix/remove path (#1221) * feature: added more test cases * fix: fixed existing test cases * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * feature: added more test cases * feature: added more test cases * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * feature: added mocks * fix: fixed bugs * fix: fixed mocks * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: made components internal * Add webstreaming to multiupload (#1190) * add webstreaming * fix typos * add webstreaming to wasm multiupload * fix typo * fix dup upload consensus (#1195) * Fix multiupload completed callback (#1172) * remove unnecessary print * fix delete and createdir * return major error * add webstreaming * fix typos * add webstreaming to wasm multiupload * fix typo * cleanup * fix completed callback * Feat/update methods in WinSDK (#1198) * delete dir in repair (#1196) * delete dir in repair * replace ioutil * fix unit test * fix list worker test * fix rename dir error * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * Add NFT Config contract (#1212) * Silent the zcnbridge http request when --silent (#1207) * Change the return type of downloadBlocks to []byte in wasm (#1218) * change the order of exchanges to get the ZCN prices (#1216) * Deprecate non multi-operation functions (#1214) * remove CreateDir, Rename, Copy, Move * use docker build wasm * use @v4 version of git action * Revert "use @v4 version of git action" This reverts commit fbb93f25a6ca63d6e205eac418d031bba428eb29. * Updated self hosted macos runner (#1219) * Updated self hosted macos runner * fixed runner name build-sdks.yml * remove path header, fix ws tag --------- Co-authored-by: YarikRevich Co-authored-by: Yaroslav Svitlytskyi <53532703+YarikRevich@users.noreply.github.com> Co-authored-by: Dinmukhammed Kambarov <52813950+din-mukhammed@users.noreply.github.com> Co-authored-by: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Co-authored-by: Lz Co-authored-by: Yaroslav Svitlytskyi Co-authored-by: peterlimg <54137706+peterlimg@users.noreply.github.com> Co-authored-by: Kishan Dhakan <42718091+Kishan-Dhakan@users.noreply.github.com> Co-authored-by: Manohar Reddy Co-authored-by: shahnawaz-creator <117025384+shahnawaz-creator@users.noreply.github.com> Co-authored-by: din-mukhammed * Revert "Fix/remove path (#1221)" (#1222) This reverts commit 464260aa3c2be34fdc0aca58582b27247528333b. * remove path header, fix ws tag * remove path header, fix ws tag (#1223) * remove path header, fix ws tag * fixed broken build --------- Co-authored-by: din-mukhammed * Updated self hosted macos runner (#1219) * Updated self hosted macos runner * fixed runner name build-sdks.yml (cherry picked from commit 1c9f143fe842e6c88fec1a6bc5fa0ced2ca84682) * added logging * updated wasm binary build fix. * updated wasm binary build fix. (cherry picked from commit 257188873db1d21ccdb04eb7e5a35ff6ef6d7696) * README grammar and formatting tweaks. --------- Co-authored-by: YarikRevich Co-authored-by: Yaroslav Svitlytskyi <53532703+YarikRevich@users.noreply.github.com> Co-authored-by: Dinmukhammed Kambarov <52813950+din-mukhammed@users.noreply.github.com> Co-authored-by: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Co-authored-by: Lz Co-authored-by: Yaroslav Svitlytskyi Co-authored-by: peterlimg <54137706+peterlimg@users.noreply.github.com> Co-authored-by: Kishan Dhakan <42718091+Kishan-Dhakan@users.noreply.github.com> Co-authored-by: Manohar Reddy Co-authored-by: shahnawaz-creator <117025384+shahnawaz-creator@users.noreply.github.com> Co-authored-by: din-mukhammed Co-authored-by: shahnawaz-creator Co-authored-by: UncertainBadg3r <139782199+UncertainBadg3r@users.noreply.github.com> Co-authored-by: Jayash Satolia <73050737+Jayashsatolia403@users.noreply.github.com> --- zboxcore/zboxutil/http.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/zboxcore/zboxutil/http.go b/zboxcore/zboxutil/http.go index c8480322b..d4c2c7dd6 100644 --- a/zboxcore/zboxutil/http.go +++ b/zboxcore/zboxutil/http.go @@ -822,7 +822,11 @@ func MakeSCRestAPICall(scAddress string, relativePath string, params map[string] go func(sharder string) { defer wg.Done() urlString := fmt.Sprintf("%v/%v%v%v", sharder, SC_REST_API_URL, scAddress, relativePath) - urlObj, _ := url.Parse(urlString) + urlObj, err := url.Parse(urlString) + if err != nil { + log.Error(err) + return + } q := urlObj.Query() for k, v := range params { q.Add(k, v) From 6ffe3b7dfacdbbc3f96f683c666dc0fb5ac0e649 Mon Sep 17 00:00:00 2001 From: Ashutosh Kumar Choudhary Date: Sun, 12 Nov 2023 23:59:21 +0530 Subject: [PATCH 084/134] Adding RegisterAuthorizer method in wasmsdk (#1273) * Adding RegisterAuthorizer method in wasmsdk * Fix:wasm test fail * Adding demo for RegisterAuthorizer handler in wasm * Js and Go bridge implementation * RegisterAuthorizer handler changes and adding Async Js bridge * golangci-lint fixes * Added error handling in setSplitKey and setAuthURL * Refactoring wasm exposed handlers * Setting split key wallet before setting auth url in setAuthURL's demo * Lint Fixes after resolving conflicts --- core/version/version.go | 3 +-- wasmsdk/auth_txn.go | 2 -- wasmsdk/demo/index.html | 43 ++++++++++++++++++++++++++++------------ wasmsdk/jsbridge/func.go | 1 + wasmsdk/proxy.go | 7 ++++--- wasmsdk/wallet_base.go | 22 +++++++++++++------- 6 files changed, 51 insertions(+), 27 deletions(-) diff --git a/core/version/version.go b/core/version/version.go index b102958cb..459a91ad3 100644 --- a/core/version/version.go +++ b/core/version/version.go @@ -2,5 +2,4 @@ //====== THIS IS AUTOGENERATED FILE. DO NOT MODIFY ======== package version -const VERSIONSTR = "v1.10.0-93-gf7075dc7" - +const VERSIONSTR = "v1.10.0-100-gf600e64b" diff --git a/wasmsdk/auth_txn.go b/wasmsdk/auth_txn.go index 1530c862f..b2716c86c 100644 --- a/wasmsdk/auth_txn.go +++ b/wasmsdk/auth_txn.go @@ -10,10 +10,8 @@ import ( "github.com/0chain/gosdk/core/sys" ) -// Declare a type for the callback function type AuthCallbackFunc func(msg string) string -// Variable to store the callback function var authCallback AuthCallbackFunc // Register the callback function diff --git a/wasmsdk/demo/index.html b/wasmsdk/demo/index.html index 64d16ecd1..c8102b285 100644 --- a/wasmsdk/demo/index.html +++ b/wasmsdk/demo/index.html @@ -165,7 +165,6 @@

please download zcn.wasm from https://github.com/0chain/gosdk/releases/lates
- diff --git a/wasmsdk/jsbridge/func.go b/wasmsdk/jsbridge/func.go index cd29aabd9..1c35286fc 100644 --- a/wasmsdk/jsbridge/func.go +++ b/wasmsdk/jsbridge/func.go @@ -45,6 +45,7 @@ func BindAsyncFuncs(global js.Value, fnList map[string]interface{}) { } } + func BindFuncs(global js.Value, fnList map[string]interface{}) { for jsFuncName, fn := range fnList { diff --git a/wasmsdk/proxy.go b/wasmsdk/proxy.go index 9e5dc98cc..2f1c8f7b7 100644 --- a/wasmsdk/proxy.go +++ b/wasmsdk/proxy.go @@ -242,9 +242,10 @@ func main() { "refreshJwtToken": refreshJwtToken, //split key - "splitKeys": splitKeys, - "setWalletInfo": setWalletInfo, - "setAuthUrl": setAuthUrl, + "splitKeys": splitKeys, + "setWalletInfo": setWalletInfo, + "setAuthUrl": setAuthUrl, + "registerAuthorizer": js.FuncOf(registerAuthorizer), "callAuth": js.FuncOf(callAuth), }) diff --git a/wasmsdk/wallet_base.go b/wasmsdk/wallet_base.go index 94c16fc56..2915a7953 100644 --- a/wasmsdk/wallet_base.go +++ b/wasmsdk/wallet_base.go @@ -6,7 +6,7 @@ import ( // Split keys from the primary master key -//nolint: unused +// nolint: unused func splitKeys(privateKey string, numSplits int) (string, error) { wStr, err := zcncore.SplitKeys(privateKey, numSplits) return wStr, err @@ -18,18 +18,26 @@ func splitKeys(privateKey string, numSplits int) (string, error) { // - jsonWallet: json format of wallet // - splitKeyWallet: if wallet keys is split -//nolint: unused -func setWalletInfo(jsonWallet string, splitKeyWallet bool) error { +// nolint: unused +func setWalletInfo(jsonWallet string, splitKeyWallet bool) bool { err := zcncore.SetWalletInfo(jsonWallet, splitKeyWallet) - return err + if err == nil { + return true + } else { + return false + } } // SetAuthUrl will be called by app to set zauth URL to SDK. // # Inputs // - url: the url of zAuth server -//nolint: unused -func setAuthUrl(url string) error { +// nolint: unused +func setAuthUrl(url string) bool { err := zcncore.SetAuthUrl(url) - return err + if err == nil { + return true + } else { + return false + } } From 17a9355755b6fe8ceab96bef7b4767d2c51a9070 Mon Sep 17 00:00:00 2001 From: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Date: Wed, 15 Nov 2023 02:58:33 +0530 Subject: [PATCH 085/134] upload optimization (#1281) * add sha256 simd and blake3 * add hash chan * fix lint and unit test * fix MHash * rmv timing log * fix thumbnail hash --- core/encryption/hash.go | 18 +++++++ core/util/fixed_merkle_tree.go | 6 +-- core/util/merkle_tree_interface.go | 5 +- core/util/validation_tree.go | 10 ++-- core/util/validation_tree_test.go | 42 +++++++-------- go.mod | 8 ++- go.sum | 13 ++++- zboxcore/sdk/chunked_upload.go | 7 +-- zboxcore/sdk/chunked_upload_chunk_reader.go | 51 +++++++++++++++--- .../chunked_upload_chunk_reader_bench_test.go | 2 +- .../sdk/chunked_upload_chunk_reader_test.go | 2 +- zboxcore/sdk/chunked_upload_hasher.go | 5 +- zboxcore/sdk/chunked_upload_model.go | 2 +- zboxcore/sdk/chunked_upload_option.go | 4 +- zboxcore/sdk/downloadworker.go | 53 ++++++++++++++----- zboxcore/sdk/sync.go | 4 +- zboxcore/zboxutil/util.go | 4 +- 17 files changed, 170 insertions(+), 66 deletions(-) diff --git a/core/encryption/hash.go b/core/encryption/hash.go index 233ce7770..5ce9edfe1 100644 --- a/core/encryption/hash.go +++ b/core/encryption/hash.go @@ -4,6 +4,7 @@ import ( "crypto/sha1" "encoding/hex" + "github.com/zeebo/blake3" "golang.org/x/crypto/sha3" ) @@ -35,6 +36,23 @@ func RawHash(data interface{}) []byte { return hash.Sum(buf) } +func BlakeHash(data interface{}) []byte { + var databuf []byte + switch dataImpl := data.(type) { + case []byte: + databuf = dataImpl + case HashBytes: + databuf = dataImpl[:] + case string: + databuf = []byte(dataImpl) + default: + panic("unknown type") + } + hash := blake3.New() + _, _ = hash.Write(databuf) + return hash.Sum(nil) +} + /*FastHash - sha1 hash the given data and return the hash as hex string */ func FastHash(data interface{}) string { return hex.EncodeToString(RawFastHash(data)) diff --git a/core/util/fixed_merkle_tree.go b/core/util/fixed_merkle_tree.go index 13f1ba306..5e3ab1bd2 100644 --- a/core/util/fixed_merkle_tree.go +++ b/core/util/fixed_merkle_tree.go @@ -10,7 +10,7 @@ import ( goError "errors" "github.com/0chain/errors" - "golang.org/x/crypto/sha3" + "github.com/zeebo/blake3" ) const ( @@ -38,14 +38,14 @@ func (l *leaf) Write(b []byte) (int, error) { func getNewLeaf() *leaf { return &leaf{ - h: sha3.New256(), + h: blake3.New(), } } // FixedMerkleTree A trusted mekerle tree for outsourcing attack protection. see section 1.8 on whitepager // see detail on https://github.com/0chain/blobber/wiki/Protocols#what-is-fixedmerkletree type FixedMerkleTree struct { - // Leaves will store hash digester that calculates sha256 hash of the leaf content + // Leaves will store hash digester that calculates blake3 hash of the leaf content Leaves []Hashable `json:"leaves,omitempty"` writeLock sync.Mutex diff --git a/core/util/merkle_tree_interface.go b/core/util/merkle_tree_interface.go index db1d6f9e3..41afeb0f3 100644 --- a/core/util/merkle_tree_interface.go +++ b/core/util/merkle_tree_interface.go @@ -4,6 +4,7 @@ import ( "encoding/hex" "github.com/0chain/gosdk/core/encryption" + "github.com/zeebo/blake3" ) /*MerkleTreeI - a merkle tree interface required for constructing and providing verification */ @@ -40,7 +41,9 @@ func MHashBytes(h1, h2 []byte) []byte { buf := make([]byte, len(h1)+len(h2)) copy(buf, h1) copy(buf[len(h1):], h2) - return encryption.RawHash(buf) + hash := blake3.New() + _, _ = hash.Write(buf) + return hash.Sum(nil) } /*MHash - merkle hashing of a pair of child hashes */ diff --git a/core/util/validation_tree.go b/core/util/validation_tree.go index 4a5bc0b6e..c5d0e0039 100644 --- a/core/util/validation_tree.go +++ b/core/util/validation_tree.go @@ -9,7 +9,7 @@ import ( "math" "sync" - "golang.org/x/crypto/sha3" + "github.com/zeebo/blake3" ) const ( @@ -99,7 +99,7 @@ func (v *ValidationTree) calculateRoot() { depth := v.CalculateDepth() nodes := make([][]byte, totalLeaves) copy(nodes, v.leaves) - h := sha3.New256() + h := blake3.New() for i := 0; i < depth; i++ { if len(nodes) == 1 { @@ -154,7 +154,7 @@ func NewValidationTree(dataSize int64) *ValidationTree { return &ValidationTree{ dataSize: dataSize, - h: sha3.New256(), + h: blake3.New(), leaves: make([][]byte, totalLeaves), } } @@ -223,7 +223,7 @@ If client had required data from 2-9 then blobber would have to provide: func (m *MerklePathForMultiLeafVerification) VerifyMultipleBlocks(data []byte) error { hashes := make([][]byte, 0) - h := sha3.New256() + h := blake3.New() // Calculate hashes from the data responded from the blobber. for i := 0; i < len(data); i += MaxMerkleLeavesSize { endIndex := i + MaxMerkleLeavesSize @@ -270,7 +270,7 @@ func (m *MerklePathForMultiLeafVerification) VerifyMultipleBlocks(data []byte) e func (m *MerklePathForMultiLeafVerification) calculateIntermediateHashes(hashes [][]byte) [][]byte { newHashes := make([][]byte, 0) - h := sha3.New256() + h := blake3.New() if len(hashes)%2 == 0 { for i := 0; i < len(hashes); i += 2 { h.Reset() diff --git a/core/util/validation_tree_test.go b/core/util/validation_tree_test.go index 9dcdd251e..9775614dc 100644 --- a/core/util/validation_tree_test.go +++ b/core/util/validation_tree_test.go @@ -9,7 +9,7 @@ import ( "testing" "github.com/stretchr/testify/require" - "golang.org/x/crypto/sha3" + "github.com/zeebo/blake3" ) const ( @@ -144,8 +144,8 @@ func calculateValidationMerkleRoot(data []byte) []byte { if j > len(data) { j = len(data) } - h := sha3.New256() - h.Write(data[i:j]) + h := blake3.New() + _, _ = h.Write(data[i:j]) hashes = append(hashes, h.Sum(nil)) } @@ -156,20 +156,20 @@ func calculateValidationMerkleRoot(data []byte) []byte { newHashes := make([][]byte, 0) if len(hashes)%2 == 0 { for i := 0; i < len(hashes); i += 2 { - h := sha3.New256() - h.Write(hashes[i]) - h.Write(hashes[i+1]) + h := blake3.New() + _, _ = h.Write(hashes[i]) + _, _ = h.Write(hashes[i+1]) newHashes = append(newHashes, h.Sum(nil)) } } else { for i := 0; i < len(hashes)-1; i += 2 { - h := sha3.New256() - h.Write(hashes[i]) - h.Write(hashes[i+1]) + h := blake3.New() + _, _ = h.Write(hashes[i]) + _, _ = h.Write(hashes[i+1]) newHashes = append(newHashes, h.Sum(nil)) } - h := sha3.New256() - h.Write(hashes[len(hashes)-1]) + h := blake3.New() + _, _ = h.Write(hashes[len(hashes)-1]) newHashes = append(newHashes, h.Sum(nil)) } @@ -191,14 +191,14 @@ func calculateValidationRootAndNodes(b []byte, startInd, endInd int) ( hashes := make([][]byte, 0) nodesData := make([]byte, 0) - h := sha3.New256() + h := blake3.New() for i := 0; i < len(b); i += MaxMerkleLeavesSize { j := i + MaxMerkleLeavesSize if j > len(b) { j = len(b) } - h.Write(b[i:j]) + _, _ = h.Write(b[i:j]) leafHash := h.Sum(nil) hashes = append(hashes, leafHash) h.Reset() @@ -212,24 +212,24 @@ func calculateValidationRootAndNodes(b []byte, startInd, endInd int) ( newHashes := make([][]byte, 0) if len(hashes)%2 == 0 { for i := 0; i < len(hashes); i += 2 { - h := sha3.New256() - h.Write(hashes[i]) - h.Write(hashes[i+1]) + h := blake3.New() + _, _ = h.Write(hashes[i]) + _, _ = h.Write(hashes[i+1]) nodesData = append(nodesData, hashes[i]...) nodesData = append(nodesData, hashes[i+1]...) newHashes = append(newHashes, h.Sum(nil)) } } else { for i := 0; i < len(hashes)-1; i += 2 { - h := sha3.New256() - h.Write(hashes[i]) - h.Write(hashes[i+1]) + h := blake3.New() + _, _ = h.Write(hashes[i]) + _, _ = h.Write(hashes[i+1]) nodesData = append(nodesData, hashes[i]...) nodesData = append(nodesData, hashes[i+1]...) newHashes = append(newHashes, h.Sum(nil)) } - h := sha3.New256() - h.Write(hashes[len(hashes)-1]) + h := blake3.New() + _, _ = h.Write(hashes[len(hashes)-1]) nodesData = append(nodesData, hashes[len(hashes)-1]...) newHashes = append(newHashes, h.Sum(nil)) } diff --git a/go.mod b/go.mod index f6a739113..604cdf9c5 100644 --- a/go.mod +++ b/go.mod @@ -18,7 +18,7 @@ require ( github.com/hashicorp/golang-lru/v2 v2.0.1 github.com/herumi/bls-go-binary v1.31.0 github.com/influxdata/influxdb v1.8.3 - github.com/klauspost/reedsolomon v1.11.7 + github.com/klauspost/reedsolomon v1.11.8 github.com/lithammer/shortuuid/v3 v3.0.7 github.com/machinebox/graphql v0.2.2 github.com/magma/augmented-networks/accounting/protos v0.1.1 @@ -42,7 +42,11 @@ require ( gopkg.in/yaml.v3 v3.0.1 ) -require github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d +require ( + github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d + github.com/minio/sha256-simd v1.0.1 + github.com/zeebo/blake3 v0.2.3 +) require ( github.com/VictoriaMetrics/fastcache v1.6.0 // indirect diff --git a/go.sum b/go.sum index a98bbbde2..1fe9b61ce 100644 --- a/go.sum +++ b/go.sum @@ -339,12 +339,13 @@ github.com/klauspost/compress v1.12.3/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8 github.com/klauspost/compress v1.16.0 h1:iULayQNOReoYUe+1qtKOqw9CwJv3aNQu8ivo7lw1HU4= github.com/klauspost/compress v1.16.0/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/cpuid v0.0.0-20170728055534-ae7887de9fa5/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= +github.com/klauspost/cpuid/v2 v2.0.12/go.mod h1:g2LTdtYhdyuGPqyWyv7qRAmj1WBqxuObKfj5c0PQa7c= github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk= github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= github.com/klauspost/crc32 v0.0.0-20161016154125-cb6bfca970f6/go.mod h1:+ZoRqAPRLkC4NPOvfYeR5KNOrY6TD+/sAC3HXPZgDYg= github.com/klauspost/pgzip v1.0.2-0.20170402124221-0bf5dcad4ada/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs= -github.com/klauspost/reedsolomon v1.11.7 h1:9uaHU0slncktTEEg4+7Vl7q7XUNMBUOK4R9gnKhMjAU= -github.com/klauspost/reedsolomon v1.11.7/go.mod h1:4bXRN+cVzMdml6ti7qLouuYi32KHJ5MGv0Qd8a47h6A= +github.com/klauspost/reedsolomon v1.11.8 h1:s8RpUW5TK4hjr+djiOpbZJB4ksx+TdYbRH7vHQpwPOY= +github.com/klauspost/reedsolomon v1.11.8/go.mod h1:4bXRN+cVzMdml6ti7qLouuYi32KHJ5MGv0Qd8a47h6A= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= @@ -382,6 +383,8 @@ github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh github.com/mattn/go-sqlite3 v1.11.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= github.com/mattn/go-tty v0.0.0-20180907095812-13ff1204f104/go.mod h1:XPvLUNfbS4fJH25nqRHfWLMa1ONC8Amw+mIA639KxkE= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/minio/sha256-simd v1.0.1 h1:6kaan5IFmwTNynnKKpDHe6FWHohJOHhCPchzK49dzMM= +github.com/minio/sha256-simd v1.0.1/go.mod h1:Pz6AKMiUdngCLpeTL/RJY1M9rUuPMYujV5xJjtbRSN8= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= @@ -537,6 +540,12 @@ github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9dec github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yusufpapurcu/wmi v1.2.2 h1:KBNDSne4vP5mbSWnJbO+51IMOXJB67QiYCSBrubbPRg= github.com/yusufpapurcu/wmi v1.2.2/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= +github.com/zeebo/assert v1.1.0 h1:hU1L1vLTHsnO8x8c9KAR5GmM5QscxHg5RNU5z5qbUWY= +github.com/zeebo/assert v1.1.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0= +github.com/zeebo/blake3 v0.2.3 h1:TFoLXsjeXqRNFxSbk35Dk4YtszE/MQQGK10BH4ptoTg= +github.com/zeebo/blake3 v0.2.3/go.mod h1:mjJjZpnsyIVtVgTOSpJ9vmRE4wgDeyt2HU3qXvvKCaQ= +github.com/zeebo/pcg v1.0.1 h1:lyqfGeWiv4ahac6ttHs+I5hwtH/+1mrhlCtVNQM2kHo= +github.com/zeebo/pcg v1.0.1/go.mod h1:09F0S9iiKrwn9rlI5yjLkmrug154/YRW6KnnXVDM/l4= go.dedis.ch/fixbuf v1.0.3 h1:hGcV9Cd/znUxlusJ64eAlExS+5cJDIyTyEG+otu5wQs= go.dedis.ch/fixbuf v1.0.3/go.mod h1:yzJMt34Wa5xD37V5RTdmp38cz3QhMagdGoem9anUalw= go.dedis.ch/kyber/v3 v3.0.4/go.mod h1:OzvaEnPvKlyrWyp3kGXlFdp7ap1VC6RkZDTaPikqhsQ= diff --git a/zboxcore/sdk/chunked_upload.go b/zboxcore/sdk/chunked_upload.go index edb45e995..2116000f5 100644 --- a/zboxcore/sdk/chunked_upload.go +++ b/zboxcore/sdk/chunked_upload.go @@ -159,7 +159,7 @@ func CreateChunkedUpload( uploadMask: uploadMask, chunkSize: DefaultChunkSize, - chunkNumber: 1, + chunkNumber: 100, encryptOnUpload: false, webStreaming: false, @@ -272,7 +272,7 @@ func CreateChunkedUpload( }, } } - cReader, err := createChunkReader(su.fileReader, fileMeta.ActualSize, int64(su.chunkSize), su.allocationObj.DataShards, su.encryptOnUpload, su.uploadMask, su.fileErasureEncoder, su.fileEncscheme, su.fileHasher) + cReader, err := createChunkReader(su.fileReader, fileMeta.ActualSize, int64(su.chunkSize), su.allocationObj.DataShards, su.encryptOnUpload, su.uploadMask, su.fileErasureEncoder, su.fileEncscheme, su.fileHasher, su.chunkNumber) if err != nil { return nil, err @@ -387,6 +387,7 @@ func (su *ChunkedUpload) process() error { su.statusCallback.Started(su.allocationObj.ID, su.fileMeta.RemotePath, su.opCode, int(su.fileMeta.ActualSize)+int(su.fileMeta.ActualThumbnailSize)) } alreadyUploadedData := 0 + defer su.chunkReader.Close() defer close(su.uploadChan) defer su.ctxCncl(nil) for { @@ -406,7 +407,7 @@ func (su *ChunkedUpload) process() error { su.progress.UploadLength += chunks.totalReadSize if chunks.isFinal { - su.fileMeta.ActualHash, err = su.fileHasher.GetFileHash() + su.fileMeta.ActualHash, err = su.chunkReader.GetFileHash() if err != nil { if su.statusCallback != nil { su.statusCallback.Error(su.allocationObj.ID, su.fileMeta.RemotePath, su.opCode, err) diff --git a/zboxcore/sdk/chunked_upload_chunk_reader.go b/zboxcore/sdk/chunked_upload_chunk_reader.go index 0642397b3..c54ba6408 100644 --- a/zboxcore/sdk/chunked_upload_chunk_reader.go +++ b/zboxcore/sdk/chunked_upload_chunk_reader.go @@ -4,6 +4,7 @@ import ( "io" "math" "strconv" + "sync" "github.com/0chain/errors" "github.com/0chain/gosdk/constants" @@ -18,6 +19,11 @@ type ChunkedUploadChunkReader interface { // Read read, encode and encrypt all bytes Read(buf []byte) ([][]byte, error) + + //Close Hash Channel + Close() + //GetFileHash get file hash + GetFileHash() (string, error) } // chunkedUploadChunkReader read chunk bytes from io.Reader. see detail on https://github.com/0chain/blobber/wiki/Protocols#what-is-fixedmerkletree @@ -54,11 +60,15 @@ type chunkedUploadChunkReader struct { // encscheme encryption scheme encscheme encryption.EncryptionScheme // hasher to calculate actual file hash, validation root and fixed merkle root - hasher Hasher + hasher Hasher + hasherDataChan chan []byte + hasherError error + hasherWG sync.WaitGroup + closeOnce sync.Once } // createChunkReader create ChunkReader instance -func createChunkReader(fileReader io.Reader, size, chunkSize int64, dataShards int, encryptOnUpload bool, uploadMask zboxutil.Uint128, erasureEncoder reedsolomon.Encoder, encscheme encryption.EncryptionScheme, hasher Hasher) (ChunkedUploadChunkReader, error) { +func createChunkReader(fileReader io.Reader, size, chunkSize int64, dataShards int, encryptOnUpload bool, uploadMask zboxutil.Uint128, erasureEncoder reedsolomon.Encoder, encscheme encryption.EncryptionScheme, hasher Hasher, chunkNumber int) (ChunkedUploadChunkReader, error) { if chunkSize <= 0 { return nil, errors.Throw(constants.ErrInvalidParameter, "chunkSize: "+strconv.FormatInt(chunkSize, 10)) @@ -87,6 +97,8 @@ func createChunkReader(fileReader io.Reader, size, chunkSize int64, dataShards i erasureEncoder: erasureEncoder, encscheme: encscheme, hasher: hasher, + hasherDataChan: make(chan []byte, 2*chunkNumber), + hasherWG: sync.WaitGroup{}, } if r.encryptOnUpload { @@ -98,7 +110,8 @@ func createChunkReader(fileReader io.Reader, size, chunkSize int64, dataShards i } r.chunkDataSizePerRead = r.chunkDataSize * int64(dataShards) - + r.hasherWG.Add(1) + go r.hashData() return r, nil } @@ -170,10 +183,10 @@ func (r *chunkedUploadChunkReader) Next() (*ChunkData, error) { } } - err = r.hasher.WriteToFile(chunkBytes) - if err != nil { - return chunk, err + if r.hasherError != nil { + return chunk, r.hasherError } + r.hasherDataChan <- chunkBytes fragments, err := r.erasureEncoder.Split(chunkBytes) if err != nil { return nil, err @@ -239,3 +252,29 @@ func (r *chunkedUploadChunkReader) Read(buf []byte) ([][]byte, error) { return fragments, nil } + +func (r *chunkedUploadChunkReader) Close() { + r.closeOnce.Do(func() { + close(r.hasherDataChan) + r.hasherWG.Wait() + }) +} + +func (r *chunkedUploadChunkReader) GetFileHash() (string, error) { + r.Close() + if r.hasherError != nil { + return "", r.hasherError + } + return r.hasher.GetFileHash() +} + +func (r *chunkedUploadChunkReader) hashData() { + defer r.hasherWG.Done() + for data := range r.hasherDataChan { + err := r.hasher.WriteToFile(data) + if err != nil { + r.hasherError = err + return + } + } +} diff --git a/zboxcore/sdk/chunked_upload_chunk_reader_bench_test.go b/zboxcore/sdk/chunked_upload_chunk_reader_bench_test.go index 57a066f8a..70d0cd111 100644 --- a/zboxcore/sdk/chunked_upload_chunk_reader_bench_test.go +++ b/zboxcore/sdk/chunked_upload_chunk_reader_bench_test.go @@ -68,7 +68,7 @@ func BenchmarkChunkedUploadChunkReader(b *testing.B) { int64(bm.ChunkSize), bm.DataShards, bm.EncryptOnUpload, uploadMask, erasureEncoder, encscheme, - CreateHasher(getShardSize(bm.Size, bm.DataShards, bm.EncryptOnUpload)), + CreateHasher(getShardSize(bm.Size, bm.DataShards, bm.EncryptOnUpload)), 100, ) if err != nil { b.Fatal(err) diff --git a/zboxcore/sdk/chunked_upload_chunk_reader_test.go b/zboxcore/sdk/chunked_upload_chunk_reader_test.go index 1cff5032f..d6e756384 100644 --- a/zboxcore/sdk/chunked_upload_chunk_reader_test.go +++ b/zboxcore/sdk/chunked_upload_chunk_reader_test.go @@ -83,7 +83,7 @@ func TestReadChunks(t *testing.T) { int64(test.ChunkSize), test.DataShards, test.EncryptOnUpload, uploadMask, erasureEncoder, encscheme, - CreateHasher(getShardSize(test.Size, test.DataShards, test.EncryptOnUpload)), + CreateHasher(getShardSize(test.Size, test.DataShards, test.EncryptOnUpload)), 100, ) require.Nil(err) diff --git a/zboxcore/sdk/chunked_upload_hasher.go b/zboxcore/sdk/chunked_upload_hasher.go index f7955934d..650958103 100644 --- a/zboxcore/sdk/chunked_upload_hasher.go +++ b/zboxcore/sdk/chunked_upload_hasher.go @@ -5,10 +5,11 @@ import ( "hash" "sync" + "github.com/minio/sha256-simd" + "github.com/0chain/errors" "github.com/0chain/gosdk/constants" "github.com/0chain/gosdk/core/util" - "golang.org/x/crypto/sha3" ) type Hasher interface { @@ -38,7 +39,7 @@ type hasher struct { // CreateHasher creat Hasher instance func CreateHasher(dataSize int64) Hasher { return &hasher{ - File: sha3.New256(), + File: sha256.New(), FixedMT: util.NewFixedMerkleTree(), ValidationMT: util.NewValidationTree(dataSize), } diff --git a/zboxcore/sdk/chunked_upload_model.go b/zboxcore/sdk/chunked_upload_model.go index ba361da46..6626c3136 100644 --- a/zboxcore/sdk/chunked_upload_model.go +++ b/zboxcore/sdk/chunked_upload_model.go @@ -56,7 +56,7 @@ type ChunkedUpload struct { webStreaming bool // chunkSize how much bytes a chunk has. 64KB is default value. chunkSize int64 - // chunkNumber the number of chunks in a http upload request. 1 is default value + // chunkNumber the number of chunks in a http upload request. 100 is default value chunkNumber int // shardUploadedSize how much bytes a shard has. it is original size diff --git a/zboxcore/sdk/chunked_upload_option.go b/zboxcore/sdk/chunked_upload_option.go index 9a97e5654..38872052c 100644 --- a/zboxcore/sdk/chunked_upload_option.go +++ b/zboxcore/sdk/chunked_upload_option.go @@ -8,7 +8,7 @@ import ( "github.com/0chain/gosdk/zboxcore/zboxutil" "github.com/klauspost/reedsolomon" - "golang.org/x/crypto/sha3" + "github.com/minio/sha256-simd" ) // ChunkedUploadOption set stream option @@ -26,7 +26,7 @@ func WithThumbnail(buf []byte) ChunkedUploadOption { su.thumbnailBytes = buf su.fileMeta.ActualThumbnailSize = int64(len(buf)) - thumbnailHasher := sha3.New256() + thumbnailHasher := sha256.New() thumbnailHasher.Write(buf) su.fileMeta.ActualThumbnailHash = hex.EncodeToString(thumbnailHasher.Sum(nil)) diff --git a/zboxcore/sdk/downloadworker.go b/zboxcore/sdk/downloadworker.go index 99bf1bd57..d6fdb112d 100644 --- a/zboxcore/sdk/downloadworker.go +++ b/zboxcore/sdk/downloadworker.go @@ -29,8 +29,8 @@ import ( "github.com/0chain/gosdk/zboxcore/marker" "github.com/0chain/gosdk/zboxcore/zboxutil" "github.com/klauspost/reedsolomon" + "github.com/minio/sha256-simd" "go.dedis.ch/kyber/v3/group/edwards25519" - "golang.org/x/crypto/sha3" "golang.org/x/sync/errgroup" ) @@ -413,21 +413,31 @@ func (req *DownloadRequest) processDownload(ctx context.Context) { req.shouldVerify = false } } - var actualFileHasher hash.Hash - var isPREAndWholeFile bool - if !req.shouldVerify && (startBlock == 0 && endBlock == chunksPerShard) && shouldVerifyHash { - actualFileHasher = sha3.New256() - isPREAndWholeFile = true - } - n := int((endBlock - startBlock + numBlocks - 1) / numBlocks) // Buffered channel to hold the blocks as they are downloaded blocks := make(chan blockData, n) + var ( + actualFileHasher hash.Hash + isPREAndWholeFile bool + closeOnce *sync.Once + hashDataChan chan []byte + hashWg *sync.WaitGroup + ) + + if !req.shouldVerify && (startBlock == 0 && endBlock == chunksPerShard) { + actualFileHasher = sha256.New() + hashDataChan = make(chan []byte, n) + hashWg = &sync.WaitGroup{} + hashWg.Add(1) + closeOnce = &sync.Once{} + go processHashData(hashDataChan, hashWg, actualFileHasher) + isPREAndWholeFile = true + } + var wg sync.WaitGroup wg.Add(1) - // Handle writing the blocks in order as soon as they are downloaded go func() { buffer := make(map[int][]byte) @@ -436,8 +446,12 @@ func (req *DownloadRequest) processDownload(ctx context.Context) { // If the block we need to write next is already in the buffer, write it numBytes := int64(math.Min(float64(remainingSize), float64(len(data)))) if isPREAndWholeFile { - actualFileHasher.Write(data[:numBytes]) + hashDataChan <- data[:numBytes] if i == n-1 { + closeOnce.Do(func() { + close(hashDataChan) + }) + hashWg.Wait() if calculatedFileHash, ok := checkHash(actualFileHasher, fRef, req.contentMode); !ok { req.errorCB(fmt.Errorf("Expected actual file hash %s, calculated file hash %s", fRef.ActualFileHash, calculatedFileHash), remotePathCB) @@ -468,8 +482,12 @@ func (req *DownloadRequest) processDownload(ctx context.Context) { // Write the data numBytes := int64(math.Min(float64(remainingSize), float64(len(block.data)))) if isPREAndWholeFile { - actualFileHasher.Write(block.data[:numBytes]) + hashDataChan <- block.data[:numBytes] if i == n-1 { + closeOnce.Do(func() { + close(hashDataChan) + }) + hashWg.Wait() if calculatedFileHash, ok := checkHash(actualFileHasher, fRef, req.contentMode); !ok { req.errorCB(fmt.Errorf("Expected actual file hash %s, calculated file hash %s", fRef.ActualFileHash, calculatedFileHash), remotePathCB) @@ -478,7 +496,6 @@ func (req *DownloadRequest) processDownload(ctx context.Context) { } } _, err = req.fileHandler.Write(block.data[:numBytes]) - if err != nil { req.errorCB(errors.Wrap(err, "Write file failed"), remotePathCB) return @@ -524,6 +541,11 @@ func (req *DownloadRequest) processDownload(ctx context.Context) { }) } if err := eg.Wait(); err != nil { + if isPREAndWholeFile { + closeOnce.Do(func() { + close(hashDataChan) + }) + } req.errorCB(err, remotePathCB) return } @@ -554,6 +576,13 @@ func checkHash(actualFileHasher hash.Hash, fref *fileref.FileRef, contentMode st } } +func processHashData(hashDataChan chan []byte, hashWg *sync.WaitGroup, actualFileHasher hash.Hash) { + defer hashWg.Done() + for data := range hashDataChan { + actualFileHasher.Write(data) + } +} + func (req *DownloadRequest) submitReadMarker(blobber *blockchain.StorageNode, readCount int64) (err error) { var retryCount = 3 for retryCount > 0 { diff --git a/zboxcore/sdk/sync.go b/zboxcore/sdk/sync.go index 80907a7ab..6f38d47e6 100644 --- a/zboxcore/sdk/sync.go +++ b/zboxcore/sdk/sync.go @@ -17,7 +17,7 @@ import ( "github.com/0chain/gosdk/core/sys" "github.com/0chain/gosdk/zboxcore/fileref" l "github.com/0chain/gosdk/zboxcore/logger" - "golang.org/x/crypto/sha3" + "github.com/minio/sha256-simd" ) // For sync app @@ -106,7 +106,7 @@ func calcFileHash(filePath string) string { } defer fp.Close() - h := sha3.New256() + h := sha256.New() if _, err := io.Copy(h, fp); err != nil { log.Fatal(err) } diff --git a/zboxcore/zboxutil/util.go b/zboxcore/zboxutil/util.go index 2efea4081..11701a02e 100644 --- a/zboxcore/zboxutil/util.go +++ b/zboxcore/zboxutil/util.go @@ -22,9 +22,9 @@ import ( "github.com/0chain/gosdk/zboxcore/blockchain" "github.com/h2non/filetype" "github.com/lithammer/shortuuid/v3" + "github.com/minio/sha256-simd" "golang.org/x/crypto/chacha20poly1305" "golang.org/x/crypto/scrypt" - "golang.org/x/crypto/sha3" ) const EncryptedFolderName = "encrypted" @@ -205,7 +205,7 @@ func Decrypt(key, text []byte) ([]byte, error) { } func GetRefsHash(r []byte) string { - hash := sha3.New256() + hash := sha256.New() hash.Write(r) var buf []byte buf = hash.Sum(buf) From 10b6a4afbdecc1e8a201d5ac80c4d12f0b97c411 Mon Sep 17 00:00:00 2001 From: dabasov Date: Wed, 15 Nov 2023 13:07:28 +0200 Subject: [PATCH 086/134] added logging --- zboxcore/zboxutil/http.go | 1 + 1 file changed, 1 insertion(+) diff --git a/zboxcore/zboxutil/http.go b/zboxcore/zboxutil/http.go index d4c2c7dd6..2fe86e6dc 100644 --- a/zboxcore/zboxutil/http.go +++ b/zboxcore/zboxutil/http.go @@ -824,6 +824,7 @@ func MakeSCRestAPICall(scAddress string, relativePath string, params map[string] urlString := fmt.Sprintf("%v/%v%v%v", sharder, SC_REST_API_URL, scAddress, relativePath) urlObj, err := url.Parse(urlString) if err != nil { + log.Info(urlString) log.Error(err) return } From fafce3c9b90c0863e574a2609a202f962ecb90ac Mon Sep 17 00:00:00 2001 From: dabasov Date: Wed, 15 Nov 2023 13:47:07 +0200 Subject: [PATCH 087/134] added logging --- zboxcore/zboxutil/http.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zboxcore/zboxutil/http.go b/zboxcore/zboxutil/http.go index 2fe86e6dc..161326474 100644 --- a/zboxcore/zboxutil/http.go +++ b/zboxcore/zboxutil/http.go @@ -824,7 +824,7 @@ func MakeSCRestAPICall(scAddress string, relativePath string, params map[string] urlString := fmt.Sprintf("%v/%v%v%v", sharder, SC_REST_API_URL, scAddress, relativePath) urlObj, err := url.Parse(urlString) if err != nil { - log.Info(urlString) + log.Error(urlString) log.Error(err) return } From 895c7f0012837d2f9a0cbfdcddf47f8dbe0d13b7 Mon Sep 17 00:00:00 2001 From: dabasov Date: Wed, 15 Nov 2023 13:57:47 +0200 Subject: [PATCH 088/134] hotfix --- zcncore/networkworker_mobile.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/zcncore/networkworker_mobile.go b/zcncore/networkworker_mobile.go index ca0863ff8..7958ddabe 100644 --- a/zcncore/networkworker_mobile.go +++ b/zcncore/networkworker_mobile.go @@ -98,6 +98,10 @@ func UpdateRequired(networkDetails *Network) bool { return true } + if len(networkDetails.net.Miners) == 0 || len(networkDetails.net.Sharders) == 0 { + return false + } + minerSame := reflect.DeepEqual(miners, networkDetails.net.Miners) sharderSame := reflect.DeepEqual(sharders, networkDetails.net.Sharders) From 48cf793a70f754f44c662d839bdde4e191ec2748 Mon Sep 17 00:00:00 2001 From: dabasov Date: Wed, 15 Nov 2023 13:57:47 +0200 Subject: [PATCH 089/134] hotfix --- zboxcore/sdk/networkworker.go | 5 +++-- zcncore/networkworker.go | 4 +++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/zboxcore/sdk/networkworker.go b/zboxcore/sdk/networkworker.go index 276fca806..04c5b40ba 100644 --- a/zboxcore/sdk/networkworker.go +++ b/zboxcore/sdk/networkworker.go @@ -51,7 +51,6 @@ func UpdateNetworkDetails() error { l.Logger.Error("Failed to update network details ", zap.Error(err)) return err } - shouldUpdate := UpdateRequired(networkDetails) if shouldUpdate { forceUpdateNetworkDetails(networkDetails) @@ -87,7 +86,9 @@ func UpdateRequired(networkDetails *Network) bool { if len(miners) == 0 || len(sharders) == 0 { return true } - + if len(networkDetails.Miners) == 0 || len(networkDetails.Sharders) == 0 { + return false + } minerSame := reflect.DeepEqual(miners, networkDetails.Miners) sharderSame := reflect.DeepEqual(sharders, networkDetails.Sharders) diff --git a/zcncore/networkworker.go b/zcncore/networkworker.go index e267c5f4a..0644e45dd 100644 --- a/zcncore/networkworker.go +++ b/zcncore/networkworker.go @@ -82,7 +82,9 @@ func UpdateRequired(networkDetails *Network) bool { if len(miners) == 0 || len(sharders) == 0 { return true } - + if len(networkDetails.Miners) == 0 || len(networkDetails.Sharders) == 0 { + return false + } minerSame := reflect.DeepEqual(miners, networkDetails.Miners) sharderSame := reflect.DeepEqual(sharders, networkDetails.Sharders) From 8446894c579f5acd14db1b09b5966f92ca1588be Mon Sep 17 00:00:00 2001 From: dabasov Date: Wed, 15 Nov 2023 17:36:33 +0200 Subject: [PATCH 090/134] experiment --- zboxcore/zboxutil/http.go | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/zboxcore/zboxutil/http.go b/zboxcore/zboxutil/http.go index 161326474..ec57e2873 100644 --- a/zboxcore/zboxutil/http.go +++ b/zboxcore/zboxutil/http.go @@ -801,6 +801,8 @@ func NewRollbackRequest(baseUrl, allocationID string, allocationTx string, body return req, nil } +var lock sync.Mutex + func MakeSCRestAPICall(scAddress string, relativePath string, params map[string]string, handler SCRestAPIHandler) ([]byte, error) { numSharders := len(blockchain.GetSharders()) sharders := blockchain.GetSharders() @@ -821,10 +823,11 @@ func MakeSCRestAPICall(scAddress string, relativePath string, params map[string] wg.Add(1) go func(sharder string) { defer wg.Done() + + lock.Lock() urlString := fmt.Sprintf("%v/%v%v%v", sharder, SC_REST_API_URL, scAddress, relativePath) - urlObj, err := url.Parse(urlString) + urlObj, err := url.ParseRequestURI(urlString) if err != nil { - log.Error(urlString) log.Error(err) return } @@ -834,7 +837,10 @@ func MakeSCRestAPICall(scAddress string, relativePath string, params map[string] } urlObj.RawQuery = q.Encode() client := &http.Client{Transport: DefaultTransport} - response, err := client.Get(urlObj.String()) + s := urlObj.String() + lock.Unlock() + + response, err := client.Get(s) if err != nil { blockchain.Sharders.Fail(sharder) return From 6834b058a99bba80621c756292f7f4205b24e936 Mon Sep 17 00:00:00 2001 From: dabasov Date: Wed, 15 Nov 2023 18:15:17 +0200 Subject: [PATCH 091/134] experiment --- zboxcore/zboxutil/http.go | 4 ---- 1 file changed, 4 deletions(-) diff --git a/zboxcore/zboxutil/http.go b/zboxcore/zboxutil/http.go index ec57e2873..2874131da 100644 --- a/zboxcore/zboxutil/http.go +++ b/zboxcore/zboxutil/http.go @@ -801,8 +801,6 @@ func NewRollbackRequest(baseUrl, allocationID string, allocationTx string, body return req, nil } -var lock sync.Mutex - func MakeSCRestAPICall(scAddress string, relativePath string, params map[string]string, handler SCRestAPIHandler) ([]byte, error) { numSharders := len(blockchain.GetSharders()) sharders := blockchain.GetSharders() @@ -824,7 +822,6 @@ func MakeSCRestAPICall(scAddress string, relativePath string, params map[string] go func(sharder string) { defer wg.Done() - lock.Lock() urlString := fmt.Sprintf("%v/%v%v%v", sharder, SC_REST_API_URL, scAddress, relativePath) urlObj, err := url.ParseRequestURI(urlString) if err != nil { @@ -838,7 +835,6 @@ func MakeSCRestAPICall(scAddress string, relativePath string, params map[string] urlObj.RawQuery = q.Encode() client := &http.Client{Transport: DefaultTransport} s := urlObj.String() - lock.Unlock() response, err := client.Get(s) if err != nil { From 65a0152adc10754977a479e09cdb8d577ca8aefb Mon Sep 17 00:00:00 2001 From: dabasov Date: Wed, 15 Nov 2023 19:10:59 +0200 Subject: [PATCH 092/134] experiment --- zboxcore/zboxutil/http.go | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/zboxcore/zboxutil/http.go b/zboxcore/zboxutil/http.go index 2874131da..46e84fec7 100644 --- a/zboxcore/zboxutil/http.go +++ b/zboxcore/zboxutil/http.go @@ -817,26 +817,30 @@ func MakeSCRestAPICall(scAddress string, relativePath string, params map[string] return nil, err } + var urls []string for _, sharder := range sharders { + urlString := fmt.Sprintf("%v/%v%v%v", sharder, SC_REST_API_URL, scAddress, relativePath) + urlObj, err := url.Parse(urlString) + if err != nil { + log.Error(err) + continue + } + q := urlObj.Query() + for k, v := range params { + q.Add(k, v) + } + urlObj.RawQuery = q.Encode() + urls = append(urls, urlObj.String()) + } + + for _, sharder := range urls { wg.Add(1) go func(sharder string) { defer wg.Done() - urlString := fmt.Sprintf("%v/%v%v%v", sharder, SC_REST_API_URL, scAddress, relativePath) - urlObj, err := url.ParseRequestURI(urlString) - if err != nil { - log.Error(err) - return - } - q := urlObj.Query() - for k, v := range params { - q.Add(k, v) - } - urlObj.RawQuery = q.Encode() client := &http.Client{Transport: DefaultTransport} - s := urlObj.String() - response, err := client.Get(s) + response, err := client.Get(sharder) if err != nil { blockchain.Sharders.Fail(sharder) return From 6b6578bb857c9e4351db941fc84e65fac0994c15 Mon Sep 17 00:00:00 2001 From: dabasov Date: Wed, 15 Nov 2023 19:25:09 +0200 Subject: [PATCH 093/134] experiment --- zboxcore/zboxutil/http.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/zboxcore/zboxutil/http.go b/zboxcore/zboxutil/http.go index 46e84fec7..40879da08 100644 --- a/zboxcore/zboxutil/http.go +++ b/zboxcore/zboxutil/http.go @@ -817,7 +817,7 @@ func MakeSCRestAPICall(scAddress string, relativePath string, params map[string] return nil, err } - var urls []string + urls := make(map[string]string) for _, sharder := range sharders { urlString := fmt.Sprintf("%v/%v%v%v", sharder, SC_REST_API_URL, scAddress, relativePath) urlObj, err := url.Parse(urlString) @@ -830,17 +830,17 @@ func MakeSCRestAPICall(scAddress string, relativePath string, params map[string] q.Add(k, v) } urlObj.RawQuery = q.Encode() - urls = append(urls, urlObj.String()) + urls[sharder] = urlObj.String() } - for _, sharder := range urls { + for sharder, url := range urls { wg.Add(1) - go func(sharder string) { + go func(sharder, url string) { defer wg.Done() client := &http.Client{Transport: DefaultTransport} - response, err := client.Get(sharder) + response, err := client.Get(url) if err != nil { blockchain.Sharders.Fail(sharder) return @@ -867,7 +867,7 @@ func MakeSCRestAPICall(scAddress string, relativePath string, params map[string] entityResult[sharder] = entityBytes blockchain.Sharders.Success(sharder) mu.Unlock() - }(sharder) + }(sharder, url) } wg.Wait() From 3a23f3f33b9446cf5711f950b0cd80a40993e429 Mon Sep 17 00:00:00 2001 From: dabasov Date: Wed, 15 Nov 2023 20:18:29 +0200 Subject: [PATCH 094/134] experiment --- zboxcore/zboxutil/http.go | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/zboxcore/zboxutil/http.go b/zboxcore/zboxutil/http.go index 40879da08..7de1139e0 100644 --- a/zboxcore/zboxutil/http.go +++ b/zboxcore/zboxutil/http.go @@ -801,6 +801,8 @@ func NewRollbackRequest(baseUrl, allocationID string, allocationTx string, body return req, nil } +var lock sync.Mutex + func MakeSCRestAPICall(scAddress string, relativePath string, params map[string]string, handler SCRestAPIHandler) ([]byte, error) { numSharders := len(blockchain.GetSharders()) sharders := blockchain.GetSharders() @@ -819,6 +821,8 @@ func MakeSCRestAPICall(scAddress string, relativePath string, params map[string] urls := make(map[string]string) for _, sharder := range sharders { + lock.Lock() + urlString := fmt.Sprintf("%v/%v%v%v", sharder, SC_REST_API_URL, scAddress, relativePath) urlObj, err := url.Parse(urlString) if err != nil { @@ -831,9 +835,10 @@ func MakeSCRestAPICall(scAddress string, relativePath string, params map[string] } urlObj.RawQuery = q.Encode() urls[sharder] = urlObj.String() + lock.Unlock() } - for sharder, url := range urls { + for sharder, u := range urls { wg.Add(1) go func(sharder, url string) { defer wg.Done() @@ -867,7 +872,7 @@ func MakeSCRestAPICall(scAddress string, relativePath string, params map[string] entityResult[sharder] = entityBytes blockchain.Sharders.Success(sharder) mu.Unlock() - }(sharder, url) + }(sharder, u) } wg.Wait() From 68d41905a3aaf1c094d50f7b418349d7c78663cc Mon Sep 17 00:00:00 2001 From: dabasov Date: Wed, 15 Nov 2023 20:30:09 +0200 Subject: [PATCH 095/134] experiment --- zboxcore/zboxutil/http.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/zboxcore/zboxutil/http.go b/zboxcore/zboxutil/http.go index 7de1139e0..c3bf7b8e6 100644 --- a/zboxcore/zboxutil/http.go +++ b/zboxcore/zboxutil/http.go @@ -835,6 +835,7 @@ func MakeSCRestAPICall(scAddress string, relativePath string, params map[string] } urlObj.RawQuery = q.Encode() urls[sharder] = urlObj.String() + lock.Unlock() } @@ -954,8 +955,12 @@ func isCurrentDominantStatus(respStatus int, currentTotalPerStatus map[int]int, } func joinUrl(baseURl string, paths ...string) (*url.URL, error) { + lock.Lock() + defer lock.Unlock() + u, err := url.Parse(baseURl) if err != nil { + log.Error(err) return nil, err } p := path.Join(paths...) From b6be0b51767f39cb53a9439c3a34fe2f828b2dfc Mon Sep 17 00:00:00 2001 From: dabasov Date: Wed, 15 Nov 2023 22:28:33 +0200 Subject: [PATCH 096/134] experiment --- zboxcore/zboxutil/http.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zboxcore/zboxutil/http.go b/zboxcore/zboxutil/http.go index c3bf7b8e6..0ab6b4bc3 100644 --- a/zboxcore/zboxutil/http.go +++ b/zboxcore/zboxutil/http.go @@ -824,7 +824,7 @@ func MakeSCRestAPICall(scAddress string, relativePath string, params map[string] lock.Lock() urlString := fmt.Sprintf("%v/%v%v%v", sharder, SC_REST_API_URL, scAddress, relativePath) - urlObj, err := url.Parse(urlString) + urlObj, err := url.ParseRequestURI(urlString) if err != nil { log.Error(err) continue @@ -958,7 +958,7 @@ func joinUrl(baseURl string, paths ...string) (*url.URL, error) { lock.Lock() defer lock.Unlock() - u, err := url.Parse(baseURl) + u, err := url.ParseRequestURI(baseURl) if err != nil { log.Error(err) return nil, err From 6313cb8a49d211ab8a6c476ca839922be7c31288 Mon Sep 17 00:00:00 2001 From: dabasov Date: Wed, 15 Nov 2023 22:57:07 +0200 Subject: [PATCH 097/134] experiment --- zboxcore/zboxutil/http.go | 6 +- zboxcore/zboxutil/url.go | 1269 +++++++++++++++++++++++++++++++++++++ 2 files changed, 1272 insertions(+), 3 deletions(-) create mode 100644 zboxcore/zboxutil/url.go diff --git a/zboxcore/zboxutil/http.go b/zboxcore/zboxutil/http.go index 0ab6b4bc3..5c641707f 100644 --- a/zboxcore/zboxutil/http.go +++ b/zboxcore/zboxutil/http.go @@ -824,7 +824,7 @@ func MakeSCRestAPICall(scAddress string, relativePath string, params map[string] lock.Lock() urlString := fmt.Sprintf("%v/%v%v%v", sharder, SC_REST_API_URL, scAddress, relativePath) - urlObj, err := url.ParseRequestURI(urlString) + urlObj, err := Parse(urlString) if err != nil { log.Error(err) continue @@ -954,11 +954,11 @@ func isCurrentDominantStatus(respStatus int, currentTotalPerStatus map[int]int, return currentTotalPerStatus[respStatus] == currentMax && (respStatus == 200 || currentTotalPerStatus[200] < currentMax) } -func joinUrl(baseURl string, paths ...string) (*url.URL, error) { +func joinUrl(baseURl string, paths ...string) (*URL, error) { lock.Lock() defer lock.Unlock() - u, err := url.ParseRequestURI(baseURl) + u, err := Parse(baseURl) if err != nil { log.Error(err) return nil, err diff --git a/zboxcore/zboxutil/url.go b/zboxcore/zboxutil/url.go new file mode 100644 index 000000000..2c626c580 --- /dev/null +++ b/zboxcore/zboxutil/url.go @@ -0,0 +1,1269 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package url parses URLs and implements query escaping. +package zboxutil + +// See RFC 3986. This package generally follows RFC 3986, except where +// it deviates for compatibility reasons. When sending changes, first +// search old issues for history on decisions. Unit tests should also +// contain references to issue numbers with details. + +import ( + "errors" + "fmt" + "path" + "sort" + "strconv" + "strings" +) + +// Error reports an error and the operation and URL that caused it. +type Error struct { + Op string + URL string + Err error +} + +func (e *Error) Unwrap() error { return e.Err } +func (e *Error) Error() string { return fmt.Sprintf("%s %q: %s", e.Op, e.URL, e.Err) } + +func (e *Error) Timeout() bool { + t, ok := e.Err.(interface { + Timeout() bool + }) + return ok && t.Timeout() +} + +func (e *Error) Temporary() bool { + t, ok := e.Err.(interface { + Temporary() bool + }) + return ok && t.Temporary() +} + +const upperhex = "0123456789ABCDEF" + +func ishex(c byte) bool { + switch { + case '0' <= c && c <= '9': + return true + case 'a' <= c && c <= 'f': + return true + case 'A' <= c && c <= 'F': + return true + } + return false +} + +func unhex(c byte) byte { + switch { + case '0' <= c && c <= '9': + return c - '0' + case 'a' <= c && c <= 'f': + return c - 'a' + 10 + case 'A' <= c && c <= 'F': + return c - 'A' + 10 + } + return 0 +} + +type encoding int + +const ( + encodePath encoding = 1 + iota + encodePathSegment + encodeHost + encodeZone + encodeUserPassword + encodeQueryComponent + encodeFragment +) + +type EscapeError string + +func (e EscapeError) Error() string { + return "invalid URL escape " + strconv.Quote(string(e)) +} + +type InvalidHostError string + +func (e InvalidHostError) Error() string { + return "invalid character " + strconv.Quote(string(e)) + " in host name" +} + +// Return true if the specified character should be escaped when +// appearing in a URL string, according to RFC 3986. +// +// Please be informed that for now shouldEscape does not check all +// reserved characters correctly. See golang.org/issue/5684. +func shouldEscape(c byte, mode encoding) bool { + // §2.3 Unreserved characters (alphanum) + if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' { + return false + } + + if mode == encodeHost || mode == encodeZone { + // §3.2.2 Host allows + // sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" + // as part of reg-name. + // We add : because we include :port as part of host. + // We add [ ] because we include [ipv6]:port as part of host. + // We add < > because they're the only characters left that + // we could possibly allow, and Parse will reject them if we + // escape them (because hosts can't use %-encoding for + // ASCII bytes). + switch c { + case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '[', ']', '<', '>', '"': + return false + } + } + + switch c { + case '-', '_', '.', '~': // §2.3 Unreserved characters (mark) + return false + + case '$', '&', '+', ',', '/', ':', ';', '=', '?', '@': // §2.2 Reserved characters (reserved) + // Different sections of the URL allow a few of + // the reserved characters to appear unescaped. + switch mode { + case encodePath: // §3.3 + // The RFC allows : @ & = + $ but saves / ; , for assigning + // meaning to individual path segments. This package + // only manipulates the path as a whole, so we allow those + // last three as well. That leaves only ? to escape. + return c == '?' + + case encodePathSegment: // §3.3 + // The RFC allows : @ & = + $ but saves / ; , for assigning + // meaning to individual path segments. + return c == '/' || c == ';' || c == ',' || c == '?' + + case encodeUserPassword: // §3.2.1 + // The RFC allows ';', ':', '&', '=', '+', '$', and ',' in + // userinfo, so we must escape only '@', '/', and '?'. + // The parsing of userinfo treats ':' as special so we must escape + // that too. + return c == '@' || c == '/' || c == '?' || c == ':' + + case encodeQueryComponent: // §3.4 + // The RFC reserves (so we must escape) everything. + return true + + case encodeFragment: // §4.1 + // The RFC text is silent but the grammar allows + // everything, so escape nothing. + return false + } + } + + if mode == encodeFragment { + // RFC 3986 §2.2 allows not escaping sub-delims. A subset of sub-delims are + // included in reserved from RFC 2396 §2.2. The remaining sub-delims do not + // need to be escaped. To minimize potential breakage, we apply two restrictions: + // (1) we always escape sub-delims outside of the fragment, and (2) we always + // escape single quote to avoid breaking callers that had previously assumed that + // single quotes would be escaped. See issue #19917. + switch c { + case '!', '(', ')', '*': + return false + } + } + + // Everything else must be escaped. + return true +} + +// QueryUnescape does the inverse transformation of QueryEscape, +// converting each 3-byte encoded substring of the form "%AB" into the +// hex-decoded byte 0xAB. +// It returns an error if any % is not followed by two hexadecimal +// digits. +func QueryUnescape(s string) (string, error) { + return unescape(s, encodeQueryComponent) +} + +// PathUnescape does the inverse transformation of PathEscape, +// converting each 3-byte encoded substring of the form "%AB" into the +// hex-decoded byte 0xAB. It returns an error if any % is not followed +// by two hexadecimal digits. +// +// PathUnescape is identical to QueryUnescape except that it does not +// unescape '+' to ' ' (space). +func PathUnescape(s string) (string, error) { + return unescape(s, encodePathSegment) +} + +// unescape unescapes a string; the mode specifies +// which section of the URL string is being unescaped. +func unescape(s string, mode encoding) (string, error) { + // Count %, check that they're well-formed. + n := 0 + hasPlus := false + for i := 0; i < len(s); { + switch s[i] { + case '%': + n++ + if i+2 >= len(s) || !ishex(s[i+1]) || !ishex(s[i+2]) { + s = s[i:] + if len(s) > 3 { + s = s[:3] + } + return "", EscapeError(s) + } + // Per https://tools.ietf.org/html/rfc3986#page-21 + // in the host component %-encoding can only be used + // for non-ASCII bytes. + // But https://tools.ietf.org/html/rfc6874#section-2 + // introduces %25 being allowed to escape a percent sign + // in IPv6 scoped-address literals. Yay. + if mode == encodeHost && unhex(s[i+1]) < 8 && s[i:i+3] != "%25" { + return "", EscapeError(s[i : i+3]) + } + if mode == encodeZone { + // RFC 6874 says basically "anything goes" for zone identifiers + // and that even non-ASCII can be redundantly escaped, + // but it seems prudent to restrict %-escaped bytes here to those + // that are valid host name bytes in their unescaped form. + // That is, you can use escaping in the zone identifier but not + // to introduce bytes you couldn't just write directly. + // But Windows puts spaces here! Yay. + v := unhex(s[i+1])<<4 | unhex(s[i+2]) + if s[i:i+3] != "%25" && v != ' ' && shouldEscape(v, encodeHost) { + return "", EscapeError(s[i : i+3]) + } + } + i += 3 + case '+': + hasPlus = mode == encodeQueryComponent + i++ + default: + if (mode == encodeHost || mode == encodeZone) && s[i] < 0x80 && shouldEscape(s[i], mode) { + log.Error(s) + return "", InvalidHostError(s[i : i+1]) + } + i++ + } + } + + if n == 0 && !hasPlus { + return s, nil + } + + var t strings.Builder + t.Grow(len(s) - 2*n) + for i := 0; i < len(s); i++ { + switch s[i] { + case '%': + t.WriteByte(unhex(s[i+1])<<4 | unhex(s[i+2])) + i += 2 + case '+': + if mode == encodeQueryComponent { + t.WriteByte(' ') + } else { + t.WriteByte('+') + } + default: + t.WriteByte(s[i]) + } + } + return t.String(), nil +} + +// QueryEscape escapes the string so it can be safely placed +// inside a URL query. +func QueryEscape(s string) string { + return escape(s, encodeQueryComponent) +} + +// PathEscape escapes the string so it can be safely placed inside a URL path segment, +// replacing special characters (including /) with %XX sequences as needed. +func PathEscape(s string) string { + return escape(s, encodePathSegment) +} + +func escape(s string, mode encoding) string { + spaceCount, hexCount := 0, 0 + for i := 0; i < len(s); i++ { + c := s[i] + if shouldEscape(c, mode) { + if c == ' ' && mode == encodeQueryComponent { + spaceCount++ + } else { + hexCount++ + } + } + } + + if spaceCount == 0 && hexCount == 0 { + return s + } + + var buf [64]byte + var t []byte + + required := len(s) + 2*hexCount + if required <= len(buf) { + t = buf[:required] + } else { + t = make([]byte, required) + } + + if hexCount == 0 { + copy(t, s) + for i := 0; i < len(s); i++ { + if s[i] == ' ' { + t[i] = '+' + } + } + return string(t) + } + + j := 0 + for i := 0; i < len(s); i++ { + switch c := s[i]; { + case c == ' ' && mode == encodeQueryComponent: + t[j] = '+' + j++ + case shouldEscape(c, mode): + t[j] = '%' + t[j+1] = upperhex[c>>4] + t[j+2] = upperhex[c&15] + j += 3 + default: + t[j] = s[i] + j++ + } + } + return string(t) +} + +// A URL represents a parsed URL (technically, a URI reference). +// +// The general form represented is: +// +// [scheme:][//[userinfo@]host][/]path[?query][#fragment] +// +// URLs that do not start with a slash after the scheme are interpreted as: +// +// scheme:opaque[?query][#fragment] +// +// Note that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/. +// A consequence is that it is impossible to tell which slashes in the Path were +// slashes in the raw URL and which were %2f. This distinction is rarely important, +// but when it is, the code should use the EscapedPath method, which preserves +// the original encoding of Path. +// +// The RawPath field is an optional field which is only set when the default +// encoding of Path is different from the escaped path. See the EscapedPath method +// for more details. +// +// URL's String method uses the EscapedPath method to obtain the path. +type URL struct { + Scheme string + Opaque string // encoded opaque data + User *Userinfo // username and password information + Host string // host or host:port + Path string // path (relative paths may omit leading slash) + RawPath string // encoded path hint (see EscapedPath method) + OmitHost bool // do not emit empty host (authority) + ForceQuery bool // append a query ('?') even if RawQuery is empty + RawQuery string // encoded query values, without '?' + Fragment string // fragment for references, without '#' + RawFragment string // encoded fragment hint (see EscapedFragment method) +} + +// User returns a Userinfo containing the provided username +// and no password set. +func User(username string) *Userinfo { + return &Userinfo{username, "", false} +} + +// UserPassword returns a Userinfo containing the provided username +// and password. +// +// This functionality should only be used with legacy web sites. +// RFC 2396 warns that interpreting Userinfo this way +// “is NOT RECOMMENDED, because the passing of authentication +// information in clear text (such as URI) has proven to be a +// security risk in almost every case where it has been used.” +func UserPassword(username, password string) *Userinfo { + return &Userinfo{username, password, true} +} + +// The Userinfo type is an immutable encapsulation of username and +// password details for a URL. An existing Userinfo value is guaranteed +// to have a username set (potentially empty, as allowed by RFC 2396), +// and optionally a password. +type Userinfo struct { + username string + password string + passwordSet bool +} + +// Username returns the username. +func (u *Userinfo) Username() string { + if u == nil { + return "" + } + return u.username +} + +// Password returns the password in case it is set, and whether it is set. +func (u *Userinfo) Password() (string, bool) { + if u == nil { + return "", false + } + return u.password, u.passwordSet +} + +// String returns the encoded userinfo information in the standard form +// of "username[:password]". +func (u *Userinfo) String() string { + if u == nil { + return "" + } + s := escape(u.username, encodeUserPassword) + if u.passwordSet { + s += ":" + escape(u.password, encodeUserPassword) + } + return s +} + +// Maybe rawURL is of the form scheme:path. +// (Scheme must be [a-zA-Z][a-zA-Z0-9+.-]*) +// If so, return scheme, path; else return "", rawURL. +func getScheme(rawURL string) (scheme, path string, err error) { + for i := 0; i < len(rawURL); i++ { + c := rawURL[i] + switch { + case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z': + // do nothing + case '0' <= c && c <= '9' || c == '+' || c == '-' || c == '.': + if i == 0 { + return "", rawURL, nil + } + case c == ':': + if i == 0 { + return "", "", errors.New("missing protocol scheme") + } + return rawURL[:i], rawURL[i+1:], nil + default: + // we have encountered an invalid character, + // so there is no valid scheme + return "", rawURL, nil + } + } + return "", rawURL, nil +} + +// Parse parses a raw url into a URL structure. +// +// The url may be relative (a path, without a host) or absolute +// (starting with a scheme). Trying to parse a hostname and path +// without a scheme is invalid but may not necessarily return an +// error, due to parsing ambiguities. +func Parse(rawURL string) (*URL, error) { + // Cut off #frag + u, frag, _ := strings.Cut(rawURL, "#") + url, err := parse(u, false) + if err != nil { + return nil, &Error{"parse", u, err} + } + if frag == "" { + return url, nil + } + if err = url.setFragment(frag); err != nil { + return nil, &Error{"parse", rawURL, err} + } + return url, nil +} + +// ParseRequestURI parses a raw url into a URL structure. It assumes that +// url was received in an HTTP request, so the url is interpreted +// only as an absolute URI or an absolute path. +// The string url is assumed not to have a #fragment suffix. +// (Web browsers strip #fragment before sending the URL to a web server.) +func ParseRequestURI(rawURL string) (*URL, error) { + url, err := parse(rawURL, true) + if err != nil { + return nil, &Error{"parse", rawURL, err} + } + return url, nil +} + +// parse parses a URL from a string in one of two contexts. If +// viaRequest is true, the URL is assumed to have arrived via an HTTP request, +// in which case only absolute URLs or path-absolute relative URLs are allowed. +// If viaRequest is false, all forms of relative URLs are allowed. +func parse(rawURL string, viaRequest bool) (*URL, error) { + var rest string + var err error + + if stringContainsCTLByte(rawURL) { + return nil, errors.New("net/url: invalid control character in URL") + } + + if rawURL == "" && viaRequest { + return nil, errors.New("empty url") + } + url := new(URL) + + if rawURL == "*" { + url.Path = "*" + return url, nil + } + + // Split off possible leading "http:", "mailto:", etc. + // Cannot contain escaped characters. + if url.Scheme, rest, err = getScheme(rawURL); err != nil { + return nil, err + } + url.Scheme = strings.ToLower(url.Scheme) + + if strings.HasSuffix(rest, "?") && strings.Count(rest, "?") == 1 { + url.ForceQuery = true + rest = rest[:len(rest)-1] + } else { + rest, url.RawQuery, _ = strings.Cut(rest, "?") + } + + if !strings.HasPrefix(rest, "/") { + if url.Scheme != "" { + // We consider rootless paths per RFC 3986 as opaque. + url.Opaque = rest + return url, nil + } + if viaRequest { + return nil, errors.New("invalid URI for request") + } + + // Avoid confusion with malformed schemes, like cache_object:foo/bar. + // See golang.org/issue/16822. + // + // RFC 3986, §3.3: + // In addition, a URI reference (Section 4.1) may be a relative-path reference, + // in which case the first path segment cannot contain a colon (":") character. + if segment, _, _ := strings.Cut(rest, "/"); strings.Contains(segment, ":") { + // First path segment has colon. Not allowed in relative URL. + return nil, errors.New("first path segment in URL cannot contain colon") + } + } + + if (url.Scheme != "" || !viaRequest && !strings.HasPrefix(rest, "///")) && strings.HasPrefix(rest, "//") { + var authority string + authority, rest = rest[2:], "" + if i := strings.Index(authority, "/"); i >= 0 { + authority, rest = authority[:i], authority[i:] + } + url.User, url.Host, err = parseAuthority(authority) + if err != nil { + return nil, err + } + } else if url.Scheme != "" && strings.HasPrefix(rest, "/") { + // OmitHost is set to true when rawURL has an empty host (authority). + // See golang.org/issue/46059. + url.OmitHost = true + } + + // Set Path and, optionally, RawPath. + // RawPath is a hint of the encoding of Path. We don't want to set it if + // the default escaping of Path is equivalent, to help make sure that people + // don't rely on it in general. + if err := url.setPath(rest); err != nil { + return nil, err + } + return url, nil +} + +func parseAuthority(authority string) (user *Userinfo, host string, err error) { + i := strings.LastIndex(authority, "@") + if i < 0 { + host, err = parseHost(authority) + } else { + host, err = parseHost(authority[i+1:]) + } + if err != nil { + return nil, "", err + } + if i < 0 { + return nil, host, nil + } + userinfo := authority[:i] + if !validUserinfo(userinfo) { + return nil, "", errors.New("net/url: invalid userinfo") + } + if !strings.Contains(userinfo, ":") { + if userinfo, err = unescape(userinfo, encodeUserPassword); err != nil { + return nil, "", err + } + user = User(userinfo) + } else { + username, password, _ := strings.Cut(userinfo, ":") + if username, err = unescape(username, encodeUserPassword); err != nil { + return nil, "", err + } + if password, err = unescape(password, encodeUserPassword); err != nil { + return nil, "", err + } + user = UserPassword(username, password) + } + return user, host, nil +} + +// parseHost parses host as an authority without user +// information. That is, as host[:port]. +func parseHost(host string) (string, error) { + if strings.HasPrefix(host, "[") { + // Parse an IP-Literal in RFC 3986 and RFC 6874. + // E.g., "[fe80::1]", "[fe80::1%25en0]", "[fe80::1]:80". + i := strings.LastIndex(host, "]") + if i < 0 { + return "", errors.New("missing ']' in host") + } + colonPort := host[i+1:] + if !validOptionalPort(colonPort) { + return "", fmt.Errorf("invalid port %q after host", colonPort) + } + + // RFC 6874 defines that %25 (%-encoded percent) introduces + // the zone identifier, and the zone identifier can use basically + // any %-encoding it likes. That's different from the host, which + // can only %-encode non-ASCII bytes. + // We do impose some restrictions on the zone, to avoid stupidity + // like newlines. + zone := strings.Index(host[:i], "%25") + if zone >= 0 { + host1, err := unescape(host[:zone], encodeHost) + if err != nil { + return "", err + } + host2, err := unescape(host[zone:i], encodeZone) + if err != nil { + return "", err + } + host3, err := unescape(host[i:], encodeHost) + if err != nil { + return "", err + } + return host1 + host2 + host3, nil + } + } else if i := strings.LastIndex(host, ":"); i != -1 { + colonPort := host[i:] + if !validOptionalPort(colonPort) { + return "", fmt.Errorf("invalid port %q after host", colonPort) + } + } + + var err error + if host, err = unescape(host, encodeHost); err != nil { + return "", err + } + return host, nil +} + +// setPath sets the Path and RawPath fields of the URL based on the provided +// escaped path p. It maintains the invariant that RawPath is only specified +// when it differs from the default encoding of the path. +// For example: +// - setPath("/foo/bar") will set Path="/foo/bar" and RawPath="" +// - setPath("/foo%2fbar") will set Path="/foo/bar" and RawPath="/foo%2fbar" +// setPath will return an error only if the provided path contains an invalid +// escaping. +func (u *URL) setPath(p string) error { + path, err := unescape(p, encodePath) + if err != nil { + return err + } + u.Path = path + if escp := escape(path, encodePath); p == escp { + // Default encoding is fine. + u.RawPath = "" + } else { + u.RawPath = p + } + return nil +} + +// EscapedPath returns the escaped form of u.Path. +// In general there are multiple possible escaped forms of any path. +// EscapedPath returns u.RawPath when it is a valid escaping of u.Path. +// Otherwise EscapedPath ignores u.RawPath and computes an escaped +// form on its own. +// The String and RequestURI methods use EscapedPath to construct +// their results. +// In general, code should call EscapedPath instead of +// reading u.RawPath directly. +func (u *URL) EscapedPath() string { + if u.RawPath != "" && validEncoded(u.RawPath, encodePath) { + p, err := unescape(u.RawPath, encodePath) + if err == nil && p == u.Path { + return u.RawPath + } + } + if u.Path == "*" { + return "*" // don't escape (Issue 11202) + } + return escape(u.Path, encodePath) +} + +// validEncoded reports whether s is a valid encoded path or fragment, +// according to mode. +// It must not contain any bytes that require escaping during encoding. +func validEncoded(s string, mode encoding) bool { + for i := 0; i < len(s); i++ { + // RFC 3986, Appendix A. + // pchar = unreserved / pct-encoded / sub-delims / ":" / "@". + // shouldEscape is not quite compliant with the RFC, + // so we check the sub-delims ourselves and let + // shouldEscape handle the others. + switch s[i] { + case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '@': + // ok + case '[', ']': + // ok - not specified in RFC 3986 but left alone by modern browsers + case '%': + // ok - percent encoded, will decode + default: + if shouldEscape(s[i], mode) { + return false + } + } + } + return true +} + +// setFragment is like setPath but for Fragment/RawFragment. +func (u *URL) setFragment(f string) error { + frag, err := unescape(f, encodeFragment) + if err != nil { + return err + } + u.Fragment = frag + if escf := escape(frag, encodeFragment); f == escf { + // Default encoding is fine. + u.RawFragment = "" + } else { + u.RawFragment = f + } + return nil +} + +// EscapedFragment returns the escaped form of u.Fragment. +// In general there are multiple possible escaped forms of any fragment. +// EscapedFragment returns u.RawFragment when it is a valid escaping of u.Fragment. +// Otherwise EscapedFragment ignores u.RawFragment and computes an escaped +// form on its own. +// The String method uses EscapedFragment to construct its result. +// In general, code should call EscapedFragment instead of +// reading u.RawFragment directly. +func (u *URL) EscapedFragment() string { + if u.RawFragment != "" && validEncoded(u.RawFragment, encodeFragment) { + f, err := unescape(u.RawFragment, encodeFragment) + if err == nil && f == u.Fragment { + return u.RawFragment + } + } + return escape(u.Fragment, encodeFragment) +} + +// validOptionalPort reports whether port is either an empty string +// or matches /^:\d*$/ +func validOptionalPort(port string) bool { + if port == "" { + return true + } + if port[0] != ':' { + return false + } + for _, b := range port[1:] { + if b < '0' || b > '9' { + return false + } + } + return true +} + +// String reassembles the URL into a valid URL string. +// The general form of the result is one of: +// +// scheme:opaque?query#fragment +// scheme://userinfo@host/path?query#fragment +// +// If u.Opaque is non-empty, String uses the first form; +// otherwise it uses the second form. +// Any non-ASCII characters in host are escaped. +// To obtain the path, String uses u.EscapedPath(). +// +// In the second form, the following rules apply: +// - if u.Scheme is empty, scheme: is omitted. +// - if u.User is nil, userinfo@ is omitted. +// - if u.Host is empty, host/ is omitted. +// - if u.Scheme and u.Host are empty and u.User is nil, +// the entire scheme://userinfo@host/ is omitted. +// - if u.Host is non-empty and u.Path begins with a /, +// the form host/path does not add its own /. +// - if u.RawQuery is empty, ?query is omitted. +// - if u.Fragment is empty, #fragment is omitted. +func (u *URL) String() string { + var buf strings.Builder + if u.Scheme != "" { + buf.WriteString(u.Scheme) + buf.WriteByte(':') + } + if u.Opaque != "" { + buf.WriteString(u.Opaque) + } else { + if u.Scheme != "" || u.Host != "" || u.User != nil { + if u.OmitHost && u.Host == "" && u.User == nil { + // omit empty host + } else { + if u.Host != "" || u.Path != "" || u.User != nil { + buf.WriteString("//") + } + if ui := u.User; ui != nil { + buf.WriteString(ui.String()) + buf.WriteByte('@') + } + if h := u.Host; h != "" { + buf.WriteString(escape(h, encodeHost)) + } + } + } + path := u.EscapedPath() + if path != "" && path[0] != '/' && u.Host != "" { + buf.WriteByte('/') + } + if buf.Len() == 0 { + // RFC 3986 §4.2 + // A path segment that contains a colon character (e.g., "this:that") + // cannot be used as the first segment of a relative-path reference, as + // it would be mistaken for a scheme name. Such a segment must be + // preceded by a dot-segment (e.g., "./this:that") to make a relative- + // path reference. + if segment, _, _ := strings.Cut(path, "/"); strings.Contains(segment, ":") { + buf.WriteString("./") + } + } + buf.WriteString(path) + } + if u.ForceQuery || u.RawQuery != "" { + buf.WriteByte('?') + buf.WriteString(u.RawQuery) + } + if u.Fragment != "" { + buf.WriteByte('#') + buf.WriteString(u.EscapedFragment()) + } + return buf.String() +} + +// Redacted is like String but replaces any password with "xxxxx". +// Only the password in u.URL is redacted. +func (u *URL) Redacted() string { + if u == nil { + return "" + } + + ru := *u + if _, has := ru.User.Password(); has { + ru.User = UserPassword(ru.User.Username(), "xxxxx") + } + return ru.String() +} + +// Values maps a string key to a list of values. +// It is typically used for query parameters and form values. +// Unlike in the http.Header map, the keys in a Values map +// are case-sensitive. +type Values map[string][]string + +// Get gets the first value associated with the given key. +// If there are no values associated with the key, Get returns +// the empty string. To access multiple values, use the map +// directly. +func (v Values) Get(key string) string { + if v == nil { + return "" + } + vs := v[key] + if len(vs) == 0 { + return "" + } + return vs[0] +} + +// Set sets the key to value. It replaces any existing +// values. +func (v Values) Set(key, value string) { + v[key] = []string{value} +} + +// Add adds the value to key. It appends to any existing +// values associated with key. +func (v Values) Add(key, value string) { + v[key] = append(v[key], value) +} + +// Del deletes the values associated with key. +func (v Values) Del(key string) { + delete(v, key) +} + +// Has checks whether a given key is set. +func (v Values) Has(key string) bool { + _, ok := v[key] + return ok +} + +// ParseQuery parses the URL-encoded query string and returns +// a map listing the values specified for each key. +// ParseQuery always returns a non-nil map containing all the +// valid query parameters found; err describes the first decoding error +// encountered, if any. +// +// Query is expected to be a list of key=value settings separated by ampersands. +// A setting without an equals sign is interpreted as a key set to an empty +// value. +// Settings containing a non-URL-encoded semicolon are considered invalid. +func ParseQuery(query string) (Values, error) { + m := make(Values) + err := parseQuery(m, query) + return m, err +} + +func parseQuery(m Values, query string) (err error) { + for query != "" { + var key string + key, query, _ = strings.Cut(query, "&") + if strings.Contains(key, ";") { + err = fmt.Errorf("invalid semicolon separator in query") + continue + } + if key == "" { + continue + } + key, value, _ := strings.Cut(key, "=") + key, err1 := QueryUnescape(key) + if err1 != nil { + if err == nil { + err = err1 + } + continue + } + value, err1 = QueryUnescape(value) + if err1 != nil { + if err == nil { + err = err1 + } + continue + } + m[key] = append(m[key], value) + } + return err +} + +// Encode encodes the values into “URL encoded” form +// ("bar=baz&foo=quux") sorted by key. +func (v Values) Encode() string { + if v == nil { + return "" + } + var buf strings.Builder + keys := make([]string, 0, len(v)) + for k := range v { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + vs := v[k] + keyEscaped := QueryEscape(k) + for _, v := range vs { + if buf.Len() > 0 { + buf.WriteByte('&') + } + buf.WriteString(keyEscaped) + buf.WriteByte('=') + buf.WriteString(QueryEscape(v)) + } + } + return buf.String() +} + +// resolvePath applies special path segments from refs and applies +// them to base, per RFC 3986. +func resolvePath(base, ref string) string { + var full string + if ref == "" { + full = base + } else if ref[0] != '/' { + i := strings.LastIndex(base, "/") + full = base[:i+1] + ref + } else { + full = ref + } + if full == "" { + return "" + } + + var ( + elem string + dst strings.Builder + ) + first := true + remaining := full + // We want to return a leading '/', so write it now. + dst.WriteByte('/') + found := true + for found { + elem, remaining, found = strings.Cut(remaining, "/") + if elem == "." { + first = false + // drop + continue + } + + if elem == ".." { + // Ignore the leading '/' we already wrote. + str := dst.String()[1:] + index := strings.LastIndexByte(str, '/') + + dst.Reset() + dst.WriteByte('/') + if index == -1 { + first = true + } else { + dst.WriteString(str[:index]) + } + } else { + if !first { + dst.WriteByte('/') + } + dst.WriteString(elem) + first = false + } + } + + if elem == "." || elem == ".." { + dst.WriteByte('/') + } + + // We wrote an initial '/', but we don't want two. + r := dst.String() + if len(r) > 1 && r[1] == '/' { + r = r[1:] + } + return r +} + +// IsAbs reports whether the URL is absolute. +// Absolute means that it has a non-empty scheme. +func (u *URL) IsAbs() bool { + return u.Scheme != "" +} + +// Parse parses a URL in the context of the receiver. The provided URL +// may be relative or absolute. Parse returns nil, err on parse +// failure, otherwise its return value is the same as ResolveReference. +func (u *URL) Parse(ref string) (*URL, error) { + refURL, err := Parse(ref) + if err != nil { + return nil, err + } + return u.ResolveReference(refURL), nil +} + +// ResolveReference resolves a URI reference to an absolute URI from +// an absolute base URI u, per RFC 3986 Section 5.2. The URI reference +// may be relative or absolute. ResolveReference always returns a new +// URL instance, even if the returned URL is identical to either the +// base or reference. If ref is an absolute URL, then ResolveReference +// ignores base and returns a copy of ref. +func (u *URL) ResolveReference(ref *URL) *URL { + url := *ref + if ref.Scheme == "" { + url.Scheme = u.Scheme + } + if ref.Scheme != "" || ref.Host != "" || ref.User != nil { + // The "absoluteURI" or "net_path" cases. + // We can ignore the error from setPath since we know we provided a + // validly-escaped path. + url.setPath(resolvePath(ref.EscapedPath(), "")) + return &url + } + if ref.Opaque != "" { + url.User = nil + url.Host = "" + url.Path = "" + return &url + } + if ref.Path == "" && !ref.ForceQuery && ref.RawQuery == "" { + url.RawQuery = u.RawQuery + if ref.Fragment == "" { + url.Fragment = u.Fragment + url.RawFragment = u.RawFragment + } + } + // The "abs_path" or "rel_path" cases. + url.Host = u.Host + url.User = u.User + url.setPath(resolvePath(u.EscapedPath(), ref.EscapedPath())) + return &url +} + +// Query parses RawQuery and returns the corresponding values. +// It silently discards malformed value pairs. +// To check errors use ParseQuery. +func (u *URL) Query() Values { + v, _ := ParseQuery(u.RawQuery) + return v +} + +// RequestURI returns the encoded path?query or opaque?query +// string that would be used in an HTTP request for u. +func (u *URL) RequestURI() string { + result := u.Opaque + if result == "" { + result = u.EscapedPath() + if result == "" { + result = "/" + } + } else { + if strings.HasPrefix(result, "//") { + result = u.Scheme + ":" + result + } + } + if u.ForceQuery || u.RawQuery != "" { + result += "?" + u.RawQuery + } + return result +} + +// Hostname returns u.Host, stripping any valid port number if present. +// +// If the result is enclosed in square brackets, as literal IPv6 addresses are, +// the square brackets are removed from the result. +func (u *URL) Hostname() string { + host, _ := splitHostPort(u.Host) + return host +} + +// Port returns the port part of u.Host, without the leading colon. +// +// If u.Host doesn't contain a valid numeric port, Port returns an empty string. +func (u *URL) Port() string { + _, port := splitHostPort(u.Host) + return port +} + +// splitHostPort separates host and port. If the port is not valid, it returns +// the entire input as host, and it doesn't check the validity of the host. +// Unlike net.SplitHostPort, but per RFC 3986, it requires ports to be numeric. +func splitHostPort(hostPort string) (host, port string) { + host = hostPort + + colon := strings.LastIndexByte(host, ':') + if colon != -1 && validOptionalPort(host[colon:]) { + host, port = host[:colon], host[colon+1:] + } + + if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") { + host = host[1 : len(host)-1] + } + + return +} + +// Marshaling interface implementations. +// Would like to implement MarshalText/UnmarshalText but that will change the JSON representation of URLs. + +func (u *URL) MarshalBinary() (text []byte, err error) { + return []byte(u.String()), nil +} + +func (u *URL) UnmarshalBinary(text []byte) error { + u1, err := Parse(string(text)) + if err != nil { + return err + } + *u = *u1 + return nil +} + +// JoinPath returns a new URL with the provided path elements joined to +// any existing path and the resulting path cleaned of any ./ or ../ elements. +// Any sequences of multiple / characters will be reduced to a single /. +func (u *URL) JoinPath(elem ...string) *URL { + elem = append([]string{u.EscapedPath()}, elem...) + var p string + if !strings.HasPrefix(elem[0], "/") { + // Return a relative path if u is relative, + // but ensure that it contains no ../ elements. + elem[0] = "/" + elem[0] + p = path.Join(elem...)[1:] + } else { + p = path.Join(elem...) + } + // path.Join will remove any trailing slashes. + // Preserve at least one. + if strings.HasSuffix(elem[len(elem)-1], "/") && !strings.HasSuffix(p, "/") { + p += "/" + } + url := *u + url.setPath(p) + return &url +} + +// validUserinfo reports whether s is a valid userinfo string per RFC 3986 +// Section 3.2.1: +// +// userinfo = *( unreserved / pct-encoded / sub-delims / ":" ) +// unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" +// sub-delims = "!" / "$" / "&" / "'" / "(" / ")" +// / "*" / "+" / "," / ";" / "=" +// +// It doesn't validate pct-encoded. The caller does that via func unescape. +func validUserinfo(s string) bool { + for _, r := range s { + if 'A' <= r && r <= 'Z' { + continue + } + if 'a' <= r && r <= 'z' { + continue + } + if '0' <= r && r <= '9' { + continue + } + switch r { + case '-', '.', '_', ':', '~', '!', '$', '&', '\'', + '(', ')', '*', '+', ',', ';', '=', '%', '@': + continue + default: + return false + } + } + return true +} + +// stringContainsCTLByte reports whether s contains any ASCII control character. +func stringContainsCTLByte(s string) bool { + for i := 0; i < len(s); i++ { + b := s[i] + if b < ' ' || b == 0x7f { + return true + } + } + return false +} + +// JoinPath returns a URL string with the provided path elements joined to +// the existing path of base and the resulting path cleaned of any ./ or ../ elements. +func JoinPath(base string, elem ...string) (result string, err error) { + url, err := Parse(base) + if err != nil { + return + } + result = url.JoinPath(elem...).String() + return +} From 9f65b2eef30528662b59482a6c59d6a633f1ff77 Mon Sep 17 00:00:00 2001 From: dabasov Date: Wed, 15 Nov 2023 23:44:22 +0200 Subject: [PATCH 098/134] experiment --- core/version/version.go | 4 ++-- zboxcore/zboxutil/url.go | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/core/version/version.go b/core/version/version.go index 459a91ad3..d1467c788 100644 --- a/core/version/version.go +++ b/core/version/version.go @@ -1,5 +1,5 @@ - //====== THIS IS AUTOGENERATED FILE. DO NOT MODIFY ======== package version -const VERSIONSTR = "v1.10.0-100-gf600e64b" + +const VERSIONSTR = "v1.10.0-111-g6313cb8a" diff --git a/zboxcore/zboxutil/url.go b/zboxcore/zboxutil/url.go index 2c626c580..7d0bf5dcb 100644 --- a/zboxcore/zboxutil/url.go +++ b/zboxcore/zboxutil/url.go @@ -241,7 +241,7 @@ func unescape(s string, mode encoding) (string, error) { default: if (mode == encodeHost || mode == encodeZone) && s[i] < 0x80 && shouldEscape(s[i], mode) { log.Error(s) - return "", InvalidHostError(s[i : i+1]) + return "", InvalidHostError(s) } i++ } From d4821f8e28c4efce59775129b4f25eaa1df2905d Mon Sep 17 00:00:00 2001 From: dabasov Date: Thu, 16 Nov 2023 00:01:00 +0200 Subject: [PATCH 099/134] experiment --- core/conf/config.go | 4 +- core/util/url.go | 1268 ++++++++++++++++++++++++++++++++++++++++ sdks/client.go | 4 +- zcnbridge/http/rest.go | 5 +- 4 files changed, 1274 insertions(+), 7 deletions(-) create mode 100644 core/util/url.go diff --git a/core/conf/config.go b/core/conf/config.go index aae29ff2a..dfd1da32c 100644 --- a/core/conf/config.go +++ b/core/conf/config.go @@ -2,12 +2,12 @@ package conf import ( "errors" - "net/url" "os" "strings" thrown "github.com/0chain/errors" "github.com/0chain/gosdk/core/sys" + "github.com/0chain/gosdk/core/util" "github.com/spf13/viper" ) @@ -171,6 +171,6 @@ func LoadConfig(v Reader) (Config, error) { } func isURL(s string) bool { - u, err := url.Parse(s) + u, err := util.Parse(s) return err == nil && u.Scheme != "" && u.Host != "" } diff --git a/core/util/url.go b/core/util/url.go new file mode 100644 index 000000000..094a5fc43 --- /dev/null +++ b/core/util/url.go @@ -0,0 +1,1268 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package url parses URLs and implements query escaping. +package util + +// See RFC 3986. This package generally follows RFC 3986, except where +// it deviates for compatibility reasons. When sending changes, first +// search old issues for history on decisions. Unit tests should also +// contain references to issue numbers with details. + +import ( + "errors" + "fmt" + "path" + "sort" + "strconv" + "strings" +) + +// Error reports an error and the operation and URL that caused it. +type Error struct { + Op string + URL string + Err error +} + +func (e *Error) Unwrap() error { return e.Err } +func (e *Error) Error() string { return fmt.Sprintf("%s %q: %s", e.Op, e.URL, e.Err) } + +func (e *Error) Timeout() bool { + t, ok := e.Err.(interface { + Timeout() bool + }) + return ok && t.Timeout() +} + +func (e *Error) Temporary() bool { + t, ok := e.Err.(interface { + Temporary() bool + }) + return ok && t.Temporary() +} + +const upperhex = "0123456789ABCDEF" + +func ishex(c byte) bool { + switch { + case '0' <= c && c <= '9': + return true + case 'a' <= c && c <= 'f': + return true + case 'A' <= c && c <= 'F': + return true + } + return false +} + +func unhex(c byte) byte { + switch { + case '0' <= c && c <= '9': + return c - '0' + case 'a' <= c && c <= 'f': + return c - 'a' + 10 + case 'A' <= c && c <= 'F': + return c - 'A' + 10 + } + return 0 +} + +type encoding int + +const ( + encodePath encoding = 1 + iota + encodePathSegment + encodeHost + encodeZone + encodeUserPassword + encodeQueryComponent + encodeFragment +) + +type EscapeError string + +func (e EscapeError) Error() string { + return "invalid URL escape " + strconv.Quote(string(e)) +} + +type InvalidHostError string + +func (e InvalidHostError) Error() string { + return "invalid character " + strconv.Quote(string(e)) + " in host name" +} + +// Return true if the specified character should be escaped when +// appearing in a URL string, according to RFC 3986. +// +// Please be informed that for now shouldEscape does not check all +// reserved characters correctly. See golang.org/issue/5684. +func shouldEscape(c byte, mode encoding) bool { + // §2.3 Unreserved characters (alphanum) + if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' { + return false + } + + if mode == encodeHost || mode == encodeZone { + // §3.2.2 Host allows + // sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" + // as part of reg-name. + // We add : because we include :port as part of host. + // We add [ ] because we include [ipv6]:port as part of host. + // We add < > because they're the only characters left that + // we could possibly allow, and Parse will reject them if we + // escape them (because hosts can't use %-encoding for + // ASCII bytes). + switch c { + case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '[', ']', '<', '>', '"': + return false + } + } + + switch c { + case '-', '_', '.', '~': // §2.3 Unreserved characters (mark) + return false + + case '$', '&', '+', ',', '/', ':', ';', '=', '?', '@': // §2.2 Reserved characters (reserved) + // Different sections of the URL allow a few of + // the reserved characters to appear unescaped. + switch mode { + case encodePath: // §3.3 + // The RFC allows : @ & = + $ but saves / ; , for assigning + // meaning to individual path segments. This package + // only manipulates the path as a whole, so we allow those + // last three as well. That leaves only ? to escape. + return c == '?' + + case encodePathSegment: // §3.3 + // The RFC allows : @ & = + $ but saves / ; , for assigning + // meaning to individual path segments. + return c == '/' || c == ';' || c == ',' || c == '?' + + case encodeUserPassword: // §3.2.1 + // The RFC allows ';', ':', '&', '=', '+', '$', and ',' in + // userinfo, so we must escape only '@', '/', and '?'. + // The parsing of userinfo treats ':' as special so we must escape + // that too. + return c == '@' || c == '/' || c == '?' || c == ':' + + case encodeQueryComponent: // §3.4 + // The RFC reserves (so we must escape) everything. + return true + + case encodeFragment: // §4.1 + // The RFC text is silent but the grammar allows + // everything, so escape nothing. + return false + } + } + + if mode == encodeFragment { + // RFC 3986 §2.2 allows not escaping sub-delims. A subset of sub-delims are + // included in reserved from RFC 2396 §2.2. The remaining sub-delims do not + // need to be escaped. To minimize potential breakage, we apply two restrictions: + // (1) we always escape sub-delims outside of the fragment, and (2) we always + // escape single quote to avoid breaking callers that had previously assumed that + // single quotes would be escaped. See issue #19917. + switch c { + case '!', '(', ')', '*': + return false + } + } + + // Everything else must be escaped. + return true +} + +// QueryUnescape does the inverse transformation of QueryEscape, +// converting each 3-byte encoded substring of the form "%AB" into the +// hex-decoded byte 0xAB. +// It returns an error if any % is not followed by two hexadecimal +// digits. +func QueryUnescape(s string) (string, error) { + return unescape(s, encodeQueryComponent) +} + +// PathUnescape does the inverse transformation of PathEscape, +// converting each 3-byte encoded substring of the form "%AB" into the +// hex-decoded byte 0xAB. It returns an error if any % is not followed +// by two hexadecimal digits. +// +// PathUnescape is identical to QueryUnescape except that it does not +// unescape '+' to ' ' (space). +func PathUnescape(s string) (string, error) { + return unescape(s, encodePathSegment) +} + +// unescape unescapes a string; the mode specifies +// which section of the URL string is being unescaped. +func unescape(s string, mode encoding) (string, error) { + // Count %, check that they're well-formed. + n := 0 + hasPlus := false + for i := 0; i < len(s); { + switch s[i] { + case '%': + n++ + if i+2 >= len(s) || !ishex(s[i+1]) || !ishex(s[i+2]) { + s = s[i:] + if len(s) > 3 { + s = s[:3] + } + return "", EscapeError(s) + } + // Per https://tools.ietf.org/html/rfc3986#page-21 + // in the host component %-encoding can only be used + // for non-ASCII bytes. + // But https://tools.ietf.org/html/rfc6874#section-2 + // introduces %25 being allowed to escape a percent sign + // in IPv6 scoped-address literals. Yay. + if mode == encodeHost && unhex(s[i+1]) < 8 && s[i:i+3] != "%25" { + return "", EscapeError(s[i : i+3]) + } + if mode == encodeZone { + // RFC 6874 says basically "anything goes" for zone identifiers + // and that even non-ASCII can be redundantly escaped, + // but it seems prudent to restrict %-escaped bytes here to those + // that are valid host name bytes in their unescaped form. + // That is, you can use escaping in the zone identifier but not + // to introduce bytes you couldn't just write directly. + // But Windows puts spaces here! Yay. + v := unhex(s[i+1])<<4 | unhex(s[i+2]) + if s[i:i+3] != "%25" && v != ' ' && shouldEscape(v, encodeHost) { + return "", EscapeError(s[i : i+3]) + } + } + i += 3 + case '+': + hasPlus = mode == encodeQueryComponent + i++ + default: + if (mode == encodeHost || mode == encodeZone) && s[i] < 0x80 && shouldEscape(s[i], mode) { + return "", InvalidHostError(s + ": symbol " + s[i:i+1]) + } + i++ + } + } + + if n == 0 && !hasPlus { + return s, nil + } + + var t strings.Builder + t.Grow(len(s) - 2*n) + for i := 0; i < len(s); i++ { + switch s[i] { + case '%': + t.WriteByte(unhex(s[i+1])<<4 | unhex(s[i+2])) + i += 2 + case '+': + if mode == encodeQueryComponent { + t.WriteByte(' ') + } else { + t.WriteByte('+') + } + default: + t.WriteByte(s[i]) + } + } + return t.String(), nil +} + +// QueryEscape escapes the string so it can be safely placed +// inside a URL query. +func QueryEscape(s string) string { + return escape(s, encodeQueryComponent) +} + +// PathEscape escapes the string so it can be safely placed inside a URL path segment, +// replacing special characters (including /) with %XX sequences as needed. +func PathEscape(s string) string { + return escape(s, encodePathSegment) +} + +func escape(s string, mode encoding) string { + spaceCount, hexCount := 0, 0 + for i := 0; i < len(s); i++ { + c := s[i] + if shouldEscape(c, mode) { + if c == ' ' && mode == encodeQueryComponent { + spaceCount++ + } else { + hexCount++ + } + } + } + + if spaceCount == 0 && hexCount == 0 { + return s + } + + var buf [64]byte + var t []byte + + required := len(s) + 2*hexCount + if required <= len(buf) { + t = buf[:required] + } else { + t = make([]byte, required) + } + + if hexCount == 0 { + copy(t, s) + for i := 0; i < len(s); i++ { + if s[i] == ' ' { + t[i] = '+' + } + } + return string(t) + } + + j := 0 + for i := 0; i < len(s); i++ { + switch c := s[i]; { + case c == ' ' && mode == encodeQueryComponent: + t[j] = '+' + j++ + case shouldEscape(c, mode): + t[j] = '%' + t[j+1] = upperhex[c>>4] + t[j+2] = upperhex[c&15] + j += 3 + default: + t[j] = s[i] + j++ + } + } + return string(t) +} + +// A URL represents a parsed URL (technically, a URI reference). +// +// The general form represented is: +// +// [scheme:][//[userinfo@]host][/]path[?query][#fragment] +// +// URLs that do not start with a slash after the scheme are interpreted as: +// +// scheme:opaque[?query][#fragment] +// +// Note that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/. +// A consequence is that it is impossible to tell which slashes in the Path were +// slashes in the raw URL and which were %2f. This distinction is rarely important, +// but when it is, the code should use the EscapedPath method, which preserves +// the original encoding of Path. +// +// The RawPath field is an optional field which is only set when the default +// encoding of Path is different from the escaped path. See the EscapedPath method +// for more details. +// +// URL's String method uses the EscapedPath method to obtain the path. +type URL struct { + Scheme string + Opaque string // encoded opaque data + User *Userinfo // username and password information + Host string // host or host:port + Path string // path (relative paths may omit leading slash) + RawPath string // encoded path hint (see EscapedPath method) + OmitHost bool // do not emit empty host (authority) + ForceQuery bool // append a query ('?') even if RawQuery is empty + RawQuery string // encoded query values, without '?' + Fragment string // fragment for references, without '#' + RawFragment string // encoded fragment hint (see EscapedFragment method) +} + +// User returns a Userinfo containing the provided username +// and no password set. +func User(username string) *Userinfo { + return &Userinfo{username, "", false} +} + +// UserPassword returns a Userinfo containing the provided username +// and password. +// +// This functionality should only be used with legacy web sites. +// RFC 2396 warns that interpreting Userinfo this way +// “is NOT RECOMMENDED, because the passing of authentication +// information in clear text (such as URI) has proven to be a +// security risk in almost every case where it has been used.” +func UserPassword(username, password string) *Userinfo { + return &Userinfo{username, password, true} +} + +// The Userinfo type is an immutable encapsulation of username and +// password details for a URL. An existing Userinfo value is guaranteed +// to have a username set (potentially empty, as allowed by RFC 2396), +// and optionally a password. +type Userinfo struct { + username string + password string + passwordSet bool +} + +// Username returns the username. +func (u *Userinfo) Username() string { + if u == nil { + return "" + } + return u.username +} + +// Password returns the password in case it is set, and whether it is set. +func (u *Userinfo) Password() (string, bool) { + if u == nil { + return "", false + } + return u.password, u.passwordSet +} + +// String returns the encoded userinfo information in the standard form +// of "username[:password]". +func (u *Userinfo) String() string { + if u == nil { + return "" + } + s := escape(u.username, encodeUserPassword) + if u.passwordSet { + s += ":" + escape(u.password, encodeUserPassword) + } + return s +} + +// Maybe rawURL is of the form scheme:path. +// (Scheme must be [a-zA-Z][a-zA-Z0-9+.-]*) +// If so, return scheme, path; else return "", rawURL. +func getScheme(rawURL string) (scheme, path string, err error) { + for i := 0; i < len(rawURL); i++ { + c := rawURL[i] + switch { + case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z': + // do nothing + case '0' <= c && c <= '9' || c == '+' || c == '-' || c == '.': + if i == 0 { + return "", rawURL, nil + } + case c == ':': + if i == 0 { + return "", "", errors.New("missing protocol scheme") + } + return rawURL[:i], rawURL[i+1:], nil + default: + // we have encountered an invalid character, + // so there is no valid scheme + return "", rawURL, nil + } + } + return "", rawURL, nil +} + +// Parse parses a raw url into a URL structure. +// +// The url may be relative (a path, without a host) or absolute +// (starting with a scheme). Trying to parse a hostname and path +// without a scheme is invalid but may not necessarily return an +// error, due to parsing ambiguities. +func Parse(rawURL string) (*URL, error) { + // Cut off #frag + u, frag, _ := strings.Cut(rawURL, "#") + url, err := parse(u, false) + if err != nil { + return nil, &Error{"parse", u, err} + } + if frag == "" { + return url, nil + } + if err = url.setFragment(frag); err != nil { + return nil, &Error{"parse", rawURL, err} + } + return url, nil +} + +// ParseRequestURI parses a raw url into a URL structure. It assumes that +// url was received in an HTTP request, so the url is interpreted +// only as an absolute URI or an absolute path. +// The string url is assumed not to have a #fragment suffix. +// (Web browsers strip #fragment before sending the URL to a web server.) +func ParseRequestURI(rawURL string) (*URL, error) { + url, err := parse(rawURL, true) + if err != nil { + return nil, &Error{"parse", rawURL, err} + } + return url, nil +} + +// parse parses a URL from a string in one of two contexts. If +// viaRequest is true, the URL is assumed to have arrived via an HTTP request, +// in which case only absolute URLs or path-absolute relative URLs are allowed. +// If viaRequest is false, all forms of relative URLs are allowed. +func parse(rawURL string, viaRequest bool) (*URL, error) { + var rest string + var err error + + if stringContainsCTLByte(rawURL) { + return nil, errors.New("net/url: invalid control character in URL") + } + + if rawURL == "" && viaRequest { + return nil, errors.New("empty url") + } + url := new(URL) + + if rawURL == "*" { + url.Path = "*" + return url, nil + } + + // Split off possible leading "http:", "mailto:", etc. + // Cannot contain escaped characters. + if url.Scheme, rest, err = getScheme(rawURL); err != nil { + return nil, err + } + url.Scheme = strings.ToLower(url.Scheme) + + if strings.HasSuffix(rest, "?") && strings.Count(rest, "?") == 1 { + url.ForceQuery = true + rest = rest[:len(rest)-1] + } else { + rest, url.RawQuery, _ = strings.Cut(rest, "?") + } + + if !strings.HasPrefix(rest, "/") { + if url.Scheme != "" { + // We consider rootless paths per RFC 3986 as opaque. + url.Opaque = rest + return url, nil + } + if viaRequest { + return nil, errors.New("invalid URI for request") + } + + // Avoid confusion with malformed schemes, like cache_object:foo/bar. + // See golang.org/issue/16822. + // + // RFC 3986, §3.3: + // In addition, a URI reference (Section 4.1) may be a relative-path reference, + // in which case the first path segment cannot contain a colon (":") character. + if segment, _, _ := strings.Cut(rest, "/"); strings.Contains(segment, ":") { + // First path segment has colon. Not allowed in relative URL. + return nil, errors.New("first path segment in URL cannot contain colon") + } + } + + if (url.Scheme != "" || !viaRequest && !strings.HasPrefix(rest, "///")) && strings.HasPrefix(rest, "//") { + var authority string + authority, rest = rest[2:], "" + if i := strings.Index(authority, "/"); i >= 0 { + authority, rest = authority[:i], authority[i:] + } + url.User, url.Host, err = parseAuthority(authority) + if err != nil { + return nil, err + } + } else if url.Scheme != "" && strings.HasPrefix(rest, "/") { + // OmitHost is set to true when rawURL has an empty host (authority). + // See golang.org/issue/46059. + url.OmitHost = true + } + + // Set Path and, optionally, RawPath. + // RawPath is a hint of the encoding of Path. We don't want to set it if + // the default escaping of Path is equivalent, to help make sure that people + // don't rely on it in general. + if err := url.setPath(rest); err != nil { + return nil, err + } + return url, nil +} + +func parseAuthority(authority string) (user *Userinfo, host string, err error) { + i := strings.LastIndex(authority, "@") + if i < 0 { + host, err = parseHost(authority) + } else { + host, err = parseHost(authority[i+1:]) + } + if err != nil { + return nil, "", err + } + if i < 0 { + return nil, host, nil + } + userinfo := authority[:i] + if !validUserinfo(userinfo) { + return nil, "", errors.New("net/url: invalid userinfo") + } + if !strings.Contains(userinfo, ":") { + if userinfo, err = unescape(userinfo, encodeUserPassword); err != nil { + return nil, "", err + } + user = User(userinfo) + } else { + username, password, _ := strings.Cut(userinfo, ":") + if username, err = unescape(username, encodeUserPassword); err != nil { + return nil, "", err + } + if password, err = unescape(password, encodeUserPassword); err != nil { + return nil, "", err + } + user = UserPassword(username, password) + } + return user, host, nil +} + +// parseHost parses host as an authority without user +// information. That is, as host[:port]. +func parseHost(host string) (string, error) { + if strings.HasPrefix(host, "[") { + // Parse an IP-Literal in RFC 3986 and RFC 6874. + // E.g., "[fe80::1]", "[fe80::1%25en0]", "[fe80::1]:80". + i := strings.LastIndex(host, "]") + if i < 0 { + return "", errors.New("missing ']' in host") + } + colonPort := host[i+1:] + if !validOptionalPort(colonPort) { + return "", fmt.Errorf("invalid port %q after host", colonPort) + } + + // RFC 6874 defines that %25 (%-encoded percent) introduces + // the zone identifier, and the zone identifier can use basically + // any %-encoding it likes. That's different from the host, which + // can only %-encode non-ASCII bytes. + // We do impose some restrictions on the zone, to avoid stupidity + // like newlines. + zone := strings.Index(host[:i], "%25") + if zone >= 0 { + host1, err := unescape(host[:zone], encodeHost) + if err != nil { + return "", err + } + host2, err := unescape(host[zone:i], encodeZone) + if err != nil { + return "", err + } + host3, err := unescape(host[i:], encodeHost) + if err != nil { + return "", err + } + return host1 + host2 + host3, nil + } + } else if i := strings.LastIndex(host, ":"); i != -1 { + colonPort := host[i:] + if !validOptionalPort(colonPort) { + return "", fmt.Errorf("invalid port %q after host", colonPort) + } + } + + var err error + if host, err = unescape(host, encodeHost); err != nil { + return "", err + } + return host, nil +} + +// setPath sets the Path and RawPath fields of the URL based on the provided +// escaped path p. It maintains the invariant that RawPath is only specified +// when it differs from the default encoding of the path. +// For example: +// - setPath("/foo/bar") will set Path="/foo/bar" and RawPath="" +// - setPath("/foo%2fbar") will set Path="/foo/bar" and RawPath="/foo%2fbar" +// setPath will return an error only if the provided path contains an invalid +// escaping. +func (u *URL) setPath(p string) error { + path, err := unescape(p, encodePath) + if err != nil { + return err + } + u.Path = path + if escp := escape(path, encodePath); p == escp { + // Default encoding is fine. + u.RawPath = "" + } else { + u.RawPath = p + } + return nil +} + +// EscapedPath returns the escaped form of u.Path. +// In general there are multiple possible escaped forms of any path. +// EscapedPath returns u.RawPath when it is a valid escaping of u.Path. +// Otherwise EscapedPath ignores u.RawPath and computes an escaped +// form on its own. +// The String and RequestURI methods use EscapedPath to construct +// their results. +// In general, code should call EscapedPath instead of +// reading u.RawPath directly. +func (u *URL) EscapedPath() string { + if u.RawPath != "" && validEncoded(u.RawPath, encodePath) { + p, err := unescape(u.RawPath, encodePath) + if err == nil && p == u.Path { + return u.RawPath + } + } + if u.Path == "*" { + return "*" // don't escape (Issue 11202) + } + return escape(u.Path, encodePath) +} + +// validEncoded reports whether s is a valid encoded path or fragment, +// according to mode. +// It must not contain any bytes that require escaping during encoding. +func validEncoded(s string, mode encoding) bool { + for i := 0; i < len(s); i++ { + // RFC 3986, Appendix A. + // pchar = unreserved / pct-encoded / sub-delims / ":" / "@". + // shouldEscape is not quite compliant with the RFC, + // so we check the sub-delims ourselves and let + // shouldEscape handle the others. + switch s[i] { + case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '@': + // ok + case '[', ']': + // ok - not specified in RFC 3986 but left alone by modern browsers + case '%': + // ok - percent encoded, will decode + default: + if shouldEscape(s[i], mode) { + return false + } + } + } + return true +} + +// setFragment is like setPath but for Fragment/RawFragment. +func (u *URL) setFragment(f string) error { + frag, err := unescape(f, encodeFragment) + if err != nil { + return err + } + u.Fragment = frag + if escf := escape(frag, encodeFragment); f == escf { + // Default encoding is fine. + u.RawFragment = "" + } else { + u.RawFragment = f + } + return nil +} + +// EscapedFragment returns the escaped form of u.Fragment. +// In general there are multiple possible escaped forms of any fragment. +// EscapedFragment returns u.RawFragment when it is a valid escaping of u.Fragment. +// Otherwise EscapedFragment ignores u.RawFragment and computes an escaped +// form on its own. +// The String method uses EscapedFragment to construct its result. +// In general, code should call EscapedFragment instead of +// reading u.RawFragment directly. +func (u *URL) EscapedFragment() string { + if u.RawFragment != "" && validEncoded(u.RawFragment, encodeFragment) { + f, err := unescape(u.RawFragment, encodeFragment) + if err == nil && f == u.Fragment { + return u.RawFragment + } + } + return escape(u.Fragment, encodeFragment) +} + +// validOptionalPort reports whether port is either an empty string +// or matches /^:\d*$/ +func validOptionalPort(port string) bool { + if port == "" { + return true + } + if port[0] != ':' { + return false + } + for _, b := range port[1:] { + if b < '0' || b > '9' { + return false + } + } + return true +} + +// String reassembles the URL into a valid URL string. +// The general form of the result is one of: +// +// scheme:opaque?query#fragment +// scheme://userinfo@host/path?query#fragment +// +// If u.Opaque is non-empty, String uses the first form; +// otherwise it uses the second form. +// Any non-ASCII characters in host are escaped. +// To obtain the path, String uses u.EscapedPath(). +// +// In the second form, the following rules apply: +// - if u.Scheme is empty, scheme: is omitted. +// - if u.User is nil, userinfo@ is omitted. +// - if u.Host is empty, host/ is omitted. +// - if u.Scheme and u.Host are empty and u.User is nil, +// the entire scheme://userinfo@host/ is omitted. +// - if u.Host is non-empty and u.Path begins with a /, +// the form host/path does not add its own /. +// - if u.RawQuery is empty, ?query is omitted. +// - if u.Fragment is empty, #fragment is omitted. +func (u *URL) String() string { + var buf strings.Builder + if u.Scheme != "" { + buf.WriteString(u.Scheme) + buf.WriteByte(':') + } + if u.Opaque != "" { + buf.WriteString(u.Opaque) + } else { + if u.Scheme != "" || u.Host != "" || u.User != nil { + if u.OmitHost && u.Host == "" && u.User == nil { + // omit empty host + } else { + if u.Host != "" || u.Path != "" || u.User != nil { + buf.WriteString("//") + } + if ui := u.User; ui != nil { + buf.WriteString(ui.String()) + buf.WriteByte('@') + } + if h := u.Host; h != "" { + buf.WriteString(escape(h, encodeHost)) + } + } + } + path := u.EscapedPath() + if path != "" && path[0] != '/' && u.Host != "" { + buf.WriteByte('/') + } + if buf.Len() == 0 { + // RFC 3986 §4.2 + // A path segment that contains a colon character (e.g., "this:that") + // cannot be used as the first segment of a relative-path reference, as + // it would be mistaken for a scheme name. Such a segment must be + // preceded by a dot-segment (e.g., "./this:that") to make a relative- + // path reference. + if segment, _, _ := strings.Cut(path, "/"); strings.Contains(segment, ":") { + buf.WriteString("./") + } + } + buf.WriteString(path) + } + if u.ForceQuery || u.RawQuery != "" { + buf.WriteByte('?') + buf.WriteString(u.RawQuery) + } + if u.Fragment != "" { + buf.WriteByte('#') + buf.WriteString(u.EscapedFragment()) + } + return buf.String() +} + +// Redacted is like String but replaces any password with "xxxxx". +// Only the password in u.URL is redacted. +func (u *URL) Redacted() string { + if u == nil { + return "" + } + + ru := *u + if _, has := ru.User.Password(); has { + ru.User = UserPassword(ru.User.Username(), "xxxxx") + } + return ru.String() +} + +// Values maps a string key to a list of values. +// It is typically used for query parameters and form values. +// Unlike in the http.Header map, the keys in a Values map +// are case-sensitive. +type Values map[string][]string + +// Get gets the first value associated with the given key. +// If there are no values associated with the key, Get returns +// the empty string. To access multiple values, use the map +// directly. +func (v Values) Get(key string) string { + if v == nil { + return "" + } + vs := v[key] + if len(vs) == 0 { + return "" + } + return vs[0] +} + +// Set sets the key to value. It replaces any existing +// values. +func (v Values) Set(key, value string) { + v[key] = []string{value} +} + +// Add adds the value to key. It appends to any existing +// values associated with key. +func (v Values) Add(key, value string) { + v[key] = append(v[key], value) +} + +// Del deletes the values associated with key. +func (v Values) Del(key string) { + delete(v, key) +} + +// Has checks whether a given key is set. +func (v Values) Has(key string) bool { + _, ok := v[key] + return ok +} + +// ParseQuery parses the URL-encoded query string and returns +// a map listing the values specified for each key. +// ParseQuery always returns a non-nil map containing all the +// valid query parameters found; err describes the first decoding error +// encountered, if any. +// +// Query is expected to be a list of key=value settings separated by ampersands. +// A setting without an equals sign is interpreted as a key set to an empty +// value. +// Settings containing a non-URL-encoded semicolon are considered invalid. +func ParseQuery(query string) (Values, error) { + m := make(Values) + err := parseQuery(m, query) + return m, err +} + +func parseQuery(m Values, query string) (err error) { + for query != "" { + var key string + key, query, _ = strings.Cut(query, "&") + if strings.Contains(key, ";") { + err = fmt.Errorf("invalid semicolon separator in query") + continue + } + if key == "" { + continue + } + key, value, _ := strings.Cut(key, "=") + key, err1 := QueryUnescape(key) + if err1 != nil { + if err == nil { + err = err1 + } + continue + } + value, err1 = QueryUnescape(value) + if err1 != nil { + if err == nil { + err = err1 + } + continue + } + m[key] = append(m[key], value) + } + return err +} + +// Encode encodes the values into “URL encoded” form +// ("bar=baz&foo=quux") sorted by key. +func (v Values) Encode() string { + if v == nil { + return "" + } + var buf strings.Builder + keys := make([]string, 0, len(v)) + for k := range v { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + vs := v[k] + keyEscaped := QueryEscape(k) + for _, v := range vs { + if buf.Len() > 0 { + buf.WriteByte('&') + } + buf.WriteString(keyEscaped) + buf.WriteByte('=') + buf.WriteString(QueryEscape(v)) + } + } + return buf.String() +} + +// resolvePath applies special path segments from refs and applies +// them to base, per RFC 3986. +func resolvePath(base, ref string) string { + var full string + if ref == "" { + full = base + } else if ref[0] != '/' { + i := strings.LastIndex(base, "/") + full = base[:i+1] + ref + } else { + full = ref + } + if full == "" { + return "" + } + + var ( + elem string + dst strings.Builder + ) + first := true + remaining := full + // We want to return a leading '/', so write it now. + dst.WriteByte('/') + found := true + for found { + elem, remaining, found = strings.Cut(remaining, "/") + if elem == "." { + first = false + // drop + continue + } + + if elem == ".." { + // Ignore the leading '/' we already wrote. + str := dst.String()[1:] + index := strings.LastIndexByte(str, '/') + + dst.Reset() + dst.WriteByte('/') + if index == -1 { + first = true + } else { + dst.WriteString(str[:index]) + } + } else { + if !first { + dst.WriteByte('/') + } + dst.WriteString(elem) + first = false + } + } + + if elem == "." || elem == ".." { + dst.WriteByte('/') + } + + // We wrote an initial '/', but we don't want two. + r := dst.String() + if len(r) > 1 && r[1] == '/' { + r = r[1:] + } + return r +} + +// IsAbs reports whether the URL is absolute. +// Absolute means that it has a non-empty scheme. +func (u *URL) IsAbs() bool { + return u.Scheme != "" +} + +// Parse parses a URL in the context of the receiver. The provided URL +// may be relative or absolute. Parse returns nil, err on parse +// failure, otherwise its return value is the same as ResolveReference. +func (u *URL) Parse(ref string) (*URL, error) { + refURL, err := Parse(ref) + if err != nil { + return nil, err + } + return u.ResolveReference(refURL), nil +} + +// ResolveReference resolves a URI reference to an absolute URI from +// an absolute base URI u, per RFC 3986 Section 5.2. The URI reference +// may be relative or absolute. ResolveReference always returns a new +// URL instance, even if the returned URL is identical to either the +// base or reference. If ref is an absolute URL, then ResolveReference +// ignores base and returns a copy of ref. +func (u *URL) ResolveReference(ref *URL) *URL { + url := *ref + if ref.Scheme == "" { + url.Scheme = u.Scheme + } + if ref.Scheme != "" || ref.Host != "" || ref.User != nil { + // The "absoluteURI" or "net_path" cases. + // We can ignore the error from setPath since we know we provided a + // validly-escaped path. + url.setPath(resolvePath(ref.EscapedPath(), "")) + return &url + } + if ref.Opaque != "" { + url.User = nil + url.Host = "" + url.Path = "" + return &url + } + if ref.Path == "" && !ref.ForceQuery && ref.RawQuery == "" { + url.RawQuery = u.RawQuery + if ref.Fragment == "" { + url.Fragment = u.Fragment + url.RawFragment = u.RawFragment + } + } + // The "abs_path" or "rel_path" cases. + url.Host = u.Host + url.User = u.User + url.setPath(resolvePath(u.EscapedPath(), ref.EscapedPath())) + return &url +} + +// Query parses RawQuery and returns the corresponding values. +// It silently discards malformed value pairs. +// To check errors use ParseQuery. +func (u *URL) Query() Values { + v, _ := ParseQuery(u.RawQuery) + return v +} + +// RequestURI returns the encoded path?query or opaque?query +// string that would be used in an HTTP request for u. +func (u *URL) RequestURI() string { + result := u.Opaque + if result == "" { + result = u.EscapedPath() + if result == "" { + result = "/" + } + } else { + if strings.HasPrefix(result, "//") { + result = u.Scheme + ":" + result + } + } + if u.ForceQuery || u.RawQuery != "" { + result += "?" + u.RawQuery + } + return result +} + +// Hostname returns u.Host, stripping any valid port number if present. +// +// If the result is enclosed in square brackets, as literal IPv6 addresses are, +// the square brackets are removed from the result. +func (u *URL) Hostname() string { + host, _ := splitHostPort(u.Host) + return host +} + +// Port returns the port part of u.Host, without the leading colon. +// +// If u.Host doesn't contain a valid numeric port, Port returns an empty string. +func (u *URL) Port() string { + _, port := splitHostPort(u.Host) + return port +} + +// splitHostPort separates host and port. If the port is not valid, it returns +// the entire input as host, and it doesn't check the validity of the host. +// Unlike net.SplitHostPort, but per RFC 3986, it requires ports to be numeric. +func splitHostPort(hostPort string) (host, port string) { + host = hostPort + + colon := strings.LastIndexByte(host, ':') + if colon != -1 && validOptionalPort(host[colon:]) { + host, port = host[:colon], host[colon+1:] + } + + if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") { + host = host[1 : len(host)-1] + } + + return +} + +// Marshaling interface implementations. +// Would like to implement MarshalText/UnmarshalText but that will change the JSON representation of URLs. + +func (u *URL) MarshalBinary() (text []byte, err error) { + return []byte(u.String()), nil +} + +func (u *URL) UnmarshalBinary(text []byte) error { + u1, err := Parse(string(text)) + if err != nil { + return err + } + *u = *u1 + return nil +} + +// JoinPath returns a new URL with the provided path elements joined to +// any existing path and the resulting path cleaned of any ./ or ../ elements. +// Any sequences of multiple / characters will be reduced to a single /. +func (u *URL) JoinPath(elem ...string) *URL { + elem = append([]string{u.EscapedPath()}, elem...) + var p string + if !strings.HasPrefix(elem[0], "/") { + // Return a relative path if u is relative, + // but ensure that it contains no ../ elements. + elem[0] = "/" + elem[0] + p = path.Join(elem...)[1:] + } else { + p = path.Join(elem...) + } + // path.Join will remove any trailing slashes. + // Preserve at least one. + if strings.HasSuffix(elem[len(elem)-1], "/") && !strings.HasSuffix(p, "/") { + p += "/" + } + url := *u + url.setPath(p) + return &url +} + +// validUserinfo reports whether s is a valid userinfo string per RFC 3986 +// Section 3.2.1: +// +// userinfo = *( unreserved / pct-encoded / sub-delims / ":" ) +// unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" +// sub-delims = "!" / "$" / "&" / "'" / "(" / ")" +// / "*" / "+" / "," / ";" / "=" +// +// It doesn't validate pct-encoded. The caller does that via func unescape. +func validUserinfo(s string) bool { + for _, r := range s { + if 'A' <= r && r <= 'Z' { + continue + } + if 'a' <= r && r <= 'z' { + continue + } + if '0' <= r && r <= '9' { + continue + } + switch r { + case '-', '.', '_', ':', '~', '!', '$', '&', '\'', + '(', ')', '*', '+', ',', ';', '=', '%', '@': + continue + default: + return false + } + } + return true +} + +// stringContainsCTLByte reports whether s contains any ASCII control character. +func stringContainsCTLByte(s string) bool { + for i := 0; i < len(s); i++ { + b := s[i] + if b < ' ' || b == 0x7f { + return true + } + } + return false +} + +// JoinPath returns a URL string with the provided path elements joined to +// the existing path of base and the resulting path cleaned of any ./ or ../ elements. +func JoinPath(base string, elem ...string) (result string, err error) { + url, err := Parse(base) + if err != nil { + return + } + result = url.JoinPath(elem...).String() + return +} diff --git a/sdks/client.go b/sdks/client.go index d5c4df2ff..84af8b9c0 100644 --- a/sdks/client.go +++ b/sdks/client.go @@ -2,12 +2,12 @@ package sdks import ( "net/http" - "net/url" "github.com/0chain/errors" "github.com/0chain/gosdk/constants" "github.com/0chain/gosdk/core/encryption" "github.com/0chain/gosdk/core/sys" + "github.com/0chain/gosdk/core/util" "github.com/0chain/gosdk/zboxcore/client" ) @@ -20,7 +20,7 @@ type Client struct { // create client instance func NewClient(clientID, clientPublicKey, baseURL string) (Client, error) { - u, err := url.Parse(baseURL) + u, err := util.Parse(baseURL) c := Client{ ClientID: clientID, diff --git a/zcnbridge/http/rest.go b/zcnbridge/http/rest.go index 87bfee4f9..b88b4ce68 100644 --- a/zcnbridge/http/rest.go +++ b/zcnbridge/http/rest.go @@ -7,7 +7,6 @@ import ( "io" "io/ioutil" "net/http" - "net/url" "sync" "go.uber.org/zap" @@ -173,9 +172,9 @@ func extractSharders() []string { } // makeURL creates url.URL to make smart contract request to sharder. -func makeURL(params Params, baseURL, relativePath string) *url.URL { +func makeURL(params Params, baseURL, relativePath string) *util.URL { uString := fmt.Sprintf("%v/%v%v", baseURL, RestPrefix, relativePath) - u, _ := url.Parse(uString) + u, _ := util.Parse(uString) q := u.Query() for k, v := range params { q.Add(k, v) From 050270f52815dcd930f760f20a4c7e3e669d73fb Mon Sep 17 00:00:00 2001 From: dabasov Date: Thu, 16 Nov 2023 00:01:00 +0200 Subject: [PATCH 100/134] experiment --- zboxcore/zboxutil/http.go | 7 +- zboxcore/zboxutil/url.go | 1269 ------------------------------------- 2 files changed, 4 insertions(+), 1272 deletions(-) delete mode 100644 zboxcore/zboxutil/url.go diff --git a/zboxcore/zboxutil/http.go b/zboxcore/zboxutil/http.go index 5c641707f..4bdeb8bef 100644 --- a/zboxcore/zboxutil/http.go +++ b/zboxcore/zboxutil/http.go @@ -20,6 +20,7 @@ import ( "github.com/0chain/gosdk/core/conf" "github.com/0chain/gosdk/core/encryption" "github.com/0chain/gosdk/core/logger" + "github.com/0chain/gosdk/core/util" "github.com/0chain/gosdk/zboxcore/blockchain" "github.com/0chain/gosdk/zboxcore/client" ) @@ -824,7 +825,7 @@ func MakeSCRestAPICall(scAddress string, relativePath string, params map[string] lock.Lock() urlString := fmt.Sprintf("%v/%v%v%v", sharder, SC_REST_API_URL, scAddress, relativePath) - urlObj, err := Parse(urlString) + urlObj, err := util.Parse(urlString) if err != nil { log.Error(err) continue @@ -954,11 +955,11 @@ func isCurrentDominantStatus(respStatus int, currentTotalPerStatus map[int]int, return currentTotalPerStatus[respStatus] == currentMax && (respStatus == 200 || currentTotalPerStatus[200] < currentMax) } -func joinUrl(baseURl string, paths ...string) (*URL, error) { +func joinUrl(baseURl string, paths ...string) (*util.URL, error) { lock.Lock() defer lock.Unlock() - u, err := Parse(baseURl) + u, err := util.Parse(baseURl) if err != nil { log.Error(err) return nil, err diff --git a/zboxcore/zboxutil/url.go b/zboxcore/zboxutil/url.go deleted file mode 100644 index 7d0bf5dcb..000000000 --- a/zboxcore/zboxutil/url.go +++ /dev/null @@ -1,1269 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package url parses URLs and implements query escaping. -package zboxutil - -// See RFC 3986. This package generally follows RFC 3986, except where -// it deviates for compatibility reasons. When sending changes, first -// search old issues for history on decisions. Unit tests should also -// contain references to issue numbers with details. - -import ( - "errors" - "fmt" - "path" - "sort" - "strconv" - "strings" -) - -// Error reports an error and the operation and URL that caused it. -type Error struct { - Op string - URL string - Err error -} - -func (e *Error) Unwrap() error { return e.Err } -func (e *Error) Error() string { return fmt.Sprintf("%s %q: %s", e.Op, e.URL, e.Err) } - -func (e *Error) Timeout() bool { - t, ok := e.Err.(interface { - Timeout() bool - }) - return ok && t.Timeout() -} - -func (e *Error) Temporary() bool { - t, ok := e.Err.(interface { - Temporary() bool - }) - return ok && t.Temporary() -} - -const upperhex = "0123456789ABCDEF" - -func ishex(c byte) bool { - switch { - case '0' <= c && c <= '9': - return true - case 'a' <= c && c <= 'f': - return true - case 'A' <= c && c <= 'F': - return true - } - return false -} - -func unhex(c byte) byte { - switch { - case '0' <= c && c <= '9': - return c - '0' - case 'a' <= c && c <= 'f': - return c - 'a' + 10 - case 'A' <= c && c <= 'F': - return c - 'A' + 10 - } - return 0 -} - -type encoding int - -const ( - encodePath encoding = 1 + iota - encodePathSegment - encodeHost - encodeZone - encodeUserPassword - encodeQueryComponent - encodeFragment -) - -type EscapeError string - -func (e EscapeError) Error() string { - return "invalid URL escape " + strconv.Quote(string(e)) -} - -type InvalidHostError string - -func (e InvalidHostError) Error() string { - return "invalid character " + strconv.Quote(string(e)) + " in host name" -} - -// Return true if the specified character should be escaped when -// appearing in a URL string, according to RFC 3986. -// -// Please be informed that for now shouldEscape does not check all -// reserved characters correctly. See golang.org/issue/5684. -func shouldEscape(c byte, mode encoding) bool { - // §2.3 Unreserved characters (alphanum) - if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' { - return false - } - - if mode == encodeHost || mode == encodeZone { - // §3.2.2 Host allows - // sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" - // as part of reg-name. - // We add : because we include :port as part of host. - // We add [ ] because we include [ipv6]:port as part of host. - // We add < > because they're the only characters left that - // we could possibly allow, and Parse will reject them if we - // escape them (because hosts can't use %-encoding for - // ASCII bytes). - switch c { - case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '[', ']', '<', '>', '"': - return false - } - } - - switch c { - case '-', '_', '.', '~': // §2.3 Unreserved characters (mark) - return false - - case '$', '&', '+', ',', '/', ':', ';', '=', '?', '@': // §2.2 Reserved characters (reserved) - // Different sections of the URL allow a few of - // the reserved characters to appear unescaped. - switch mode { - case encodePath: // §3.3 - // The RFC allows : @ & = + $ but saves / ; , for assigning - // meaning to individual path segments. This package - // only manipulates the path as a whole, so we allow those - // last three as well. That leaves only ? to escape. - return c == '?' - - case encodePathSegment: // §3.3 - // The RFC allows : @ & = + $ but saves / ; , for assigning - // meaning to individual path segments. - return c == '/' || c == ';' || c == ',' || c == '?' - - case encodeUserPassword: // §3.2.1 - // The RFC allows ';', ':', '&', '=', '+', '$', and ',' in - // userinfo, so we must escape only '@', '/', and '?'. - // The parsing of userinfo treats ':' as special so we must escape - // that too. - return c == '@' || c == '/' || c == '?' || c == ':' - - case encodeQueryComponent: // §3.4 - // The RFC reserves (so we must escape) everything. - return true - - case encodeFragment: // §4.1 - // The RFC text is silent but the grammar allows - // everything, so escape nothing. - return false - } - } - - if mode == encodeFragment { - // RFC 3986 §2.2 allows not escaping sub-delims. A subset of sub-delims are - // included in reserved from RFC 2396 §2.2. The remaining sub-delims do not - // need to be escaped. To minimize potential breakage, we apply two restrictions: - // (1) we always escape sub-delims outside of the fragment, and (2) we always - // escape single quote to avoid breaking callers that had previously assumed that - // single quotes would be escaped. See issue #19917. - switch c { - case '!', '(', ')', '*': - return false - } - } - - // Everything else must be escaped. - return true -} - -// QueryUnescape does the inverse transformation of QueryEscape, -// converting each 3-byte encoded substring of the form "%AB" into the -// hex-decoded byte 0xAB. -// It returns an error if any % is not followed by two hexadecimal -// digits. -func QueryUnescape(s string) (string, error) { - return unescape(s, encodeQueryComponent) -} - -// PathUnescape does the inverse transformation of PathEscape, -// converting each 3-byte encoded substring of the form "%AB" into the -// hex-decoded byte 0xAB. It returns an error if any % is not followed -// by two hexadecimal digits. -// -// PathUnescape is identical to QueryUnescape except that it does not -// unescape '+' to ' ' (space). -func PathUnescape(s string) (string, error) { - return unescape(s, encodePathSegment) -} - -// unescape unescapes a string; the mode specifies -// which section of the URL string is being unescaped. -func unescape(s string, mode encoding) (string, error) { - // Count %, check that they're well-formed. - n := 0 - hasPlus := false - for i := 0; i < len(s); { - switch s[i] { - case '%': - n++ - if i+2 >= len(s) || !ishex(s[i+1]) || !ishex(s[i+2]) { - s = s[i:] - if len(s) > 3 { - s = s[:3] - } - return "", EscapeError(s) - } - // Per https://tools.ietf.org/html/rfc3986#page-21 - // in the host component %-encoding can only be used - // for non-ASCII bytes. - // But https://tools.ietf.org/html/rfc6874#section-2 - // introduces %25 being allowed to escape a percent sign - // in IPv6 scoped-address literals. Yay. - if mode == encodeHost && unhex(s[i+1]) < 8 && s[i:i+3] != "%25" { - return "", EscapeError(s[i : i+3]) - } - if mode == encodeZone { - // RFC 6874 says basically "anything goes" for zone identifiers - // and that even non-ASCII can be redundantly escaped, - // but it seems prudent to restrict %-escaped bytes here to those - // that are valid host name bytes in their unescaped form. - // That is, you can use escaping in the zone identifier but not - // to introduce bytes you couldn't just write directly. - // But Windows puts spaces here! Yay. - v := unhex(s[i+1])<<4 | unhex(s[i+2]) - if s[i:i+3] != "%25" && v != ' ' && shouldEscape(v, encodeHost) { - return "", EscapeError(s[i : i+3]) - } - } - i += 3 - case '+': - hasPlus = mode == encodeQueryComponent - i++ - default: - if (mode == encodeHost || mode == encodeZone) && s[i] < 0x80 && shouldEscape(s[i], mode) { - log.Error(s) - return "", InvalidHostError(s) - } - i++ - } - } - - if n == 0 && !hasPlus { - return s, nil - } - - var t strings.Builder - t.Grow(len(s) - 2*n) - for i := 0; i < len(s); i++ { - switch s[i] { - case '%': - t.WriteByte(unhex(s[i+1])<<4 | unhex(s[i+2])) - i += 2 - case '+': - if mode == encodeQueryComponent { - t.WriteByte(' ') - } else { - t.WriteByte('+') - } - default: - t.WriteByte(s[i]) - } - } - return t.String(), nil -} - -// QueryEscape escapes the string so it can be safely placed -// inside a URL query. -func QueryEscape(s string) string { - return escape(s, encodeQueryComponent) -} - -// PathEscape escapes the string so it can be safely placed inside a URL path segment, -// replacing special characters (including /) with %XX sequences as needed. -func PathEscape(s string) string { - return escape(s, encodePathSegment) -} - -func escape(s string, mode encoding) string { - spaceCount, hexCount := 0, 0 - for i := 0; i < len(s); i++ { - c := s[i] - if shouldEscape(c, mode) { - if c == ' ' && mode == encodeQueryComponent { - spaceCount++ - } else { - hexCount++ - } - } - } - - if spaceCount == 0 && hexCount == 0 { - return s - } - - var buf [64]byte - var t []byte - - required := len(s) + 2*hexCount - if required <= len(buf) { - t = buf[:required] - } else { - t = make([]byte, required) - } - - if hexCount == 0 { - copy(t, s) - for i := 0; i < len(s); i++ { - if s[i] == ' ' { - t[i] = '+' - } - } - return string(t) - } - - j := 0 - for i := 0; i < len(s); i++ { - switch c := s[i]; { - case c == ' ' && mode == encodeQueryComponent: - t[j] = '+' - j++ - case shouldEscape(c, mode): - t[j] = '%' - t[j+1] = upperhex[c>>4] - t[j+2] = upperhex[c&15] - j += 3 - default: - t[j] = s[i] - j++ - } - } - return string(t) -} - -// A URL represents a parsed URL (technically, a URI reference). -// -// The general form represented is: -// -// [scheme:][//[userinfo@]host][/]path[?query][#fragment] -// -// URLs that do not start with a slash after the scheme are interpreted as: -// -// scheme:opaque[?query][#fragment] -// -// Note that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/. -// A consequence is that it is impossible to tell which slashes in the Path were -// slashes in the raw URL and which were %2f. This distinction is rarely important, -// but when it is, the code should use the EscapedPath method, which preserves -// the original encoding of Path. -// -// The RawPath field is an optional field which is only set when the default -// encoding of Path is different from the escaped path. See the EscapedPath method -// for more details. -// -// URL's String method uses the EscapedPath method to obtain the path. -type URL struct { - Scheme string - Opaque string // encoded opaque data - User *Userinfo // username and password information - Host string // host or host:port - Path string // path (relative paths may omit leading slash) - RawPath string // encoded path hint (see EscapedPath method) - OmitHost bool // do not emit empty host (authority) - ForceQuery bool // append a query ('?') even if RawQuery is empty - RawQuery string // encoded query values, without '?' - Fragment string // fragment for references, without '#' - RawFragment string // encoded fragment hint (see EscapedFragment method) -} - -// User returns a Userinfo containing the provided username -// and no password set. -func User(username string) *Userinfo { - return &Userinfo{username, "", false} -} - -// UserPassword returns a Userinfo containing the provided username -// and password. -// -// This functionality should only be used with legacy web sites. -// RFC 2396 warns that interpreting Userinfo this way -// “is NOT RECOMMENDED, because the passing of authentication -// information in clear text (such as URI) has proven to be a -// security risk in almost every case where it has been used.” -func UserPassword(username, password string) *Userinfo { - return &Userinfo{username, password, true} -} - -// The Userinfo type is an immutable encapsulation of username and -// password details for a URL. An existing Userinfo value is guaranteed -// to have a username set (potentially empty, as allowed by RFC 2396), -// and optionally a password. -type Userinfo struct { - username string - password string - passwordSet bool -} - -// Username returns the username. -func (u *Userinfo) Username() string { - if u == nil { - return "" - } - return u.username -} - -// Password returns the password in case it is set, and whether it is set. -func (u *Userinfo) Password() (string, bool) { - if u == nil { - return "", false - } - return u.password, u.passwordSet -} - -// String returns the encoded userinfo information in the standard form -// of "username[:password]". -func (u *Userinfo) String() string { - if u == nil { - return "" - } - s := escape(u.username, encodeUserPassword) - if u.passwordSet { - s += ":" + escape(u.password, encodeUserPassword) - } - return s -} - -// Maybe rawURL is of the form scheme:path. -// (Scheme must be [a-zA-Z][a-zA-Z0-9+.-]*) -// If so, return scheme, path; else return "", rawURL. -func getScheme(rawURL string) (scheme, path string, err error) { - for i := 0; i < len(rawURL); i++ { - c := rawURL[i] - switch { - case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z': - // do nothing - case '0' <= c && c <= '9' || c == '+' || c == '-' || c == '.': - if i == 0 { - return "", rawURL, nil - } - case c == ':': - if i == 0 { - return "", "", errors.New("missing protocol scheme") - } - return rawURL[:i], rawURL[i+1:], nil - default: - // we have encountered an invalid character, - // so there is no valid scheme - return "", rawURL, nil - } - } - return "", rawURL, nil -} - -// Parse parses a raw url into a URL structure. -// -// The url may be relative (a path, without a host) or absolute -// (starting with a scheme). Trying to parse a hostname and path -// without a scheme is invalid but may not necessarily return an -// error, due to parsing ambiguities. -func Parse(rawURL string) (*URL, error) { - // Cut off #frag - u, frag, _ := strings.Cut(rawURL, "#") - url, err := parse(u, false) - if err != nil { - return nil, &Error{"parse", u, err} - } - if frag == "" { - return url, nil - } - if err = url.setFragment(frag); err != nil { - return nil, &Error{"parse", rawURL, err} - } - return url, nil -} - -// ParseRequestURI parses a raw url into a URL structure. It assumes that -// url was received in an HTTP request, so the url is interpreted -// only as an absolute URI or an absolute path. -// The string url is assumed not to have a #fragment suffix. -// (Web browsers strip #fragment before sending the URL to a web server.) -func ParseRequestURI(rawURL string) (*URL, error) { - url, err := parse(rawURL, true) - if err != nil { - return nil, &Error{"parse", rawURL, err} - } - return url, nil -} - -// parse parses a URL from a string in one of two contexts. If -// viaRequest is true, the URL is assumed to have arrived via an HTTP request, -// in which case only absolute URLs or path-absolute relative URLs are allowed. -// If viaRequest is false, all forms of relative URLs are allowed. -func parse(rawURL string, viaRequest bool) (*URL, error) { - var rest string - var err error - - if stringContainsCTLByte(rawURL) { - return nil, errors.New("net/url: invalid control character in URL") - } - - if rawURL == "" && viaRequest { - return nil, errors.New("empty url") - } - url := new(URL) - - if rawURL == "*" { - url.Path = "*" - return url, nil - } - - // Split off possible leading "http:", "mailto:", etc. - // Cannot contain escaped characters. - if url.Scheme, rest, err = getScheme(rawURL); err != nil { - return nil, err - } - url.Scheme = strings.ToLower(url.Scheme) - - if strings.HasSuffix(rest, "?") && strings.Count(rest, "?") == 1 { - url.ForceQuery = true - rest = rest[:len(rest)-1] - } else { - rest, url.RawQuery, _ = strings.Cut(rest, "?") - } - - if !strings.HasPrefix(rest, "/") { - if url.Scheme != "" { - // We consider rootless paths per RFC 3986 as opaque. - url.Opaque = rest - return url, nil - } - if viaRequest { - return nil, errors.New("invalid URI for request") - } - - // Avoid confusion with malformed schemes, like cache_object:foo/bar. - // See golang.org/issue/16822. - // - // RFC 3986, §3.3: - // In addition, a URI reference (Section 4.1) may be a relative-path reference, - // in which case the first path segment cannot contain a colon (":") character. - if segment, _, _ := strings.Cut(rest, "/"); strings.Contains(segment, ":") { - // First path segment has colon. Not allowed in relative URL. - return nil, errors.New("first path segment in URL cannot contain colon") - } - } - - if (url.Scheme != "" || !viaRequest && !strings.HasPrefix(rest, "///")) && strings.HasPrefix(rest, "//") { - var authority string - authority, rest = rest[2:], "" - if i := strings.Index(authority, "/"); i >= 0 { - authority, rest = authority[:i], authority[i:] - } - url.User, url.Host, err = parseAuthority(authority) - if err != nil { - return nil, err - } - } else if url.Scheme != "" && strings.HasPrefix(rest, "/") { - // OmitHost is set to true when rawURL has an empty host (authority). - // See golang.org/issue/46059. - url.OmitHost = true - } - - // Set Path and, optionally, RawPath. - // RawPath is a hint of the encoding of Path. We don't want to set it if - // the default escaping of Path is equivalent, to help make sure that people - // don't rely on it in general. - if err := url.setPath(rest); err != nil { - return nil, err - } - return url, nil -} - -func parseAuthority(authority string) (user *Userinfo, host string, err error) { - i := strings.LastIndex(authority, "@") - if i < 0 { - host, err = parseHost(authority) - } else { - host, err = parseHost(authority[i+1:]) - } - if err != nil { - return nil, "", err - } - if i < 0 { - return nil, host, nil - } - userinfo := authority[:i] - if !validUserinfo(userinfo) { - return nil, "", errors.New("net/url: invalid userinfo") - } - if !strings.Contains(userinfo, ":") { - if userinfo, err = unescape(userinfo, encodeUserPassword); err != nil { - return nil, "", err - } - user = User(userinfo) - } else { - username, password, _ := strings.Cut(userinfo, ":") - if username, err = unescape(username, encodeUserPassword); err != nil { - return nil, "", err - } - if password, err = unescape(password, encodeUserPassword); err != nil { - return nil, "", err - } - user = UserPassword(username, password) - } - return user, host, nil -} - -// parseHost parses host as an authority without user -// information. That is, as host[:port]. -func parseHost(host string) (string, error) { - if strings.HasPrefix(host, "[") { - // Parse an IP-Literal in RFC 3986 and RFC 6874. - // E.g., "[fe80::1]", "[fe80::1%25en0]", "[fe80::1]:80". - i := strings.LastIndex(host, "]") - if i < 0 { - return "", errors.New("missing ']' in host") - } - colonPort := host[i+1:] - if !validOptionalPort(colonPort) { - return "", fmt.Errorf("invalid port %q after host", colonPort) - } - - // RFC 6874 defines that %25 (%-encoded percent) introduces - // the zone identifier, and the zone identifier can use basically - // any %-encoding it likes. That's different from the host, which - // can only %-encode non-ASCII bytes. - // We do impose some restrictions on the zone, to avoid stupidity - // like newlines. - zone := strings.Index(host[:i], "%25") - if zone >= 0 { - host1, err := unescape(host[:zone], encodeHost) - if err != nil { - return "", err - } - host2, err := unescape(host[zone:i], encodeZone) - if err != nil { - return "", err - } - host3, err := unescape(host[i:], encodeHost) - if err != nil { - return "", err - } - return host1 + host2 + host3, nil - } - } else if i := strings.LastIndex(host, ":"); i != -1 { - colonPort := host[i:] - if !validOptionalPort(colonPort) { - return "", fmt.Errorf("invalid port %q after host", colonPort) - } - } - - var err error - if host, err = unescape(host, encodeHost); err != nil { - return "", err - } - return host, nil -} - -// setPath sets the Path and RawPath fields of the URL based on the provided -// escaped path p. It maintains the invariant that RawPath is only specified -// when it differs from the default encoding of the path. -// For example: -// - setPath("/foo/bar") will set Path="/foo/bar" and RawPath="" -// - setPath("/foo%2fbar") will set Path="/foo/bar" and RawPath="/foo%2fbar" -// setPath will return an error only if the provided path contains an invalid -// escaping. -func (u *URL) setPath(p string) error { - path, err := unescape(p, encodePath) - if err != nil { - return err - } - u.Path = path - if escp := escape(path, encodePath); p == escp { - // Default encoding is fine. - u.RawPath = "" - } else { - u.RawPath = p - } - return nil -} - -// EscapedPath returns the escaped form of u.Path. -// In general there are multiple possible escaped forms of any path. -// EscapedPath returns u.RawPath when it is a valid escaping of u.Path. -// Otherwise EscapedPath ignores u.RawPath and computes an escaped -// form on its own. -// The String and RequestURI methods use EscapedPath to construct -// their results. -// In general, code should call EscapedPath instead of -// reading u.RawPath directly. -func (u *URL) EscapedPath() string { - if u.RawPath != "" && validEncoded(u.RawPath, encodePath) { - p, err := unescape(u.RawPath, encodePath) - if err == nil && p == u.Path { - return u.RawPath - } - } - if u.Path == "*" { - return "*" // don't escape (Issue 11202) - } - return escape(u.Path, encodePath) -} - -// validEncoded reports whether s is a valid encoded path or fragment, -// according to mode. -// It must not contain any bytes that require escaping during encoding. -func validEncoded(s string, mode encoding) bool { - for i := 0; i < len(s); i++ { - // RFC 3986, Appendix A. - // pchar = unreserved / pct-encoded / sub-delims / ":" / "@". - // shouldEscape is not quite compliant with the RFC, - // so we check the sub-delims ourselves and let - // shouldEscape handle the others. - switch s[i] { - case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '@': - // ok - case '[', ']': - // ok - not specified in RFC 3986 but left alone by modern browsers - case '%': - // ok - percent encoded, will decode - default: - if shouldEscape(s[i], mode) { - return false - } - } - } - return true -} - -// setFragment is like setPath but for Fragment/RawFragment. -func (u *URL) setFragment(f string) error { - frag, err := unescape(f, encodeFragment) - if err != nil { - return err - } - u.Fragment = frag - if escf := escape(frag, encodeFragment); f == escf { - // Default encoding is fine. - u.RawFragment = "" - } else { - u.RawFragment = f - } - return nil -} - -// EscapedFragment returns the escaped form of u.Fragment. -// In general there are multiple possible escaped forms of any fragment. -// EscapedFragment returns u.RawFragment when it is a valid escaping of u.Fragment. -// Otherwise EscapedFragment ignores u.RawFragment and computes an escaped -// form on its own. -// The String method uses EscapedFragment to construct its result. -// In general, code should call EscapedFragment instead of -// reading u.RawFragment directly. -func (u *URL) EscapedFragment() string { - if u.RawFragment != "" && validEncoded(u.RawFragment, encodeFragment) { - f, err := unescape(u.RawFragment, encodeFragment) - if err == nil && f == u.Fragment { - return u.RawFragment - } - } - return escape(u.Fragment, encodeFragment) -} - -// validOptionalPort reports whether port is either an empty string -// or matches /^:\d*$/ -func validOptionalPort(port string) bool { - if port == "" { - return true - } - if port[0] != ':' { - return false - } - for _, b := range port[1:] { - if b < '0' || b > '9' { - return false - } - } - return true -} - -// String reassembles the URL into a valid URL string. -// The general form of the result is one of: -// -// scheme:opaque?query#fragment -// scheme://userinfo@host/path?query#fragment -// -// If u.Opaque is non-empty, String uses the first form; -// otherwise it uses the second form. -// Any non-ASCII characters in host are escaped. -// To obtain the path, String uses u.EscapedPath(). -// -// In the second form, the following rules apply: -// - if u.Scheme is empty, scheme: is omitted. -// - if u.User is nil, userinfo@ is omitted. -// - if u.Host is empty, host/ is omitted. -// - if u.Scheme and u.Host are empty and u.User is nil, -// the entire scheme://userinfo@host/ is omitted. -// - if u.Host is non-empty and u.Path begins with a /, -// the form host/path does not add its own /. -// - if u.RawQuery is empty, ?query is omitted. -// - if u.Fragment is empty, #fragment is omitted. -func (u *URL) String() string { - var buf strings.Builder - if u.Scheme != "" { - buf.WriteString(u.Scheme) - buf.WriteByte(':') - } - if u.Opaque != "" { - buf.WriteString(u.Opaque) - } else { - if u.Scheme != "" || u.Host != "" || u.User != nil { - if u.OmitHost && u.Host == "" && u.User == nil { - // omit empty host - } else { - if u.Host != "" || u.Path != "" || u.User != nil { - buf.WriteString("//") - } - if ui := u.User; ui != nil { - buf.WriteString(ui.String()) - buf.WriteByte('@') - } - if h := u.Host; h != "" { - buf.WriteString(escape(h, encodeHost)) - } - } - } - path := u.EscapedPath() - if path != "" && path[0] != '/' && u.Host != "" { - buf.WriteByte('/') - } - if buf.Len() == 0 { - // RFC 3986 §4.2 - // A path segment that contains a colon character (e.g., "this:that") - // cannot be used as the first segment of a relative-path reference, as - // it would be mistaken for a scheme name. Such a segment must be - // preceded by a dot-segment (e.g., "./this:that") to make a relative- - // path reference. - if segment, _, _ := strings.Cut(path, "/"); strings.Contains(segment, ":") { - buf.WriteString("./") - } - } - buf.WriteString(path) - } - if u.ForceQuery || u.RawQuery != "" { - buf.WriteByte('?') - buf.WriteString(u.RawQuery) - } - if u.Fragment != "" { - buf.WriteByte('#') - buf.WriteString(u.EscapedFragment()) - } - return buf.String() -} - -// Redacted is like String but replaces any password with "xxxxx". -// Only the password in u.URL is redacted. -func (u *URL) Redacted() string { - if u == nil { - return "" - } - - ru := *u - if _, has := ru.User.Password(); has { - ru.User = UserPassword(ru.User.Username(), "xxxxx") - } - return ru.String() -} - -// Values maps a string key to a list of values. -// It is typically used for query parameters and form values. -// Unlike in the http.Header map, the keys in a Values map -// are case-sensitive. -type Values map[string][]string - -// Get gets the first value associated with the given key. -// If there are no values associated with the key, Get returns -// the empty string. To access multiple values, use the map -// directly. -func (v Values) Get(key string) string { - if v == nil { - return "" - } - vs := v[key] - if len(vs) == 0 { - return "" - } - return vs[0] -} - -// Set sets the key to value. It replaces any existing -// values. -func (v Values) Set(key, value string) { - v[key] = []string{value} -} - -// Add adds the value to key. It appends to any existing -// values associated with key. -func (v Values) Add(key, value string) { - v[key] = append(v[key], value) -} - -// Del deletes the values associated with key. -func (v Values) Del(key string) { - delete(v, key) -} - -// Has checks whether a given key is set. -func (v Values) Has(key string) bool { - _, ok := v[key] - return ok -} - -// ParseQuery parses the URL-encoded query string and returns -// a map listing the values specified for each key. -// ParseQuery always returns a non-nil map containing all the -// valid query parameters found; err describes the first decoding error -// encountered, if any. -// -// Query is expected to be a list of key=value settings separated by ampersands. -// A setting without an equals sign is interpreted as a key set to an empty -// value. -// Settings containing a non-URL-encoded semicolon are considered invalid. -func ParseQuery(query string) (Values, error) { - m := make(Values) - err := parseQuery(m, query) - return m, err -} - -func parseQuery(m Values, query string) (err error) { - for query != "" { - var key string - key, query, _ = strings.Cut(query, "&") - if strings.Contains(key, ";") { - err = fmt.Errorf("invalid semicolon separator in query") - continue - } - if key == "" { - continue - } - key, value, _ := strings.Cut(key, "=") - key, err1 := QueryUnescape(key) - if err1 != nil { - if err == nil { - err = err1 - } - continue - } - value, err1 = QueryUnescape(value) - if err1 != nil { - if err == nil { - err = err1 - } - continue - } - m[key] = append(m[key], value) - } - return err -} - -// Encode encodes the values into “URL encoded” form -// ("bar=baz&foo=quux") sorted by key. -func (v Values) Encode() string { - if v == nil { - return "" - } - var buf strings.Builder - keys := make([]string, 0, len(v)) - for k := range v { - keys = append(keys, k) - } - sort.Strings(keys) - for _, k := range keys { - vs := v[k] - keyEscaped := QueryEscape(k) - for _, v := range vs { - if buf.Len() > 0 { - buf.WriteByte('&') - } - buf.WriteString(keyEscaped) - buf.WriteByte('=') - buf.WriteString(QueryEscape(v)) - } - } - return buf.String() -} - -// resolvePath applies special path segments from refs and applies -// them to base, per RFC 3986. -func resolvePath(base, ref string) string { - var full string - if ref == "" { - full = base - } else if ref[0] != '/' { - i := strings.LastIndex(base, "/") - full = base[:i+1] + ref - } else { - full = ref - } - if full == "" { - return "" - } - - var ( - elem string - dst strings.Builder - ) - first := true - remaining := full - // We want to return a leading '/', so write it now. - dst.WriteByte('/') - found := true - for found { - elem, remaining, found = strings.Cut(remaining, "/") - if elem == "." { - first = false - // drop - continue - } - - if elem == ".." { - // Ignore the leading '/' we already wrote. - str := dst.String()[1:] - index := strings.LastIndexByte(str, '/') - - dst.Reset() - dst.WriteByte('/') - if index == -1 { - first = true - } else { - dst.WriteString(str[:index]) - } - } else { - if !first { - dst.WriteByte('/') - } - dst.WriteString(elem) - first = false - } - } - - if elem == "." || elem == ".." { - dst.WriteByte('/') - } - - // We wrote an initial '/', but we don't want two. - r := dst.String() - if len(r) > 1 && r[1] == '/' { - r = r[1:] - } - return r -} - -// IsAbs reports whether the URL is absolute. -// Absolute means that it has a non-empty scheme. -func (u *URL) IsAbs() bool { - return u.Scheme != "" -} - -// Parse parses a URL in the context of the receiver. The provided URL -// may be relative or absolute. Parse returns nil, err on parse -// failure, otherwise its return value is the same as ResolveReference. -func (u *URL) Parse(ref string) (*URL, error) { - refURL, err := Parse(ref) - if err != nil { - return nil, err - } - return u.ResolveReference(refURL), nil -} - -// ResolveReference resolves a URI reference to an absolute URI from -// an absolute base URI u, per RFC 3986 Section 5.2. The URI reference -// may be relative or absolute. ResolveReference always returns a new -// URL instance, even if the returned URL is identical to either the -// base or reference. If ref is an absolute URL, then ResolveReference -// ignores base and returns a copy of ref. -func (u *URL) ResolveReference(ref *URL) *URL { - url := *ref - if ref.Scheme == "" { - url.Scheme = u.Scheme - } - if ref.Scheme != "" || ref.Host != "" || ref.User != nil { - // The "absoluteURI" or "net_path" cases. - // We can ignore the error from setPath since we know we provided a - // validly-escaped path. - url.setPath(resolvePath(ref.EscapedPath(), "")) - return &url - } - if ref.Opaque != "" { - url.User = nil - url.Host = "" - url.Path = "" - return &url - } - if ref.Path == "" && !ref.ForceQuery && ref.RawQuery == "" { - url.RawQuery = u.RawQuery - if ref.Fragment == "" { - url.Fragment = u.Fragment - url.RawFragment = u.RawFragment - } - } - // The "abs_path" or "rel_path" cases. - url.Host = u.Host - url.User = u.User - url.setPath(resolvePath(u.EscapedPath(), ref.EscapedPath())) - return &url -} - -// Query parses RawQuery and returns the corresponding values. -// It silently discards malformed value pairs. -// To check errors use ParseQuery. -func (u *URL) Query() Values { - v, _ := ParseQuery(u.RawQuery) - return v -} - -// RequestURI returns the encoded path?query or opaque?query -// string that would be used in an HTTP request for u. -func (u *URL) RequestURI() string { - result := u.Opaque - if result == "" { - result = u.EscapedPath() - if result == "" { - result = "/" - } - } else { - if strings.HasPrefix(result, "//") { - result = u.Scheme + ":" + result - } - } - if u.ForceQuery || u.RawQuery != "" { - result += "?" + u.RawQuery - } - return result -} - -// Hostname returns u.Host, stripping any valid port number if present. -// -// If the result is enclosed in square brackets, as literal IPv6 addresses are, -// the square brackets are removed from the result. -func (u *URL) Hostname() string { - host, _ := splitHostPort(u.Host) - return host -} - -// Port returns the port part of u.Host, without the leading colon. -// -// If u.Host doesn't contain a valid numeric port, Port returns an empty string. -func (u *URL) Port() string { - _, port := splitHostPort(u.Host) - return port -} - -// splitHostPort separates host and port. If the port is not valid, it returns -// the entire input as host, and it doesn't check the validity of the host. -// Unlike net.SplitHostPort, but per RFC 3986, it requires ports to be numeric. -func splitHostPort(hostPort string) (host, port string) { - host = hostPort - - colon := strings.LastIndexByte(host, ':') - if colon != -1 && validOptionalPort(host[colon:]) { - host, port = host[:colon], host[colon+1:] - } - - if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") { - host = host[1 : len(host)-1] - } - - return -} - -// Marshaling interface implementations. -// Would like to implement MarshalText/UnmarshalText but that will change the JSON representation of URLs. - -func (u *URL) MarshalBinary() (text []byte, err error) { - return []byte(u.String()), nil -} - -func (u *URL) UnmarshalBinary(text []byte) error { - u1, err := Parse(string(text)) - if err != nil { - return err - } - *u = *u1 - return nil -} - -// JoinPath returns a new URL with the provided path elements joined to -// any existing path and the resulting path cleaned of any ./ or ../ elements. -// Any sequences of multiple / characters will be reduced to a single /. -func (u *URL) JoinPath(elem ...string) *URL { - elem = append([]string{u.EscapedPath()}, elem...) - var p string - if !strings.HasPrefix(elem[0], "/") { - // Return a relative path if u is relative, - // but ensure that it contains no ../ elements. - elem[0] = "/" + elem[0] - p = path.Join(elem...)[1:] - } else { - p = path.Join(elem...) - } - // path.Join will remove any trailing slashes. - // Preserve at least one. - if strings.HasSuffix(elem[len(elem)-1], "/") && !strings.HasSuffix(p, "/") { - p += "/" - } - url := *u - url.setPath(p) - return &url -} - -// validUserinfo reports whether s is a valid userinfo string per RFC 3986 -// Section 3.2.1: -// -// userinfo = *( unreserved / pct-encoded / sub-delims / ":" ) -// unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" -// sub-delims = "!" / "$" / "&" / "'" / "(" / ")" -// / "*" / "+" / "," / ";" / "=" -// -// It doesn't validate pct-encoded. The caller does that via func unescape. -func validUserinfo(s string) bool { - for _, r := range s { - if 'A' <= r && r <= 'Z' { - continue - } - if 'a' <= r && r <= 'z' { - continue - } - if '0' <= r && r <= '9' { - continue - } - switch r { - case '-', '.', '_', ':', '~', '!', '$', '&', '\'', - '(', ')', '*', '+', ',', ';', '=', '%', '@': - continue - default: - return false - } - } - return true -} - -// stringContainsCTLByte reports whether s contains any ASCII control character. -func stringContainsCTLByte(s string) bool { - for i := 0; i < len(s); i++ { - b := s[i] - if b < ' ' || b == 0x7f { - return true - } - } - return false -} - -// JoinPath returns a URL string with the provided path elements joined to -// the existing path of base and the resulting path cleaned of any ./ or ../ elements. -func JoinPath(base string, elem ...string) (result string, err error) { - url, err := Parse(base) - if err != nil { - return - } - result = url.JoinPath(elem...).String() - return -} From ceff40fc5ee234ffda6d2d77a93910195bff6cbd Mon Sep 17 00:00:00 2001 From: Yury Date: Thu, 16 Nov 2023 15:20:38 +0200 Subject: [PATCH 101/134] Sprint 1.11 revert (#1284) * Revert "experiment" This reverts commit 050270f52815dcd930f760f20a4c7e3e669d73fb. * Revert "experiment" This reverts commit d4821f8e28c4efce59775129b4f25eaa1df2905d. * Revert "experiment" This reverts commit 9f65b2eef30528662b59482a6c59d6a633f1ff77. * Revert "experiment" This reverts commit 6313cb8a49d211ab8a6c476ca839922be7c31288. * Revert "experiment" This reverts commit b6be0b51767f39cb53a9439c3a34fe2f828b2dfc. * Revert "experiment" This reverts commit 68d41905a3aaf1c094d50f7b418349d7c78663cc. * Revert "experiment" This reverts commit 3a23f3f33b9446cf5711f950b0cd80a40993e429. * Revert "experiment" This reverts commit 6b6578bb857c9e4351db941fc84e65fac0994c15. * Revert "experiment" This reverts commit 65a0152adc10754977a479e09cdb8d577ca8aefb. * Revert "experiment" This reverts commit 6834b058a99bba80621c756292f7f4205b24e936. * Revert "experiment" This reverts commit 8446894c579f5acd14db1b09b5966f92ca1588be. * Revert "hotfix" This reverts commit 48cf793a70f754f44c662d839bdde4e191ec2748. * Revert "hotfix" This reverts commit 895c7f0012837d2f9a0cbfdcddf47f8dbe0d13b7. * Revert "added logging" This reverts commit fafce3c9b90c0863e574a2609a202f962ecb90ac. * Revert "added logging" This reverts commit 10b6a4afbdecc1e8a201d5ac80c4d12f0b97c411. --- core/conf/config.go | 4 +- core/util/url.go | 1268 ------------------------------- core/version/version.go | 4 +- sdks/client.go | 4 +- zboxcore/sdk/networkworker.go | 5 +- zboxcore/zboxutil/http.go | 50 +- zcnbridge/http/rest.go | 5 +- zcncore/networkworker.go | 4 +- zcncore/networkworker_mobile.go | 4 - 9 files changed, 28 insertions(+), 1320 deletions(-) delete mode 100644 core/util/url.go diff --git a/core/conf/config.go b/core/conf/config.go index dfd1da32c..aae29ff2a 100644 --- a/core/conf/config.go +++ b/core/conf/config.go @@ -2,12 +2,12 @@ package conf import ( "errors" + "net/url" "os" "strings" thrown "github.com/0chain/errors" "github.com/0chain/gosdk/core/sys" - "github.com/0chain/gosdk/core/util" "github.com/spf13/viper" ) @@ -171,6 +171,6 @@ func LoadConfig(v Reader) (Config, error) { } func isURL(s string) bool { - u, err := util.Parse(s) + u, err := url.Parse(s) return err == nil && u.Scheme != "" && u.Host != "" } diff --git a/core/util/url.go b/core/util/url.go deleted file mode 100644 index 094a5fc43..000000000 --- a/core/util/url.go +++ /dev/null @@ -1,1268 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package url parses URLs and implements query escaping. -package util - -// See RFC 3986. This package generally follows RFC 3986, except where -// it deviates for compatibility reasons. When sending changes, first -// search old issues for history on decisions. Unit tests should also -// contain references to issue numbers with details. - -import ( - "errors" - "fmt" - "path" - "sort" - "strconv" - "strings" -) - -// Error reports an error and the operation and URL that caused it. -type Error struct { - Op string - URL string - Err error -} - -func (e *Error) Unwrap() error { return e.Err } -func (e *Error) Error() string { return fmt.Sprintf("%s %q: %s", e.Op, e.URL, e.Err) } - -func (e *Error) Timeout() bool { - t, ok := e.Err.(interface { - Timeout() bool - }) - return ok && t.Timeout() -} - -func (e *Error) Temporary() bool { - t, ok := e.Err.(interface { - Temporary() bool - }) - return ok && t.Temporary() -} - -const upperhex = "0123456789ABCDEF" - -func ishex(c byte) bool { - switch { - case '0' <= c && c <= '9': - return true - case 'a' <= c && c <= 'f': - return true - case 'A' <= c && c <= 'F': - return true - } - return false -} - -func unhex(c byte) byte { - switch { - case '0' <= c && c <= '9': - return c - '0' - case 'a' <= c && c <= 'f': - return c - 'a' + 10 - case 'A' <= c && c <= 'F': - return c - 'A' + 10 - } - return 0 -} - -type encoding int - -const ( - encodePath encoding = 1 + iota - encodePathSegment - encodeHost - encodeZone - encodeUserPassword - encodeQueryComponent - encodeFragment -) - -type EscapeError string - -func (e EscapeError) Error() string { - return "invalid URL escape " + strconv.Quote(string(e)) -} - -type InvalidHostError string - -func (e InvalidHostError) Error() string { - return "invalid character " + strconv.Quote(string(e)) + " in host name" -} - -// Return true if the specified character should be escaped when -// appearing in a URL string, according to RFC 3986. -// -// Please be informed that for now shouldEscape does not check all -// reserved characters correctly. See golang.org/issue/5684. -func shouldEscape(c byte, mode encoding) bool { - // §2.3 Unreserved characters (alphanum) - if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' { - return false - } - - if mode == encodeHost || mode == encodeZone { - // §3.2.2 Host allows - // sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" - // as part of reg-name. - // We add : because we include :port as part of host. - // We add [ ] because we include [ipv6]:port as part of host. - // We add < > because they're the only characters left that - // we could possibly allow, and Parse will reject them if we - // escape them (because hosts can't use %-encoding for - // ASCII bytes). - switch c { - case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '[', ']', '<', '>', '"': - return false - } - } - - switch c { - case '-', '_', '.', '~': // §2.3 Unreserved characters (mark) - return false - - case '$', '&', '+', ',', '/', ':', ';', '=', '?', '@': // §2.2 Reserved characters (reserved) - // Different sections of the URL allow a few of - // the reserved characters to appear unescaped. - switch mode { - case encodePath: // §3.3 - // The RFC allows : @ & = + $ but saves / ; , for assigning - // meaning to individual path segments. This package - // only manipulates the path as a whole, so we allow those - // last three as well. That leaves only ? to escape. - return c == '?' - - case encodePathSegment: // §3.3 - // The RFC allows : @ & = + $ but saves / ; , for assigning - // meaning to individual path segments. - return c == '/' || c == ';' || c == ',' || c == '?' - - case encodeUserPassword: // §3.2.1 - // The RFC allows ';', ':', '&', '=', '+', '$', and ',' in - // userinfo, so we must escape only '@', '/', and '?'. - // The parsing of userinfo treats ':' as special so we must escape - // that too. - return c == '@' || c == '/' || c == '?' || c == ':' - - case encodeQueryComponent: // §3.4 - // The RFC reserves (so we must escape) everything. - return true - - case encodeFragment: // §4.1 - // The RFC text is silent but the grammar allows - // everything, so escape nothing. - return false - } - } - - if mode == encodeFragment { - // RFC 3986 §2.2 allows not escaping sub-delims. A subset of sub-delims are - // included in reserved from RFC 2396 §2.2. The remaining sub-delims do not - // need to be escaped. To minimize potential breakage, we apply two restrictions: - // (1) we always escape sub-delims outside of the fragment, and (2) we always - // escape single quote to avoid breaking callers that had previously assumed that - // single quotes would be escaped. See issue #19917. - switch c { - case '!', '(', ')', '*': - return false - } - } - - // Everything else must be escaped. - return true -} - -// QueryUnescape does the inverse transformation of QueryEscape, -// converting each 3-byte encoded substring of the form "%AB" into the -// hex-decoded byte 0xAB. -// It returns an error if any % is not followed by two hexadecimal -// digits. -func QueryUnescape(s string) (string, error) { - return unescape(s, encodeQueryComponent) -} - -// PathUnescape does the inverse transformation of PathEscape, -// converting each 3-byte encoded substring of the form "%AB" into the -// hex-decoded byte 0xAB. It returns an error if any % is not followed -// by two hexadecimal digits. -// -// PathUnescape is identical to QueryUnescape except that it does not -// unescape '+' to ' ' (space). -func PathUnescape(s string) (string, error) { - return unescape(s, encodePathSegment) -} - -// unescape unescapes a string; the mode specifies -// which section of the URL string is being unescaped. -func unescape(s string, mode encoding) (string, error) { - // Count %, check that they're well-formed. - n := 0 - hasPlus := false - for i := 0; i < len(s); { - switch s[i] { - case '%': - n++ - if i+2 >= len(s) || !ishex(s[i+1]) || !ishex(s[i+2]) { - s = s[i:] - if len(s) > 3 { - s = s[:3] - } - return "", EscapeError(s) - } - // Per https://tools.ietf.org/html/rfc3986#page-21 - // in the host component %-encoding can only be used - // for non-ASCII bytes. - // But https://tools.ietf.org/html/rfc6874#section-2 - // introduces %25 being allowed to escape a percent sign - // in IPv6 scoped-address literals. Yay. - if mode == encodeHost && unhex(s[i+1]) < 8 && s[i:i+3] != "%25" { - return "", EscapeError(s[i : i+3]) - } - if mode == encodeZone { - // RFC 6874 says basically "anything goes" for zone identifiers - // and that even non-ASCII can be redundantly escaped, - // but it seems prudent to restrict %-escaped bytes here to those - // that are valid host name bytes in their unescaped form. - // That is, you can use escaping in the zone identifier but not - // to introduce bytes you couldn't just write directly. - // But Windows puts spaces here! Yay. - v := unhex(s[i+1])<<4 | unhex(s[i+2]) - if s[i:i+3] != "%25" && v != ' ' && shouldEscape(v, encodeHost) { - return "", EscapeError(s[i : i+3]) - } - } - i += 3 - case '+': - hasPlus = mode == encodeQueryComponent - i++ - default: - if (mode == encodeHost || mode == encodeZone) && s[i] < 0x80 && shouldEscape(s[i], mode) { - return "", InvalidHostError(s + ": symbol " + s[i:i+1]) - } - i++ - } - } - - if n == 0 && !hasPlus { - return s, nil - } - - var t strings.Builder - t.Grow(len(s) - 2*n) - for i := 0; i < len(s); i++ { - switch s[i] { - case '%': - t.WriteByte(unhex(s[i+1])<<4 | unhex(s[i+2])) - i += 2 - case '+': - if mode == encodeQueryComponent { - t.WriteByte(' ') - } else { - t.WriteByte('+') - } - default: - t.WriteByte(s[i]) - } - } - return t.String(), nil -} - -// QueryEscape escapes the string so it can be safely placed -// inside a URL query. -func QueryEscape(s string) string { - return escape(s, encodeQueryComponent) -} - -// PathEscape escapes the string so it can be safely placed inside a URL path segment, -// replacing special characters (including /) with %XX sequences as needed. -func PathEscape(s string) string { - return escape(s, encodePathSegment) -} - -func escape(s string, mode encoding) string { - spaceCount, hexCount := 0, 0 - for i := 0; i < len(s); i++ { - c := s[i] - if shouldEscape(c, mode) { - if c == ' ' && mode == encodeQueryComponent { - spaceCount++ - } else { - hexCount++ - } - } - } - - if spaceCount == 0 && hexCount == 0 { - return s - } - - var buf [64]byte - var t []byte - - required := len(s) + 2*hexCount - if required <= len(buf) { - t = buf[:required] - } else { - t = make([]byte, required) - } - - if hexCount == 0 { - copy(t, s) - for i := 0; i < len(s); i++ { - if s[i] == ' ' { - t[i] = '+' - } - } - return string(t) - } - - j := 0 - for i := 0; i < len(s); i++ { - switch c := s[i]; { - case c == ' ' && mode == encodeQueryComponent: - t[j] = '+' - j++ - case shouldEscape(c, mode): - t[j] = '%' - t[j+1] = upperhex[c>>4] - t[j+2] = upperhex[c&15] - j += 3 - default: - t[j] = s[i] - j++ - } - } - return string(t) -} - -// A URL represents a parsed URL (technically, a URI reference). -// -// The general form represented is: -// -// [scheme:][//[userinfo@]host][/]path[?query][#fragment] -// -// URLs that do not start with a slash after the scheme are interpreted as: -// -// scheme:opaque[?query][#fragment] -// -// Note that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/. -// A consequence is that it is impossible to tell which slashes in the Path were -// slashes in the raw URL and which were %2f. This distinction is rarely important, -// but when it is, the code should use the EscapedPath method, which preserves -// the original encoding of Path. -// -// The RawPath field is an optional field which is only set when the default -// encoding of Path is different from the escaped path. See the EscapedPath method -// for more details. -// -// URL's String method uses the EscapedPath method to obtain the path. -type URL struct { - Scheme string - Opaque string // encoded opaque data - User *Userinfo // username and password information - Host string // host or host:port - Path string // path (relative paths may omit leading slash) - RawPath string // encoded path hint (see EscapedPath method) - OmitHost bool // do not emit empty host (authority) - ForceQuery bool // append a query ('?') even if RawQuery is empty - RawQuery string // encoded query values, without '?' - Fragment string // fragment for references, without '#' - RawFragment string // encoded fragment hint (see EscapedFragment method) -} - -// User returns a Userinfo containing the provided username -// and no password set. -func User(username string) *Userinfo { - return &Userinfo{username, "", false} -} - -// UserPassword returns a Userinfo containing the provided username -// and password. -// -// This functionality should only be used with legacy web sites. -// RFC 2396 warns that interpreting Userinfo this way -// “is NOT RECOMMENDED, because the passing of authentication -// information in clear text (such as URI) has proven to be a -// security risk in almost every case where it has been used.” -func UserPassword(username, password string) *Userinfo { - return &Userinfo{username, password, true} -} - -// The Userinfo type is an immutable encapsulation of username and -// password details for a URL. An existing Userinfo value is guaranteed -// to have a username set (potentially empty, as allowed by RFC 2396), -// and optionally a password. -type Userinfo struct { - username string - password string - passwordSet bool -} - -// Username returns the username. -func (u *Userinfo) Username() string { - if u == nil { - return "" - } - return u.username -} - -// Password returns the password in case it is set, and whether it is set. -func (u *Userinfo) Password() (string, bool) { - if u == nil { - return "", false - } - return u.password, u.passwordSet -} - -// String returns the encoded userinfo information in the standard form -// of "username[:password]". -func (u *Userinfo) String() string { - if u == nil { - return "" - } - s := escape(u.username, encodeUserPassword) - if u.passwordSet { - s += ":" + escape(u.password, encodeUserPassword) - } - return s -} - -// Maybe rawURL is of the form scheme:path. -// (Scheme must be [a-zA-Z][a-zA-Z0-9+.-]*) -// If so, return scheme, path; else return "", rawURL. -func getScheme(rawURL string) (scheme, path string, err error) { - for i := 0; i < len(rawURL); i++ { - c := rawURL[i] - switch { - case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z': - // do nothing - case '0' <= c && c <= '9' || c == '+' || c == '-' || c == '.': - if i == 0 { - return "", rawURL, nil - } - case c == ':': - if i == 0 { - return "", "", errors.New("missing protocol scheme") - } - return rawURL[:i], rawURL[i+1:], nil - default: - // we have encountered an invalid character, - // so there is no valid scheme - return "", rawURL, nil - } - } - return "", rawURL, nil -} - -// Parse parses a raw url into a URL structure. -// -// The url may be relative (a path, without a host) or absolute -// (starting with a scheme). Trying to parse a hostname and path -// without a scheme is invalid but may not necessarily return an -// error, due to parsing ambiguities. -func Parse(rawURL string) (*URL, error) { - // Cut off #frag - u, frag, _ := strings.Cut(rawURL, "#") - url, err := parse(u, false) - if err != nil { - return nil, &Error{"parse", u, err} - } - if frag == "" { - return url, nil - } - if err = url.setFragment(frag); err != nil { - return nil, &Error{"parse", rawURL, err} - } - return url, nil -} - -// ParseRequestURI parses a raw url into a URL structure. It assumes that -// url was received in an HTTP request, so the url is interpreted -// only as an absolute URI or an absolute path. -// The string url is assumed not to have a #fragment suffix. -// (Web browsers strip #fragment before sending the URL to a web server.) -func ParseRequestURI(rawURL string) (*URL, error) { - url, err := parse(rawURL, true) - if err != nil { - return nil, &Error{"parse", rawURL, err} - } - return url, nil -} - -// parse parses a URL from a string in one of two contexts. If -// viaRequest is true, the URL is assumed to have arrived via an HTTP request, -// in which case only absolute URLs or path-absolute relative URLs are allowed. -// If viaRequest is false, all forms of relative URLs are allowed. -func parse(rawURL string, viaRequest bool) (*URL, error) { - var rest string - var err error - - if stringContainsCTLByte(rawURL) { - return nil, errors.New("net/url: invalid control character in URL") - } - - if rawURL == "" && viaRequest { - return nil, errors.New("empty url") - } - url := new(URL) - - if rawURL == "*" { - url.Path = "*" - return url, nil - } - - // Split off possible leading "http:", "mailto:", etc. - // Cannot contain escaped characters. - if url.Scheme, rest, err = getScheme(rawURL); err != nil { - return nil, err - } - url.Scheme = strings.ToLower(url.Scheme) - - if strings.HasSuffix(rest, "?") && strings.Count(rest, "?") == 1 { - url.ForceQuery = true - rest = rest[:len(rest)-1] - } else { - rest, url.RawQuery, _ = strings.Cut(rest, "?") - } - - if !strings.HasPrefix(rest, "/") { - if url.Scheme != "" { - // We consider rootless paths per RFC 3986 as opaque. - url.Opaque = rest - return url, nil - } - if viaRequest { - return nil, errors.New("invalid URI for request") - } - - // Avoid confusion with malformed schemes, like cache_object:foo/bar. - // See golang.org/issue/16822. - // - // RFC 3986, §3.3: - // In addition, a URI reference (Section 4.1) may be a relative-path reference, - // in which case the first path segment cannot contain a colon (":") character. - if segment, _, _ := strings.Cut(rest, "/"); strings.Contains(segment, ":") { - // First path segment has colon. Not allowed in relative URL. - return nil, errors.New("first path segment in URL cannot contain colon") - } - } - - if (url.Scheme != "" || !viaRequest && !strings.HasPrefix(rest, "///")) && strings.HasPrefix(rest, "//") { - var authority string - authority, rest = rest[2:], "" - if i := strings.Index(authority, "/"); i >= 0 { - authority, rest = authority[:i], authority[i:] - } - url.User, url.Host, err = parseAuthority(authority) - if err != nil { - return nil, err - } - } else if url.Scheme != "" && strings.HasPrefix(rest, "/") { - // OmitHost is set to true when rawURL has an empty host (authority). - // See golang.org/issue/46059. - url.OmitHost = true - } - - // Set Path and, optionally, RawPath. - // RawPath is a hint of the encoding of Path. We don't want to set it if - // the default escaping of Path is equivalent, to help make sure that people - // don't rely on it in general. - if err := url.setPath(rest); err != nil { - return nil, err - } - return url, nil -} - -func parseAuthority(authority string) (user *Userinfo, host string, err error) { - i := strings.LastIndex(authority, "@") - if i < 0 { - host, err = parseHost(authority) - } else { - host, err = parseHost(authority[i+1:]) - } - if err != nil { - return nil, "", err - } - if i < 0 { - return nil, host, nil - } - userinfo := authority[:i] - if !validUserinfo(userinfo) { - return nil, "", errors.New("net/url: invalid userinfo") - } - if !strings.Contains(userinfo, ":") { - if userinfo, err = unescape(userinfo, encodeUserPassword); err != nil { - return nil, "", err - } - user = User(userinfo) - } else { - username, password, _ := strings.Cut(userinfo, ":") - if username, err = unescape(username, encodeUserPassword); err != nil { - return nil, "", err - } - if password, err = unescape(password, encodeUserPassword); err != nil { - return nil, "", err - } - user = UserPassword(username, password) - } - return user, host, nil -} - -// parseHost parses host as an authority without user -// information. That is, as host[:port]. -func parseHost(host string) (string, error) { - if strings.HasPrefix(host, "[") { - // Parse an IP-Literal in RFC 3986 and RFC 6874. - // E.g., "[fe80::1]", "[fe80::1%25en0]", "[fe80::1]:80". - i := strings.LastIndex(host, "]") - if i < 0 { - return "", errors.New("missing ']' in host") - } - colonPort := host[i+1:] - if !validOptionalPort(colonPort) { - return "", fmt.Errorf("invalid port %q after host", colonPort) - } - - // RFC 6874 defines that %25 (%-encoded percent) introduces - // the zone identifier, and the zone identifier can use basically - // any %-encoding it likes. That's different from the host, which - // can only %-encode non-ASCII bytes. - // We do impose some restrictions on the zone, to avoid stupidity - // like newlines. - zone := strings.Index(host[:i], "%25") - if zone >= 0 { - host1, err := unescape(host[:zone], encodeHost) - if err != nil { - return "", err - } - host2, err := unescape(host[zone:i], encodeZone) - if err != nil { - return "", err - } - host3, err := unescape(host[i:], encodeHost) - if err != nil { - return "", err - } - return host1 + host2 + host3, nil - } - } else if i := strings.LastIndex(host, ":"); i != -1 { - colonPort := host[i:] - if !validOptionalPort(colonPort) { - return "", fmt.Errorf("invalid port %q after host", colonPort) - } - } - - var err error - if host, err = unescape(host, encodeHost); err != nil { - return "", err - } - return host, nil -} - -// setPath sets the Path and RawPath fields of the URL based on the provided -// escaped path p. It maintains the invariant that RawPath is only specified -// when it differs from the default encoding of the path. -// For example: -// - setPath("/foo/bar") will set Path="/foo/bar" and RawPath="" -// - setPath("/foo%2fbar") will set Path="/foo/bar" and RawPath="/foo%2fbar" -// setPath will return an error only if the provided path contains an invalid -// escaping. -func (u *URL) setPath(p string) error { - path, err := unescape(p, encodePath) - if err != nil { - return err - } - u.Path = path - if escp := escape(path, encodePath); p == escp { - // Default encoding is fine. - u.RawPath = "" - } else { - u.RawPath = p - } - return nil -} - -// EscapedPath returns the escaped form of u.Path. -// In general there are multiple possible escaped forms of any path. -// EscapedPath returns u.RawPath when it is a valid escaping of u.Path. -// Otherwise EscapedPath ignores u.RawPath and computes an escaped -// form on its own. -// The String and RequestURI methods use EscapedPath to construct -// their results. -// In general, code should call EscapedPath instead of -// reading u.RawPath directly. -func (u *URL) EscapedPath() string { - if u.RawPath != "" && validEncoded(u.RawPath, encodePath) { - p, err := unescape(u.RawPath, encodePath) - if err == nil && p == u.Path { - return u.RawPath - } - } - if u.Path == "*" { - return "*" // don't escape (Issue 11202) - } - return escape(u.Path, encodePath) -} - -// validEncoded reports whether s is a valid encoded path or fragment, -// according to mode. -// It must not contain any bytes that require escaping during encoding. -func validEncoded(s string, mode encoding) bool { - for i := 0; i < len(s); i++ { - // RFC 3986, Appendix A. - // pchar = unreserved / pct-encoded / sub-delims / ":" / "@". - // shouldEscape is not quite compliant with the RFC, - // so we check the sub-delims ourselves and let - // shouldEscape handle the others. - switch s[i] { - case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '@': - // ok - case '[', ']': - // ok - not specified in RFC 3986 but left alone by modern browsers - case '%': - // ok - percent encoded, will decode - default: - if shouldEscape(s[i], mode) { - return false - } - } - } - return true -} - -// setFragment is like setPath but for Fragment/RawFragment. -func (u *URL) setFragment(f string) error { - frag, err := unescape(f, encodeFragment) - if err != nil { - return err - } - u.Fragment = frag - if escf := escape(frag, encodeFragment); f == escf { - // Default encoding is fine. - u.RawFragment = "" - } else { - u.RawFragment = f - } - return nil -} - -// EscapedFragment returns the escaped form of u.Fragment. -// In general there are multiple possible escaped forms of any fragment. -// EscapedFragment returns u.RawFragment when it is a valid escaping of u.Fragment. -// Otherwise EscapedFragment ignores u.RawFragment and computes an escaped -// form on its own. -// The String method uses EscapedFragment to construct its result. -// In general, code should call EscapedFragment instead of -// reading u.RawFragment directly. -func (u *URL) EscapedFragment() string { - if u.RawFragment != "" && validEncoded(u.RawFragment, encodeFragment) { - f, err := unescape(u.RawFragment, encodeFragment) - if err == nil && f == u.Fragment { - return u.RawFragment - } - } - return escape(u.Fragment, encodeFragment) -} - -// validOptionalPort reports whether port is either an empty string -// or matches /^:\d*$/ -func validOptionalPort(port string) bool { - if port == "" { - return true - } - if port[0] != ':' { - return false - } - for _, b := range port[1:] { - if b < '0' || b > '9' { - return false - } - } - return true -} - -// String reassembles the URL into a valid URL string. -// The general form of the result is one of: -// -// scheme:opaque?query#fragment -// scheme://userinfo@host/path?query#fragment -// -// If u.Opaque is non-empty, String uses the first form; -// otherwise it uses the second form. -// Any non-ASCII characters in host are escaped. -// To obtain the path, String uses u.EscapedPath(). -// -// In the second form, the following rules apply: -// - if u.Scheme is empty, scheme: is omitted. -// - if u.User is nil, userinfo@ is omitted. -// - if u.Host is empty, host/ is omitted. -// - if u.Scheme and u.Host are empty and u.User is nil, -// the entire scheme://userinfo@host/ is omitted. -// - if u.Host is non-empty and u.Path begins with a /, -// the form host/path does not add its own /. -// - if u.RawQuery is empty, ?query is omitted. -// - if u.Fragment is empty, #fragment is omitted. -func (u *URL) String() string { - var buf strings.Builder - if u.Scheme != "" { - buf.WriteString(u.Scheme) - buf.WriteByte(':') - } - if u.Opaque != "" { - buf.WriteString(u.Opaque) - } else { - if u.Scheme != "" || u.Host != "" || u.User != nil { - if u.OmitHost && u.Host == "" && u.User == nil { - // omit empty host - } else { - if u.Host != "" || u.Path != "" || u.User != nil { - buf.WriteString("//") - } - if ui := u.User; ui != nil { - buf.WriteString(ui.String()) - buf.WriteByte('@') - } - if h := u.Host; h != "" { - buf.WriteString(escape(h, encodeHost)) - } - } - } - path := u.EscapedPath() - if path != "" && path[0] != '/' && u.Host != "" { - buf.WriteByte('/') - } - if buf.Len() == 0 { - // RFC 3986 §4.2 - // A path segment that contains a colon character (e.g., "this:that") - // cannot be used as the first segment of a relative-path reference, as - // it would be mistaken for a scheme name. Such a segment must be - // preceded by a dot-segment (e.g., "./this:that") to make a relative- - // path reference. - if segment, _, _ := strings.Cut(path, "/"); strings.Contains(segment, ":") { - buf.WriteString("./") - } - } - buf.WriteString(path) - } - if u.ForceQuery || u.RawQuery != "" { - buf.WriteByte('?') - buf.WriteString(u.RawQuery) - } - if u.Fragment != "" { - buf.WriteByte('#') - buf.WriteString(u.EscapedFragment()) - } - return buf.String() -} - -// Redacted is like String but replaces any password with "xxxxx". -// Only the password in u.URL is redacted. -func (u *URL) Redacted() string { - if u == nil { - return "" - } - - ru := *u - if _, has := ru.User.Password(); has { - ru.User = UserPassword(ru.User.Username(), "xxxxx") - } - return ru.String() -} - -// Values maps a string key to a list of values. -// It is typically used for query parameters and form values. -// Unlike in the http.Header map, the keys in a Values map -// are case-sensitive. -type Values map[string][]string - -// Get gets the first value associated with the given key. -// If there are no values associated with the key, Get returns -// the empty string. To access multiple values, use the map -// directly. -func (v Values) Get(key string) string { - if v == nil { - return "" - } - vs := v[key] - if len(vs) == 0 { - return "" - } - return vs[0] -} - -// Set sets the key to value. It replaces any existing -// values. -func (v Values) Set(key, value string) { - v[key] = []string{value} -} - -// Add adds the value to key. It appends to any existing -// values associated with key. -func (v Values) Add(key, value string) { - v[key] = append(v[key], value) -} - -// Del deletes the values associated with key. -func (v Values) Del(key string) { - delete(v, key) -} - -// Has checks whether a given key is set. -func (v Values) Has(key string) bool { - _, ok := v[key] - return ok -} - -// ParseQuery parses the URL-encoded query string and returns -// a map listing the values specified for each key. -// ParseQuery always returns a non-nil map containing all the -// valid query parameters found; err describes the first decoding error -// encountered, if any. -// -// Query is expected to be a list of key=value settings separated by ampersands. -// A setting without an equals sign is interpreted as a key set to an empty -// value. -// Settings containing a non-URL-encoded semicolon are considered invalid. -func ParseQuery(query string) (Values, error) { - m := make(Values) - err := parseQuery(m, query) - return m, err -} - -func parseQuery(m Values, query string) (err error) { - for query != "" { - var key string - key, query, _ = strings.Cut(query, "&") - if strings.Contains(key, ";") { - err = fmt.Errorf("invalid semicolon separator in query") - continue - } - if key == "" { - continue - } - key, value, _ := strings.Cut(key, "=") - key, err1 := QueryUnescape(key) - if err1 != nil { - if err == nil { - err = err1 - } - continue - } - value, err1 = QueryUnescape(value) - if err1 != nil { - if err == nil { - err = err1 - } - continue - } - m[key] = append(m[key], value) - } - return err -} - -// Encode encodes the values into “URL encoded” form -// ("bar=baz&foo=quux") sorted by key. -func (v Values) Encode() string { - if v == nil { - return "" - } - var buf strings.Builder - keys := make([]string, 0, len(v)) - for k := range v { - keys = append(keys, k) - } - sort.Strings(keys) - for _, k := range keys { - vs := v[k] - keyEscaped := QueryEscape(k) - for _, v := range vs { - if buf.Len() > 0 { - buf.WriteByte('&') - } - buf.WriteString(keyEscaped) - buf.WriteByte('=') - buf.WriteString(QueryEscape(v)) - } - } - return buf.String() -} - -// resolvePath applies special path segments from refs and applies -// them to base, per RFC 3986. -func resolvePath(base, ref string) string { - var full string - if ref == "" { - full = base - } else if ref[0] != '/' { - i := strings.LastIndex(base, "/") - full = base[:i+1] + ref - } else { - full = ref - } - if full == "" { - return "" - } - - var ( - elem string - dst strings.Builder - ) - first := true - remaining := full - // We want to return a leading '/', so write it now. - dst.WriteByte('/') - found := true - for found { - elem, remaining, found = strings.Cut(remaining, "/") - if elem == "." { - first = false - // drop - continue - } - - if elem == ".." { - // Ignore the leading '/' we already wrote. - str := dst.String()[1:] - index := strings.LastIndexByte(str, '/') - - dst.Reset() - dst.WriteByte('/') - if index == -1 { - first = true - } else { - dst.WriteString(str[:index]) - } - } else { - if !first { - dst.WriteByte('/') - } - dst.WriteString(elem) - first = false - } - } - - if elem == "." || elem == ".." { - dst.WriteByte('/') - } - - // We wrote an initial '/', but we don't want two. - r := dst.String() - if len(r) > 1 && r[1] == '/' { - r = r[1:] - } - return r -} - -// IsAbs reports whether the URL is absolute. -// Absolute means that it has a non-empty scheme. -func (u *URL) IsAbs() bool { - return u.Scheme != "" -} - -// Parse parses a URL in the context of the receiver. The provided URL -// may be relative or absolute. Parse returns nil, err on parse -// failure, otherwise its return value is the same as ResolveReference. -func (u *URL) Parse(ref string) (*URL, error) { - refURL, err := Parse(ref) - if err != nil { - return nil, err - } - return u.ResolveReference(refURL), nil -} - -// ResolveReference resolves a URI reference to an absolute URI from -// an absolute base URI u, per RFC 3986 Section 5.2. The URI reference -// may be relative or absolute. ResolveReference always returns a new -// URL instance, even if the returned URL is identical to either the -// base or reference. If ref is an absolute URL, then ResolveReference -// ignores base and returns a copy of ref. -func (u *URL) ResolveReference(ref *URL) *URL { - url := *ref - if ref.Scheme == "" { - url.Scheme = u.Scheme - } - if ref.Scheme != "" || ref.Host != "" || ref.User != nil { - // The "absoluteURI" or "net_path" cases. - // We can ignore the error from setPath since we know we provided a - // validly-escaped path. - url.setPath(resolvePath(ref.EscapedPath(), "")) - return &url - } - if ref.Opaque != "" { - url.User = nil - url.Host = "" - url.Path = "" - return &url - } - if ref.Path == "" && !ref.ForceQuery && ref.RawQuery == "" { - url.RawQuery = u.RawQuery - if ref.Fragment == "" { - url.Fragment = u.Fragment - url.RawFragment = u.RawFragment - } - } - // The "abs_path" or "rel_path" cases. - url.Host = u.Host - url.User = u.User - url.setPath(resolvePath(u.EscapedPath(), ref.EscapedPath())) - return &url -} - -// Query parses RawQuery and returns the corresponding values. -// It silently discards malformed value pairs. -// To check errors use ParseQuery. -func (u *URL) Query() Values { - v, _ := ParseQuery(u.RawQuery) - return v -} - -// RequestURI returns the encoded path?query or opaque?query -// string that would be used in an HTTP request for u. -func (u *URL) RequestURI() string { - result := u.Opaque - if result == "" { - result = u.EscapedPath() - if result == "" { - result = "/" - } - } else { - if strings.HasPrefix(result, "//") { - result = u.Scheme + ":" + result - } - } - if u.ForceQuery || u.RawQuery != "" { - result += "?" + u.RawQuery - } - return result -} - -// Hostname returns u.Host, stripping any valid port number if present. -// -// If the result is enclosed in square brackets, as literal IPv6 addresses are, -// the square brackets are removed from the result. -func (u *URL) Hostname() string { - host, _ := splitHostPort(u.Host) - return host -} - -// Port returns the port part of u.Host, without the leading colon. -// -// If u.Host doesn't contain a valid numeric port, Port returns an empty string. -func (u *URL) Port() string { - _, port := splitHostPort(u.Host) - return port -} - -// splitHostPort separates host and port. If the port is not valid, it returns -// the entire input as host, and it doesn't check the validity of the host. -// Unlike net.SplitHostPort, but per RFC 3986, it requires ports to be numeric. -func splitHostPort(hostPort string) (host, port string) { - host = hostPort - - colon := strings.LastIndexByte(host, ':') - if colon != -1 && validOptionalPort(host[colon:]) { - host, port = host[:colon], host[colon+1:] - } - - if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") { - host = host[1 : len(host)-1] - } - - return -} - -// Marshaling interface implementations. -// Would like to implement MarshalText/UnmarshalText but that will change the JSON representation of URLs. - -func (u *URL) MarshalBinary() (text []byte, err error) { - return []byte(u.String()), nil -} - -func (u *URL) UnmarshalBinary(text []byte) error { - u1, err := Parse(string(text)) - if err != nil { - return err - } - *u = *u1 - return nil -} - -// JoinPath returns a new URL with the provided path elements joined to -// any existing path and the resulting path cleaned of any ./ or ../ elements. -// Any sequences of multiple / characters will be reduced to a single /. -func (u *URL) JoinPath(elem ...string) *URL { - elem = append([]string{u.EscapedPath()}, elem...) - var p string - if !strings.HasPrefix(elem[0], "/") { - // Return a relative path if u is relative, - // but ensure that it contains no ../ elements. - elem[0] = "/" + elem[0] - p = path.Join(elem...)[1:] - } else { - p = path.Join(elem...) - } - // path.Join will remove any trailing slashes. - // Preserve at least one. - if strings.HasSuffix(elem[len(elem)-1], "/") && !strings.HasSuffix(p, "/") { - p += "/" - } - url := *u - url.setPath(p) - return &url -} - -// validUserinfo reports whether s is a valid userinfo string per RFC 3986 -// Section 3.2.1: -// -// userinfo = *( unreserved / pct-encoded / sub-delims / ":" ) -// unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" -// sub-delims = "!" / "$" / "&" / "'" / "(" / ")" -// / "*" / "+" / "," / ";" / "=" -// -// It doesn't validate pct-encoded. The caller does that via func unescape. -func validUserinfo(s string) bool { - for _, r := range s { - if 'A' <= r && r <= 'Z' { - continue - } - if 'a' <= r && r <= 'z' { - continue - } - if '0' <= r && r <= '9' { - continue - } - switch r { - case '-', '.', '_', ':', '~', '!', '$', '&', '\'', - '(', ')', '*', '+', ',', ';', '=', '%', '@': - continue - default: - return false - } - } - return true -} - -// stringContainsCTLByte reports whether s contains any ASCII control character. -func stringContainsCTLByte(s string) bool { - for i := 0; i < len(s); i++ { - b := s[i] - if b < ' ' || b == 0x7f { - return true - } - } - return false -} - -// JoinPath returns a URL string with the provided path elements joined to -// the existing path of base and the resulting path cleaned of any ./ or ../ elements. -func JoinPath(base string, elem ...string) (result string, err error) { - url, err := Parse(base) - if err != nil { - return - } - result = url.JoinPath(elem...).String() - return -} diff --git a/core/version/version.go b/core/version/version.go index d1467c788..459a91ad3 100644 --- a/core/version/version.go +++ b/core/version/version.go @@ -1,5 +1,5 @@ + //====== THIS IS AUTOGENERATED FILE. DO NOT MODIFY ======== package version - -const VERSIONSTR = "v1.10.0-111-g6313cb8a" +const VERSIONSTR = "v1.10.0-100-gf600e64b" diff --git a/sdks/client.go b/sdks/client.go index 84af8b9c0..d5c4df2ff 100644 --- a/sdks/client.go +++ b/sdks/client.go @@ -2,12 +2,12 @@ package sdks import ( "net/http" + "net/url" "github.com/0chain/errors" "github.com/0chain/gosdk/constants" "github.com/0chain/gosdk/core/encryption" "github.com/0chain/gosdk/core/sys" - "github.com/0chain/gosdk/core/util" "github.com/0chain/gosdk/zboxcore/client" ) @@ -20,7 +20,7 @@ type Client struct { // create client instance func NewClient(clientID, clientPublicKey, baseURL string) (Client, error) { - u, err := util.Parse(baseURL) + u, err := url.Parse(baseURL) c := Client{ ClientID: clientID, diff --git a/zboxcore/sdk/networkworker.go b/zboxcore/sdk/networkworker.go index 04c5b40ba..276fca806 100644 --- a/zboxcore/sdk/networkworker.go +++ b/zboxcore/sdk/networkworker.go @@ -51,6 +51,7 @@ func UpdateNetworkDetails() error { l.Logger.Error("Failed to update network details ", zap.Error(err)) return err } + shouldUpdate := UpdateRequired(networkDetails) if shouldUpdate { forceUpdateNetworkDetails(networkDetails) @@ -86,9 +87,7 @@ func UpdateRequired(networkDetails *Network) bool { if len(miners) == 0 || len(sharders) == 0 { return true } - if len(networkDetails.Miners) == 0 || len(networkDetails.Sharders) == 0 { - return false - } + minerSame := reflect.DeepEqual(miners, networkDetails.Miners) sharderSame := reflect.DeepEqual(sharders, networkDetails.Sharders) diff --git a/zboxcore/zboxutil/http.go b/zboxcore/zboxutil/http.go index 4bdeb8bef..d4c2c7dd6 100644 --- a/zboxcore/zboxutil/http.go +++ b/zboxcore/zboxutil/http.go @@ -20,7 +20,6 @@ import ( "github.com/0chain/gosdk/core/conf" "github.com/0chain/gosdk/core/encryption" "github.com/0chain/gosdk/core/logger" - "github.com/0chain/gosdk/core/util" "github.com/0chain/gosdk/zboxcore/blockchain" "github.com/0chain/gosdk/zboxcore/client" ) @@ -802,8 +801,6 @@ func NewRollbackRequest(baseUrl, allocationID string, allocationTx string, body return req, nil } -var lock sync.Mutex - func MakeSCRestAPICall(scAddress string, relativePath string, params map[string]string, handler SCRestAPIHandler) ([]byte, error) { numSharders := len(blockchain.GetSharders()) sharders := blockchain.GetSharders() @@ -820,34 +817,23 @@ func MakeSCRestAPICall(scAddress string, relativePath string, params map[string] return nil, err } - urls := make(map[string]string) for _, sharder := range sharders { - lock.Lock() - - urlString := fmt.Sprintf("%v/%v%v%v", sharder, SC_REST_API_URL, scAddress, relativePath) - urlObj, err := util.Parse(urlString) - if err != nil { - log.Error(err) - continue - } - q := urlObj.Query() - for k, v := range params { - q.Add(k, v) - } - urlObj.RawQuery = q.Encode() - urls[sharder] = urlObj.String() - - lock.Unlock() - } - - for sharder, u := range urls { wg.Add(1) - go func(sharder, url string) { + go func(sharder string) { defer wg.Done() - + urlString := fmt.Sprintf("%v/%v%v%v", sharder, SC_REST_API_URL, scAddress, relativePath) + urlObj, err := url.Parse(urlString) + if err != nil { + log.Error(err) + return + } + q := urlObj.Query() + for k, v := range params { + q.Add(k, v) + } + urlObj.RawQuery = q.Encode() client := &http.Client{Transport: DefaultTransport} - - response, err := client.Get(url) + response, err := client.Get(urlObj.String()) if err != nil { blockchain.Sharders.Fail(sharder) return @@ -874,7 +860,7 @@ func MakeSCRestAPICall(scAddress string, relativePath string, params map[string] entityResult[sharder] = entityBytes blockchain.Sharders.Success(sharder) mu.Unlock() - }(sharder, u) + }(sharder) } wg.Wait() @@ -955,13 +941,9 @@ func isCurrentDominantStatus(respStatus int, currentTotalPerStatus map[int]int, return currentTotalPerStatus[respStatus] == currentMax && (respStatus == 200 || currentTotalPerStatus[200] < currentMax) } -func joinUrl(baseURl string, paths ...string) (*util.URL, error) { - lock.Lock() - defer lock.Unlock() - - u, err := util.Parse(baseURl) +func joinUrl(baseURl string, paths ...string) (*url.URL, error) { + u, err := url.Parse(baseURl) if err != nil { - log.Error(err) return nil, err } p := path.Join(paths...) diff --git a/zcnbridge/http/rest.go b/zcnbridge/http/rest.go index b88b4ce68..87bfee4f9 100644 --- a/zcnbridge/http/rest.go +++ b/zcnbridge/http/rest.go @@ -7,6 +7,7 @@ import ( "io" "io/ioutil" "net/http" + "net/url" "sync" "go.uber.org/zap" @@ -172,9 +173,9 @@ func extractSharders() []string { } // makeURL creates url.URL to make smart contract request to sharder. -func makeURL(params Params, baseURL, relativePath string) *util.URL { +func makeURL(params Params, baseURL, relativePath string) *url.URL { uString := fmt.Sprintf("%v/%v%v", baseURL, RestPrefix, relativePath) - u, _ := util.Parse(uString) + u, _ := url.Parse(uString) q := u.Query() for k, v := range params { q.Add(k, v) diff --git a/zcncore/networkworker.go b/zcncore/networkworker.go index 0644e45dd..e267c5f4a 100644 --- a/zcncore/networkworker.go +++ b/zcncore/networkworker.go @@ -82,9 +82,7 @@ func UpdateRequired(networkDetails *Network) bool { if len(miners) == 0 || len(sharders) == 0 { return true } - if len(networkDetails.Miners) == 0 || len(networkDetails.Sharders) == 0 { - return false - } + minerSame := reflect.DeepEqual(miners, networkDetails.Miners) sharderSame := reflect.DeepEqual(sharders, networkDetails.Sharders) diff --git a/zcncore/networkworker_mobile.go b/zcncore/networkworker_mobile.go index 7958ddabe..ca0863ff8 100644 --- a/zcncore/networkworker_mobile.go +++ b/zcncore/networkworker_mobile.go @@ -98,10 +98,6 @@ func UpdateRequired(networkDetails *Network) bool { return true } - if len(networkDetails.net.Miners) == 0 || len(networkDetails.net.Sharders) == 0 { - return false - } - minerSame := reflect.DeepEqual(miners, networkDetails.net.Miners) sharderSame := reflect.DeepEqual(sharders, networkDetails.net.Sharders) From 717dfe3952f1afdafcf2cb0d84073d7934078fea Mon Sep 17 00:00:00 2001 From: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Date: Fri, 17 Nov 2023 01:56:32 +0530 Subject: [PATCH 102/134] rmv channel hasher (#1285) --- zboxcore/sdk/chunked_upload_chunk_reader.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/zboxcore/sdk/chunked_upload_chunk_reader.go b/zboxcore/sdk/chunked_upload_chunk_reader.go index c54ba6408..00417a188 100644 --- a/zboxcore/sdk/chunked_upload_chunk_reader.go +++ b/zboxcore/sdk/chunked_upload_chunk_reader.go @@ -110,8 +110,8 @@ func createChunkReader(fileReader io.Reader, size, chunkSize int64, dataShards i } r.chunkDataSizePerRead = r.chunkDataSize * int64(dataShards) - r.hasherWG.Add(1) - go r.hashData() + // r.hasherWG.Add(1) + // go r.hashData() return r, nil } @@ -186,7 +186,7 @@ func (r *chunkedUploadChunkReader) Next() (*ChunkData, error) { if r.hasherError != nil { return chunk, r.hasherError } - r.hasherDataChan <- chunkBytes + _ = r.hasher.WriteToFile(chunkBytes) fragments, err := r.erasureEncoder.Split(chunkBytes) if err != nil { return nil, err From 69a53a3c392a28337ffacb92344e13d92bfb8d85 Mon Sep 17 00:00:00 2001 From: Jayash Satolia <73050737+Jayashsatolia403@users.noreply.github.com> Date: Fri, 17 Nov 2023 18:32:04 +0530 Subject: [PATCH 103/134] Fix submit txn (#1287) --- core/transaction/entity.go | 18 ++++++++++++++++-- zboxcore/sdk/sdk.go | 7 ++++++- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/core/transaction/entity.go b/core/transaction/entity.go index c123b5ec1..3f2a2879e 100644 --- a/core/transaction/entity.go +++ b/core/transaction/entity.go @@ -256,14 +256,28 @@ func (t *Transaction) VerifyTransaction(verifyHandler VerifyFunc) (bool, error) return verifyHandler(t.Signature, t.Hash, t.PublicKey) } -func SendTransactionSync(txn *Transaction, miners []string) { +func SendTransactionSync(txn *Transaction, miners []string) error { wg := sync.WaitGroup{} wg.Add(len(miners)) + + failureCount := 0 + for _, miner := range miners { url := fmt.Sprintf("%v/%v", miner, TXN_SUBMIT_URL) - go sendTransactionToURL(url, txn, &wg) //nolint + go func() { + _, err := sendTransactionToURL(url, txn, &wg) + if err != nil { + failureCount++ + } + }() //nolint } wg.Wait() + + if failureCount == len(miners) { + return errors.New("transaction_send_error", "failed to send transaction to all miners") + } + + return nil } func sendTransactionToURL(url string, txn *Transaction, wg *sync.WaitGroup) ([]byte, error) { diff --git a/zboxcore/sdk/sdk.go b/zboxcore/sdk/sdk.go index c4464e312..191f95077 100644 --- a/zboxcore/sdk/sdk.go +++ b/zboxcore/sdk/sdk.go @@ -1455,7 +1455,12 @@ func smartContractTxnValueFee(sn transaction.SmartContractTxnData, l.Logger.Info(msg) l.Logger.Info("estimated txn fee: ", txn.TransactionFee) - transaction.SendTransactionSync(txn, blockchain.GetMiners()) + err = transaction.SendTransactionSync(txn, blockchain.GetMiners()) + if err != nil { + l.Logger.Info("transaction submission failed", zap.Error(err)) + node.Cache.Evict(txn.ClientID) + return + } var ( querySleepTime = time.Duration(blockchain.GetQuerySleepTime()) * time.Second From 1dc0f7fa44755755ea1c003df1ebca53315507e5 Mon Sep 17 00:00:00 2001 From: Yaroslav Svitlytskyi <53532703+YarikRevich@users.noreply.github.com> Date: Sun, 19 Nov 2023 14:22:11 +0100 Subject: [PATCH 104/134] Feature: add BNT, USDC and EURC tokens for Swap (#1277) * feature: add multiple token support for swap * feature: add correct Bancor API calls * feature: added approve for swap of bancor token * fix: removed debug lines * fix: fixed swap approval * fix: fixed bug * fix: fixed bugs --- zcnbridge/bridge.go | 201 ++- zcnbridge/bridge_helper.go | 7 +- zcnbridge/bridge_test.go | 34 +- zcnbridge/config.go | 7 +- .../bancornetwork.go} | 34 +- zcnbridge/ethereum/bancortoken/bancortoken.go | 1556 +++++++++++++++++ .../{token/token.go => zcntoken/zcntoken.go} | 2 +- 7 files changed, 1745 insertions(+), 96 deletions(-) rename zcnbridge/ethereum/{bancor/bancor.go => bancornetwork/bancornetwork.go} (88%) create mode 100644 zcnbridge/ethereum/bancortoken/bancortoken.go rename zcnbridge/ethereum/{token/token.go => zcntoken/zcntoken.go} (99%) diff --git a/zcnbridge/bridge.go b/zcnbridge/bridge.go index 9bf79bf1a..9c9d9457b 100644 --- a/zcnbridge/bridge.go +++ b/zcnbridge/bridge.go @@ -5,14 +5,15 @@ import ( "encoding/hex" "encoding/json" "fmt" + "github.com/0chain/gosdk/zcnbridge/ethereum/bancortoken" "io" "math/big" "strconv" "time" "github.com/0chain/common/core/currency" - "github.com/0chain/gosdk/zcnbridge/ethereum/bancor" - "github.com/0chain/gosdk/zcnbridge/ethereum/token" + "github.com/0chain/gosdk/zcnbridge/ethereum/bancornetwork" + "github.com/0chain/gosdk/zcnbridge/ethereum/zcntoken" h "github.com/0chain/gosdk/zcnbridge/http" hdw "github.com/0chain/gosdk/zcncore/ethhdwallet" "github.com/spf13/viper" @@ -333,11 +334,11 @@ func (b *BridgeClient) NFTConfigGetAddress(ctx context.Context, key string) (str } // IncreaseBurnerAllowance Increases allowance for bridge contract address to transfer -// ERC-20 tokens on behalf of the token owner to the Burn TokenPool -// During the burn the script transfers amount from token owner to the bridge burn token pool +// ERC-20 tokens on behalf of the zcntoken owner to the Burn TokenPool +// During the burn the script transfers amount from zcntoken owner to the bridge burn zcntoken pool // Example: owner wants to burn some amount. // The contract will transfer some amount from owner address to the pool. -// So the owner must call IncreaseAllowance of the WZCN token with 2 parameters: +// So the owner must call IncreaseAllowance of the WZCN zcntoken with 2 parameters: // spender address which is the bridge contract and amount to be burned (transferred) // Token signature: "increaseApproval(address,uint256)" // @@ -357,12 +358,12 @@ func (b *BridgeClient) IncreaseBurnerAllowance(ctx context.Context, allowanceAmo tokenInstance, transactOpts, err := b.prepareToken(ctx, "increaseApproval", tokenAddress, spenderAddress, amount) if err != nil { - return nil, errors.Wrap(err, "failed to prepare token") + return nil, errors.Wrap(err, "failed to prepare zcntoken") } Logger.Info( "Starting IncreaseApproval", - zap.String("token", tokenAddress.String()), + zap.String("zcntoken", tokenAddress.String()), zap.String("spender", spenderAddress.String()), zap.Int64("amount", amount.Int64()), ) @@ -371,7 +372,7 @@ func (b *BridgeClient) IncreaseBurnerAllowance(ctx context.Context, allowanceAmo if err != nil { Logger.Error( "IncreaseApproval FAILED", - zap.String("token", tokenAddress.String()), + zap.String("zcntoken", tokenAddress.String()), zap.String("spender", spenderAddress.String()), zap.Int64("amount", amount.Int64()), zap.Error(err)) @@ -382,7 +383,7 @@ func (b *BridgeClient) IncreaseBurnerAllowance(ctx context.Context, allowanceAmo Logger.Info( "Posted IncreaseApproval", zap.String("hash", tran.Hash().String()), - zap.String("token", tokenAddress.String()), + zap.String("zcntoken", tokenAddress.String()), zap.String("spender", spenderAddress.String()), zap.Int64("amount", amount.Int64()), ) @@ -390,7 +391,7 @@ func (b *BridgeClient) IncreaseBurnerAllowance(ctx context.Context, allowanceAmo return tran, nil } -// GetTokenBalance returns balance of the current client for the token address +// GetTokenBalance returns balance of the current client for the zcntoken address func (b *BridgeClient) GetTokenBalance() (*big.Int, error) { // 1. Token address parameter of := common.HexToAddress(b.TokenAddress) @@ -398,9 +399,9 @@ func (b *BridgeClient) GetTokenBalance() (*big.Int, error) { // 2. User's Ethereum wallet address parameter from := common.HexToAddress(b.EthereumAddress) - tokenInstance, err := token.NewToken(of, b.ethereumClient) + tokenInstance, err := zcntoken.NewToken(of, b.ethereumClient) if err != nil { - return nil, errors.Wrap(err, "failed to initialize token instance") + return nil, errors.Wrap(err, "failed to initialize zcntoken instance") } wei, err := tokenInstance.BalanceOf(&bind.CallOpts{}, from) @@ -665,7 +666,7 @@ func (b *BridgeClient) BurnZCN(ctx context.Context, amount, txnfee uint64) (tran } // FetchZCNToETHRate retrieves latest ZCN to ETH rate using Bancor API -func (b *BridgeClient) FetchZCNToETHRate() (*big.Float, error) { +func (b *BridgeClient) FetchZCNToSourceTokenRate(sourceTokenAddress string) (*big.Float, error) { client = h.CleanClient() resp, err := client.Get(fmt.Sprintf("%s/tokens?dlt_id=%s", b.BancorAPIURL, b.TokenAddress)) @@ -685,17 +686,73 @@ func (b *BridgeClient) FetchZCNToETHRate() (*big.Float, error) { return nil, err } - var zcnEthRateFloat float64 - zcnEthRateFloat, err = strconv.ParseFloat(bancorTokenDetails.Data.Rate.ETH, 64) + var zcnSourceTokenRateFloat float64 + + switch sourceTokenAddress { + case SourceTokenETHAddress: + zcnSourceTokenRateFloat, err = strconv.ParseFloat(bancorTokenDetails.Data.Rate.ETH, 64) + case SourceTokenBNTAddress: + zcnSourceTokenRateFloat, err = strconv.ParseFloat(bancorTokenDetails.Data.Rate.BNT, 64) + case SourceTokenUSDCAddress: + zcnSourceTokenRateFloat, err = strconv.ParseFloat(bancorTokenDetails.Data.Rate.USDC, 64) + case SourceTokenEURCAddress: + zcnSourceTokenRateFloat, err = strconv.ParseFloat(bancorTokenDetails.Data.Rate.EURC, 64) + } + if err != nil { return nil, err } - return big.NewFloat(zcnEthRateFloat), nil + return big.NewFloat(zcnSourceTokenRateFloat), nil } -// Swap provides opportunity to perform token swap operation. -func (b *BridgeClient) Swap(ctx context.Context, amountSwap uint64, deadlinePeriod time.Time) (*types.Transaction, error) { +// GetMaxBancorTargetAmount retrieves max amount of a given source token for Bancor swap +func (b *BridgeClient) GetMaxBancorTargetAmount(sourceTokenAddress string, amountSwap uint64) (*big.Int, error) { + amountSwapZCN, err := currency.Coin(amountSwap).ToZCN() + if err != nil { + return nil, errors.Wrap(err, "failed to convert current zcntoken balance to ZCN") + } + + var zcnEthRate *big.Float + zcnEthRate, err = b.FetchZCNToSourceTokenRate(sourceTokenAddress) + if err != nil { + return nil, errors.Wrap(err, "failed to retrieve ZCN to source zcntoken rate using Bancor API") + } + + zcnEthRateFloat, _ := zcnEthRate.Float64() + + return big.NewInt(int64(amountSwapZCN * zcnEthRateFloat * 1.5 * 1e18)), nil +} + +// ApproveSwap provides opportunity to approve swap operation for ERC20 tokens +func (b *BridgeClient) ApproveSwap(ctx context.Context, sourceTokenAddress string, maxAmountSwap *big.Int) (*types.Transaction, error) { + // 1. Token source token address parameter + tokenAddress := common.HexToAddress(sourceTokenAddress) + + // 2. Spender source token address parameter + spender := common.HexToAddress(BancorNetworkAddress) + + bancorTokenInstance, transactOpts, err := b.prepareBancorToken(ctx, "approve", tokenAddress, spender, maxAmountSwap) + if err != nil { + return nil, errors.Wrap(err, "failed to prepare bancor token") + } + + Logger.Info( + "Starting ApproveSwap", + zap.Int64("amount", maxAmountSwap.Int64()), + zap.String("spender", spender.String()), + ) + + tran, err := bancorTokenInstance.Approve(transactOpts, spender, maxAmountSwap) + if err != nil { + return nil, errors.Wrap(err, "failed to execute Approve transaction") + } + + return tran, nil +} + +// Swap provides opportunity to perform zcntoken swap operation. +func (b *BridgeClient) Swap(ctx context.Context, sourceTokenAddress string, amountSwap uint64, maxAmountSwap *big.Int, deadlinePeriod time.Time) (*types.Transaction, error) { // 1. Swap amount parameter. amount := big.NewInt(int64(amountSwap)) @@ -705,54 +762,90 @@ func (b *BridgeClient) Swap(ctx context.Context, amountSwap uint64, deadlinePeri // 3. Trade deadline deadline := big.NewInt(deadlinePeriod.Unix()) - amountSwapZCN, err := currency.Coin(amountSwap).ToZCN() - if err != nil { - return nil, errors.Wrap(err, "failed to convert current token balance to ZCN") - } + // 4. Value of the Ethereum transaction + var value *big.Int - var zcnEthRate *big.Float - zcnEthRate, err = b.FetchZCNToETHRate() - if err != nil { - return nil, errors.Wrap(err, "failed to retrieve ZCN to ETH rate using Bancor API") + if sourceTokenAddress == SourceTokenETHAddress { + value = maxAmountSwap + } else { + value = big.NewInt(0) } - zcnEthRateFloat, _ := zcnEthRate.Float64() - - // 4. Max trade token amount - maxAmount := big.NewInt(int64(amountSwapZCN * zcnEthRateFloat * 1.5 * 1e18)) - - // 5. Source token address parameter - from := common.HexToAddress(SourceTokenAddress) + // 6. Source zcntoken address parameter + from := common.HexToAddress(sourceTokenAddress) - // 6. Target token address parameter + // 7. Target zcntoken address parameter to := common.HexToAddress(b.TokenAddress) - bancorInstance, transactOpts, err := b.prepareBancor(ctx, maxAmount, "tradeByTargetAmount", from, to, amount, maxAmount, deadline, beneficiary) + bancorInstance, transactOpts, err := b.prepareBancor(ctx, value, "tradeByTargetAmount", from, to, amount, maxAmountSwap, deadline, beneficiary) if err != nil { - return nil, errors.Wrap(err, "failed to prepare bancor") + return nil, errors.Wrap(err, "failed to prepare bancornetwork") } Logger.Info( "Starting Swap", zap.Int64("amount", amount.Int64()), - zap.String("sourceToken", SourceTokenAddress), + zap.String("sourceToken", sourceTokenAddress), ) - tran, err := bancorInstance.TradeByTargetAmount(transactOpts, from, to, amount, maxAmount, deadline, beneficiary) + tran, err := bancorInstance.TradeByTargetAmount(transactOpts, from, to, amount, maxAmountSwap, deadline, beneficiary) if err != nil { - return nil, errors.Wrap(err, "failed to execute ConvertByPath transaction") + return nil, errors.Wrap(err, "failed to execute TradeByTargetAmount transaction") } return tran, nil } -func (b *BridgeClient) prepareBancor(ctx context.Context, value *big.Int, method string, params ...interface{}) (*bancor.Bancor, *bind.TransactOpts, error) { +func (b *BridgeClient) prepareBancor(ctx context.Context, value *big.Int, method string, params ...interface{}) (*bancornetwork.Bancor, *bind.TransactOpts, error) { // 1. Bancor network smart contract address contractAddress := common.HexToAddress(BancorNetworkAddress) - abi, err := bancor.BancorMetaData.GetAbi() + abi, err := bancornetwork.BancorMetaData.GetAbi() if err != nil { - return nil, nil, errors.Wrap(err, "failed to get bancor abi") + return nil, nil, errors.Wrap(err, "failed to get bancornetwork abi") + } + + pack, err := abi.Pack(method, params...) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to pack arguments") + } + + from := common.HexToAddress(b.EthereumAddress) + + opts := eth.CallMsg{ + To: &contractAddress, + From: from, + Data: pack, + } + + if value.Int64() != 0 { + opts.Value = value + } + + gasLimitUnits, err := b.ethereumClient.EstimateGas(ctx, opts) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to estimate gas limit") + } + + gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() + + transactOpts := b.CreateSignedTransactionFromKeyStore(b.ethereumClient, gasLimitUnits) + if value.Int64() != 0 { + transactOpts.Value = value + } + + bancorInstance, err := bancornetwork.NewBancor(contractAddress, b.ethereumClient) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to initialize bancornetwork instance") + } + + return bancorInstance, transactOpts, nil +} + +func (b *BridgeClient) prepareBancorToken(ctx context.Context, method string, tokenAddress common.Address, params ...interface{}) (*bancortoken.Bancortoken, *bind.TransactOpts, error) { + abi, err := zcntoken.TokenMetaData.GetAbi() + if err != nil { + return nil, nil, errors.Wrap(err, "failed to get zcntoken abi") } pack, err := abi.Pack(method, params...) @@ -763,10 +856,9 @@ func (b *BridgeClient) prepareBancor(ctx context.Context, value *big.Int, method from := common.HexToAddress(b.EthereumAddress) gasLimitUnits, err := b.ethereumClient.EstimateGas(ctx, eth.CallMsg{ - To: &contractAddress, - From: from, - Data: pack, - Value: value, + To: &tokenAddress, + From: from, + Data: pack, }) if err != nil { return nil, nil, errors.Wrap(err, "failed to estimate gas limit") @@ -775,20 +867,19 @@ func (b *BridgeClient) prepareBancor(ctx context.Context, value *big.Int, method gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() transactOpts := b.CreateSignedTransactionFromKeyStore(b.ethereumClient, gasLimitUnits) - transactOpts.Value = value - bancorInstance, err := bancor.NewBancor(contractAddress, b.ethereumClient) + bancorTokenInstance, err := bancortoken.NewBancortoken(tokenAddress, b.ethereumClient) if err != nil { - return nil, nil, errors.Wrap(err, "failed to initialize bancor instance") + return nil, nil, errors.Wrap(err, "failed to initialize zcntoken instance") } - return bancorInstance, transactOpts, nil + return bancorTokenInstance, transactOpts, nil } -func (b *BridgeClient) prepareToken(ctx context.Context, method string, tokenAddress common.Address, params ...interface{}) (*token.Token, *bind.TransactOpts, error) { - abi, err := token.TokenMetaData.GetAbi() +func (b *BridgeClient) prepareToken(ctx context.Context, method string, tokenAddress common.Address, params ...interface{}) (*zcntoken.Token, *bind.TransactOpts, error) { + abi, err := zcntoken.TokenMetaData.GetAbi() if err != nil { - return nil, nil, errors.Wrap(err, "failed to get token abi") + return nil, nil, errors.Wrap(err, "failed to get zcntoken abi") } pack, err := abi.Pack(method, params...) @@ -811,9 +902,9 @@ func (b *BridgeClient) prepareToken(ctx context.Context, method string, tokenAdd transactOpts := b.CreateSignedTransactionFromKeyStore(b.ethereumClient, gasLimitUnits) - tokenInstance, err := token.NewToken(tokenAddress, b.ethereumClient) + tokenInstance, err := zcntoken.NewToken(tokenAddress, b.ethereumClient) if err != nil { - return nil, nil, errors.Wrap(err, "failed to initialize token instance") + return nil, nil, errors.Wrap(err, "failed to initialize zcntoken instance") } return tokenInstance, transactOpts, nil diff --git a/zcnbridge/bridge_helper.go b/zcnbridge/bridge_helper.go index d68b5a0b1..729fec2e2 100644 --- a/zcnbridge/bridge_helper.go +++ b/zcnbridge/bridge_helper.go @@ -10,11 +10,14 @@ import ( "github.com/pkg/errors" ) -// BancorTokenDetails describes Bancor ZCN token pool details +// BancorTokenDetails describes Bancor ZCN zcntoken pool details type BancorTokenDetails struct { Data struct { Rate struct { - ETH string `json:"eth"` + ETH string `json:"eth"` + BNT string `json:"bnt"` + USDC string `json:"usd"` + EURC string `json:"eur"` } } `json:"data"` } diff --git a/zcnbridge/bridge_test.go b/zcnbridge/bridge_test.go index 3890c777d..d2b8d4f13 100644 --- a/zcnbridge/bridge_test.go +++ b/zcnbridge/bridge_test.go @@ -4,9 +4,8 @@ import ( "context" "encoding/json" "fmt" - "github.com/0chain/common/core/currency" - "github.com/0chain/gosdk/zcnbridge/ethereum/bancor" - "github.com/0chain/gosdk/zcnbridge/ethereum/token" + "github.com/0chain/gosdk/zcnbridge/ethereum/bancornetwork" + "github.com/0chain/gosdk/zcnbridge/ethereum/zcntoken" "log" "math/big" "net/http" @@ -537,7 +536,7 @@ func Test_ZCNBridge(t *testing.T) { to := common.HexToAddress(tokenAddress) fromAddress := common.HexToAddress(ethereumAddress) - abi, err := token.TokenMetaData.GetAbi() + abi, err := zcntoken.TokenMetaData.GetAbi() require.NoError(t, err) pack, err := abi.Pack("increaseApproval", spenderAddress, big.NewInt(amount)) @@ -559,37 +558,34 @@ func Test_ZCNBridge(t *testing.T) { // 1. Predefined deadline period deadlinePeriod := time.Date(2009, 11, 17, 20, 34, 58, 651387237, time.UTC) - _, err := bridgeClient.Swap(context.Background(), amount, deadlinePeriod) + _, err := bridgeClient.Swap(context.Background(), SourceTokenETHAddress, amount, big.NewInt(amount), deadlinePeriod) require.NoError(t, err) - // 1. Trade deadline + // 2. Trade deadline deadline := big.NewInt(deadlinePeriod.Unix()) - // 2. Swap amount parameter - amount := big.NewInt(amount) + // 3. Swap amount parameter + swapAmount := big.NewInt(amount) - // 3. User's Ethereum wallet address. + // 4. User's Ethereum wallet address. beneficiary := common.HexToAddress(ethereumAddress) - // 4. Source token address parameter + // 5. Source zcntoken address parameter from := common.HexToAddress(sourceAddress) - // 5. Target token address parameter + // 6. Target zcntoken address parameter to := common.HexToAddress(tokenAddress) - amountZCN, err := currency.Coin(amount.Int64()).ToZCN() - require.NoError(t, err) - - // 6. Max trade token amount - maxAmount := big.NewInt(int64(amountZCN * 1.5 * 1e18)) + // 7. Max trade zcntoken amount + maxAmount := big.NewInt(amount) - // 7. Bancor network smart contract address + // 8. Bancor network smart contract address contractAddress := common.HexToAddress(BancorNetworkAddress) - abi, err := bancor.BancorMetaData.GetAbi() + abi, err := bancornetwork.BancorMetaData.GetAbi() require.NoError(t, err) - pack, err := abi.Pack("tradeByTargetAmount", from, to, amount, maxAmount, deadline, beneficiary) + pack, err := abi.Pack("tradeByTargetAmount", from, to, swapAmount, maxAmount, deadline, beneficiary) require.NoError(t, err) require.True(t, ethereumClient.AssertCalled( diff --git a/zcnbridge/config.go b/zcnbridge/config.go index 5ce608971..d871eb653 100644 --- a/zcnbridge/config.go +++ b/zcnbridge/config.go @@ -21,8 +21,11 @@ const ( ) const ( - BancorNetworkAddress = "0xeEF417e1D5CC832e619ae18D2F140De2999dD4fB" - SourceTokenAddress = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE" + BancorNetworkAddress = "0xeEF417e1D5CC832e619ae18D2F140De2999dD4fB" + SourceTokenETHAddress = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE" + SourceTokenUSDCAddress = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" + SourceTokenEURCAddress = "0x1aBaEA1f7C830bD89Acc67eC4af516284b1bC33c" + SourceTokenBNTAddress = "0x1f573d6fb3f13d689ff844b4ce37794d79a7ff1c" ) const BancorAPIURL = "https://api-v3.bancor.network" diff --git a/zcnbridge/ethereum/bancor/bancor.go b/zcnbridge/ethereum/bancornetwork/bancornetwork.go similarity index 88% rename from zcnbridge/ethereum/bancor/bancor.go rename to zcnbridge/ethereum/bancornetwork/bancornetwork.go index 75372aa43..6c432375d 100755 --- a/zcnbridge/ethereum/bancor/bancor.go +++ b/zcnbridge/ethereum/bancornetwork/bancornetwork.go @@ -1,7 +1,7 @@ // Code generated - DO NOT EDIT. // This file is a generated binding and any manual changes will be lost. -package bancor +package bancornetwork import ( "errors" @@ -31,7 +31,7 @@ var ( // BancorMetaData contains all meta data concerning the Bancor contract. var BancorMetaData = &bind.MetaData{ - ABI: "[{\"inputs\":[{\"internalType\":\"contractITokenGovernance\",\"name\":\"initBNTGovernance\",\"type\":\"address\"},{\"internalType\":\"contractITokenGovernance\",\"name\":\"initVBNTGovernance\",\"type\":\"address\"},{\"internalType\":\"contractINetworkSettings\",\"name\":\"initNetworkSettings\",\"type\":\"address\"},{\"internalType\":\"contractIMasterVault\",\"name\":\"initMasterVault\",\"type\":\"address\"},{\"internalType\":\"contractIExternalProtectionVault\",\"name\":\"initExternalProtectionVault\",\"type\":\"address\"},{\"internalType\":\"contractIPoolToken\",\"name\":\"initBNTPoolToken\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"bancorArbitrage\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"carbonPOL\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"inputs\":[],\"name\":\"AccessDenied\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"AlreadyExists\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"AlreadyInitialized\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"DeadlineExpired\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"DepositingDisabled\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"DoesNotExist\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InsufficientFlashLoanReturn\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidAddress\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidFee\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidPool\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidToken\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"NativeTokenAmountMismatch\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"NotEmpty\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"NotWhitelisted\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"NotWhitelistedForPOL\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"Overflow\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"PoolNotInSurplus\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"ZeroValue\",\"type\":\"error\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"contractToken\",\"name\":\"token\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"borrower\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"feeAmount\",\"type\":\"uint256\"}],\"name\":\"FlashLoanCompleted\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"contextId\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"contractToken\",\"name\":\"token\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"provider\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"availableAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"originalAmount\",\"type\":\"uint256\"}],\"name\":\"FundsMigrated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"caller\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"NetworkFeesWithdrawn\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint32\",\"name\":\"oldRewardsPPM\",\"type\":\"uint32\"},{\"indexed\":false,\"internalType\":\"uint32\",\"name\":\"newRewardsPPM\",\"type\":\"uint32\"}],\"name\":\"POLRewardsPPMUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"caller\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"polTokenAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"userReward\",\"type\":\"uint256\"}],\"name\":\"POLWithdrawn\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"Paused\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"contractToken\",\"name\":\"pool\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"contractIPoolCollection\",\"name\":\"poolCollection\",\"type\":\"address\"}],\"name\":\"PoolAdded\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"uint16\",\"name\":\"poolType\",\"type\":\"uint16\"},{\"indexed\":true,\"internalType\":\"contractIPoolCollection\",\"name\":\"poolCollection\",\"type\":\"address\"}],\"name\":\"PoolCollectionAdded\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"uint16\",\"name\":\"poolType\",\"type\":\"uint16\"},{\"indexed\":true,\"internalType\":\"contractIPoolCollection\",\"name\":\"poolCollection\",\"type\":\"address\"}],\"name\":\"PoolCollectionRemoved\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"contractToken\",\"name\":\"pool\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"contractIPoolCollection\",\"name\":\"poolCollection\",\"type\":\"address\"}],\"name\":\"PoolCreated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"contractToken\",\"name\":\"pool\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"contractIPoolCollection\",\"name\":\"poolCollection\",\"type\":\"address\"}],\"name\":\"PoolRemoved\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"previousAdminRole\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"newAdminRole\",\"type\":\"bytes32\"}],\"name\":\"RoleAdminChanged\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"}],\"name\":\"RoleGranted\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"}],\"name\":\"RoleRevoked\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"contextId\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"contractToken\",\"name\":\"sourceToken\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"contractToken\",\"name\":\"targetToken\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"sourceAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"targetAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"bntAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"targetFeeAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"bntFeeAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"trader\",\"type\":\"address\"}],\"name\":\"TokensTraded\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"Unpaused\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"DEFAULT_ADMIN_ROLE\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"id\",\"type\":\"uint256\"}],\"name\":\"cancelWithdrawal\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"pool\",\"type\":\"address\"}],\"name\":\"collectionByPool\",\"outputs\":[{\"internalType\":\"contractIPoolCollection\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken[]\",\"name\":\"tokens\",\"type\":\"address[]\"},{\"internalType\":\"contractIPoolCollection\",\"name\":\"poolCollection\",\"type\":\"address\"}],\"name\":\"createPools\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"pool\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenAmount\",\"type\":\"uint256\"}],\"name\":\"deposit\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"provider\",\"type\":\"address\"},{\"internalType\":\"contractToken\",\"name\":\"pool\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenAmount\",\"type\":\"uint256\"}],\"name\":\"depositFor\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"depositingEnabled\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bool\",\"name\":\"status\",\"type\":\"bool\"}],\"name\":\"enableDepositing\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"internalType\":\"contractIFlashLoanRecipient\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"flashLoan\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"}],\"name\":\"getRoleAdmin\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"uint256\",\"name\":\"index\",\"type\":\"uint256\"}],\"name\":\"getRoleMember\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"}],\"name\":\"getRoleMemberCount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"grantRole\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"hasRole\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractIPoolToken\",\"name\":\"poolToken\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"poolTokenAmount\",\"type\":\"uint256\"}],\"name\":\"initWithdrawal\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractIBNTPool\",\"name\":\"initBNTPool\",\"type\":\"address\"},{\"internalType\":\"contractIPendingWithdrawals\",\"name\":\"initPendingWithdrawals\",\"type\":\"address\"},{\"internalType\":\"contractIPoolMigrator\",\"name\":\"initPoolMigrator\",\"type\":\"address\"}],\"name\":\"initialize\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"liquidityPools\",\"outputs\":[{\"internalType\":\"contractToken[]\",\"name\":\"\",\"type\":\"address[]\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"provider\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"availableAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"originalAmount\",\"type\":\"uint256\"}],\"name\":\"migrateLiquidity\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken[]\",\"name\":\"pools\",\"type\":\"address[]\"},{\"internalType\":\"contractIPoolCollection\",\"name\":\"newPoolCollection\",\"type\":\"address\"}],\"name\":\"migratePools\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"pause\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"paused\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"pendingNetworkFeeAmount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"polRewardsPPM\",\"outputs\":[{\"internalType\":\"uint32\",\"name\":\"\",\"type\":\"uint32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"poolCollections\",\"outputs\":[{\"internalType\":\"contractIPoolCollection[]\",\"name\":\"\",\"type\":\"address[]\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"postUpgrade\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractIPoolCollection\",\"name\":\"newPoolCollection\",\"type\":\"address\"}],\"name\":\"registerPoolCollection\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"renounceRole\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"resume\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"revokeRole\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"roleAdmin\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"roleEmergencyStopper\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"roleMigrationManager\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"roleNetworkFeeManager\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint32\",\"name\":\"newRewardsPPM\",\"type\":\"uint32\"}],\"name\":\"setPOLRewardsPPM\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes4\",\"name\":\"interfaceId\",\"type\":\"bytes4\"}],\"name\":\"supportsInterface\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"sourceToken\",\"type\":\"address\"},{\"internalType\":\"contractToken\",\"name\":\"targetToken\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"sourceAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"minReturnAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"beneficiary\",\"type\":\"address\"}],\"name\":\"tradeBySourceAmount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"sourceToken\",\"type\":\"address\"},{\"internalType\":\"contractToken\",\"name\":\"targetToken\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"sourceAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"minReturnAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"beneficiary\",\"type\":\"address\"}],\"name\":\"tradeBySourceAmountArb\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"sourceToken\",\"type\":\"address\"},{\"internalType\":\"contractToken\",\"name\":\"targetToken\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"targetAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"maxSourceAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"beneficiary\",\"type\":\"address\"}],\"name\":\"tradeByTargetAmount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"sourceToken\",\"type\":\"address\"},{\"internalType\":\"contractToken\",\"name\":\"targetToken\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"targetAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"maxSourceAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"beneficiary\",\"type\":\"address\"}],\"name\":\"tradeByTargetAmountArb\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractIPoolCollection\",\"name\":\"poolCollection\",\"type\":\"address\"}],\"name\":\"unregisterPoolCollection\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"version\",\"outputs\":[{\"internalType\":\"uint16\",\"name\":\"\",\"type\":\"uint16\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"id\",\"type\":\"uint256\"}],\"name\":\"withdraw\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"}],\"name\":\"withdrawNetworkFees\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"pool\",\"type\":\"address\"}],\"name\":\"withdrawPOL\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"stateMutability\":\"payable\",\"type\":\"receive\"}]", + ABI: "[{\"inputs\":[{\"internalType\":\"contractITokenGovernance\",\"name\":\"initBNTGovernance\",\"type\":\"address\"},{\"internalType\":\"contractITokenGovernance\",\"name\":\"initVBNTGovernance\",\"type\":\"address\"},{\"internalType\":\"contractINetworkSettings\",\"name\":\"initNetworkSettings\",\"type\":\"address\"},{\"internalType\":\"contractIMasterVault\",\"name\":\"initMasterVault\",\"type\":\"address\"},{\"internalType\":\"contractIExternalProtectionVault\",\"name\":\"initExternalProtectionVault\",\"type\":\"address\"},{\"internalType\":\"contractIPoolToken\",\"name\":\"initBNTPoolToken\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"bancorArbitrage\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"carbonPOL\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"inputs\":[],\"name\":\"AccessDenied\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"AlreadyExists\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"AlreadyInitialized\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"DeadlineExpired\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"DepositingDisabled\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"DoesNotExist\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InsufficientFlashLoanReturn\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidAddress\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidFee\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidPool\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidToken\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"NativeTokenAmountMismatch\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"NotEmpty\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"NotWhitelisted\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"NotWhitelistedForPOL\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"Overflow\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"PoolNotInSurplus\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"ZeroValue\",\"type\":\"error\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"contractToken\",\"name\":\"zcntoken\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"borrower\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"feeAmount\",\"type\":\"uint256\"}],\"name\":\"FlashLoanCompleted\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"contextId\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"contractToken\",\"name\":\"zcntoken\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"provider\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"availableAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"originalAmount\",\"type\":\"uint256\"}],\"name\":\"FundsMigrated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"caller\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"NetworkFeesWithdrawn\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint32\",\"name\":\"oldRewardsPPM\",\"type\":\"uint32\"},{\"indexed\":false,\"internalType\":\"uint32\",\"name\":\"newRewardsPPM\",\"type\":\"uint32\"}],\"name\":\"POLRewardsPPMUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"caller\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"zcntoken\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"polTokenAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"userReward\",\"type\":\"uint256\"}],\"name\":\"POLWithdrawn\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"Paused\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"contractToken\",\"name\":\"pool\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"contractIPoolCollection\",\"name\":\"poolCollection\",\"type\":\"address\"}],\"name\":\"PoolAdded\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"uint16\",\"name\":\"poolType\",\"type\":\"uint16\"},{\"indexed\":true,\"internalType\":\"contractIPoolCollection\",\"name\":\"poolCollection\",\"type\":\"address\"}],\"name\":\"PoolCollectionAdded\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"uint16\",\"name\":\"poolType\",\"type\":\"uint16\"},{\"indexed\":true,\"internalType\":\"contractIPoolCollection\",\"name\":\"poolCollection\",\"type\":\"address\"}],\"name\":\"PoolCollectionRemoved\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"contractToken\",\"name\":\"pool\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"contractIPoolCollection\",\"name\":\"poolCollection\",\"type\":\"address\"}],\"name\":\"PoolCreated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"contractToken\",\"name\":\"pool\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"contractIPoolCollection\",\"name\":\"poolCollection\",\"type\":\"address\"}],\"name\":\"PoolRemoved\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"previousAdminRole\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"newAdminRole\",\"type\":\"bytes32\"}],\"name\":\"RoleAdminChanged\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"}],\"name\":\"RoleGranted\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"}],\"name\":\"RoleRevoked\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"contextId\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"contractToken\",\"name\":\"sourceToken\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"contractToken\",\"name\":\"targetToken\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"sourceAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"targetAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"bntAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"targetFeeAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"bntFeeAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"trader\",\"type\":\"address\"}],\"name\":\"TokensTraded\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"Unpaused\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"DEFAULT_ADMIN_ROLE\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"id\",\"type\":\"uint256\"}],\"name\":\"cancelWithdrawal\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"pool\",\"type\":\"address\"}],\"name\":\"collectionByPool\",\"outputs\":[{\"internalType\":\"contractIPoolCollection\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken[]\",\"name\":\"tokens\",\"type\":\"address[]\"},{\"internalType\":\"contractIPoolCollection\",\"name\":\"poolCollection\",\"type\":\"address\"}],\"name\":\"createPools\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"pool\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenAmount\",\"type\":\"uint256\"}],\"name\":\"deposit\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"provider\",\"type\":\"address\"},{\"internalType\":\"contractToken\",\"name\":\"pool\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenAmount\",\"type\":\"uint256\"}],\"name\":\"depositFor\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"depositingEnabled\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bool\",\"name\":\"status\",\"type\":\"bool\"}],\"name\":\"enableDepositing\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"zcntoken\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"internalType\":\"contractIFlashLoanRecipient\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"flashLoan\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"}],\"name\":\"getRoleAdmin\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"uint256\",\"name\":\"index\",\"type\":\"uint256\"}],\"name\":\"getRoleMember\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"}],\"name\":\"getRoleMemberCount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"grantRole\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"hasRole\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractIPoolToken\",\"name\":\"poolToken\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"poolTokenAmount\",\"type\":\"uint256\"}],\"name\":\"initWithdrawal\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractIBNTPool\",\"name\":\"initBNTPool\",\"type\":\"address\"},{\"internalType\":\"contractIPendingWithdrawals\",\"name\":\"initPendingWithdrawals\",\"type\":\"address\"},{\"internalType\":\"contractIPoolMigrator\",\"name\":\"initPoolMigrator\",\"type\":\"address\"}],\"name\":\"initialize\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"liquidityPools\",\"outputs\":[{\"internalType\":\"contractToken[]\",\"name\":\"\",\"type\":\"address[]\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"zcntoken\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"provider\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"availableAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"originalAmount\",\"type\":\"uint256\"}],\"name\":\"migrateLiquidity\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken[]\",\"name\":\"pools\",\"type\":\"address[]\"},{\"internalType\":\"contractIPoolCollection\",\"name\":\"newPoolCollection\",\"type\":\"address\"}],\"name\":\"migratePools\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"pause\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"paused\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"pendingNetworkFeeAmount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"polRewardsPPM\",\"outputs\":[{\"internalType\":\"uint32\",\"name\":\"\",\"type\":\"uint32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"poolCollections\",\"outputs\":[{\"internalType\":\"contractIPoolCollection[]\",\"name\":\"\",\"type\":\"address[]\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"postUpgrade\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractIPoolCollection\",\"name\":\"newPoolCollection\",\"type\":\"address\"}],\"name\":\"registerPoolCollection\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"renounceRole\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"resume\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"revokeRole\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"roleAdmin\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"roleEmergencyStopper\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"roleMigrationManager\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"roleNetworkFeeManager\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint32\",\"name\":\"newRewardsPPM\",\"type\":\"uint32\"}],\"name\":\"setPOLRewardsPPM\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes4\",\"name\":\"interfaceId\",\"type\":\"bytes4\"}],\"name\":\"supportsInterface\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"sourceToken\",\"type\":\"address\"},{\"internalType\":\"contractToken\",\"name\":\"targetToken\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"sourceAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"minReturnAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"beneficiary\",\"type\":\"address\"}],\"name\":\"tradeBySourceAmount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"sourceToken\",\"type\":\"address\"},{\"internalType\":\"contractToken\",\"name\":\"targetToken\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"sourceAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"minReturnAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"beneficiary\",\"type\":\"address\"}],\"name\":\"tradeBySourceAmountArb\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"sourceToken\",\"type\":\"address\"},{\"internalType\":\"contractToken\",\"name\":\"targetToken\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"targetAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"maxSourceAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"beneficiary\",\"type\":\"address\"}],\"name\":\"tradeByTargetAmount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"sourceToken\",\"type\":\"address\"},{\"internalType\":\"contractToken\",\"name\":\"targetToken\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"targetAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"maxSourceAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"beneficiary\",\"type\":\"address\"}],\"name\":\"tradeByTargetAmountArb\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractIPoolCollection\",\"name\":\"poolCollection\",\"type\":\"address\"}],\"name\":\"unregisterPoolCollection\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"version\",\"outputs\":[{\"internalType\":\"uint16\",\"name\":\"\",\"type\":\"uint16\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"id\",\"type\":\"uint256\"}],\"name\":\"withdraw\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"}],\"name\":\"withdrawNetworkFees\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"pool\",\"type\":\"address\"}],\"name\":\"withdrawPOL\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"stateMutability\":\"payable\",\"type\":\"receive\"}]", } // BancorABI is the input ABI used to generate the binding from. @@ -845,21 +845,21 @@ func (_Bancor *BancorTransactorSession) EnableDepositing(status bool) (*types.Tr // FlashLoan is a paid mutator transaction binding the contract method 0xadf51de1. // -// Solidity: function flashLoan(address token, uint256 amount, address recipient, bytes data) returns() +// Solidity: function flashLoan(address zcntoken, uint256 amount, address recipient, bytes data) returns() func (_Bancor *BancorTransactor) FlashLoan(opts *bind.TransactOpts, token common.Address, amount *big.Int, recipient common.Address, data []byte) (*types.Transaction, error) { return _Bancor.contract.Transact(opts, "flashLoan", token, amount, recipient, data) } // FlashLoan is a paid mutator transaction binding the contract method 0xadf51de1. // -// Solidity: function flashLoan(address token, uint256 amount, address recipient, bytes data) returns() +// Solidity: function flashLoan(address zcntoken, uint256 amount, address recipient, bytes data) returns() func (_Bancor *BancorSession) FlashLoan(token common.Address, amount *big.Int, recipient common.Address, data []byte) (*types.Transaction, error) { return _Bancor.Contract.FlashLoan(&_Bancor.TransactOpts, token, amount, recipient, data) } // FlashLoan is a paid mutator transaction binding the contract method 0xadf51de1. // -// Solidity: function flashLoan(address token, uint256 amount, address recipient, bytes data) returns() +// Solidity: function flashLoan(address zcntoken, uint256 amount, address recipient, bytes data) returns() func (_Bancor *BancorTransactorSession) FlashLoan(token common.Address, amount *big.Int, recipient common.Address, data []byte) (*types.Transaction, error) { return _Bancor.Contract.FlashLoan(&_Bancor.TransactOpts, token, amount, recipient, data) } @@ -929,21 +929,21 @@ func (_Bancor *BancorTransactorSession) Initialize(initBNTPool common.Address, i // MigrateLiquidity is a paid mutator transaction binding the contract method 0x3d1c24e7. // -// Solidity: function migrateLiquidity(address token, address provider, uint256 amount, uint256 availableAmount, uint256 originalAmount) payable returns() +// Solidity: function migrateLiquidity(address zcntoken, address provider, uint256 amount, uint256 availableAmount, uint256 originalAmount) payable returns() func (_Bancor *BancorTransactor) MigrateLiquidity(opts *bind.TransactOpts, token common.Address, provider common.Address, amount *big.Int, availableAmount *big.Int, originalAmount *big.Int) (*types.Transaction, error) { return _Bancor.contract.Transact(opts, "migrateLiquidity", token, provider, amount, availableAmount, originalAmount) } // MigrateLiquidity is a paid mutator transaction binding the contract method 0x3d1c24e7. // -// Solidity: function migrateLiquidity(address token, address provider, uint256 amount, uint256 availableAmount, uint256 originalAmount) payable returns() +// Solidity: function migrateLiquidity(address zcntoken, address provider, uint256 amount, uint256 availableAmount, uint256 originalAmount) payable returns() func (_Bancor *BancorSession) MigrateLiquidity(token common.Address, provider common.Address, amount *big.Int, availableAmount *big.Int, originalAmount *big.Int) (*types.Transaction, error) { return _Bancor.Contract.MigrateLiquidity(&_Bancor.TransactOpts, token, provider, amount, availableAmount, originalAmount) } // MigrateLiquidity is a paid mutator transaction binding the contract method 0x3d1c24e7. // -// Solidity: function migrateLiquidity(address token, address provider, uint256 amount, uint256 availableAmount, uint256 originalAmount) payable returns() +// Solidity: function migrateLiquidity(address zcntoken, address provider, uint256 amount, uint256 availableAmount, uint256 originalAmount) payable returns() func (_Bancor *BancorTransactorSession) MigrateLiquidity(token common.Address, provider common.Address, amount *big.Int, availableAmount *big.Int, originalAmount *big.Int) (*types.Transaction, error) { return _Bancor.Contract.MigrateLiquidity(&_Bancor.TransactOpts, token, provider, amount, availableAmount, originalAmount) } @@ -1383,7 +1383,7 @@ type BancorFlashLoanCompleted struct { // FilterFlashLoanCompleted is a free log retrieval operation binding the contract event 0x0da3485ef1bb570df7bb888887eae5aa01d81b83cd8ccc80c0ea0922a677ecef. // -// Solidity: event FlashLoanCompleted(address indexed token, address indexed borrower, uint256 amount, uint256 feeAmount) +// Solidity: event FlashLoanCompleted(address indexed zcntoken, address indexed borrower, uint256 amount, uint256 feeAmount) func (_Bancor *BancorFilterer) FilterFlashLoanCompleted(opts *bind.FilterOpts, token []common.Address, borrower []common.Address) (*BancorFlashLoanCompletedIterator, error) { var tokenRule []interface{} @@ -1404,7 +1404,7 @@ func (_Bancor *BancorFilterer) FilterFlashLoanCompleted(opts *bind.FilterOpts, t // WatchFlashLoanCompleted is a free log subscription operation binding the contract event 0x0da3485ef1bb570df7bb888887eae5aa01d81b83cd8ccc80c0ea0922a677ecef. // -// Solidity: event FlashLoanCompleted(address indexed token, address indexed borrower, uint256 amount, uint256 feeAmount) +// Solidity: event FlashLoanCompleted(address indexed zcntoken, address indexed borrower, uint256 amount, uint256 feeAmount) func (_Bancor *BancorFilterer) WatchFlashLoanCompleted(opts *bind.WatchOpts, sink chan<- *BancorFlashLoanCompleted, token []common.Address, borrower []common.Address) (event.Subscription, error) { var tokenRule []interface{} @@ -1450,7 +1450,7 @@ func (_Bancor *BancorFilterer) WatchFlashLoanCompleted(opts *bind.WatchOpts, sin // ParseFlashLoanCompleted is a log parse operation binding the contract event 0x0da3485ef1bb570df7bb888887eae5aa01d81b83cd8ccc80c0ea0922a677ecef. // -// Solidity: event FlashLoanCompleted(address indexed token, address indexed borrower, uint256 amount, uint256 feeAmount) +// Solidity: event FlashLoanCompleted(address indexed zcntoken, address indexed borrower, uint256 amount, uint256 feeAmount) func (_Bancor *BancorFilterer) ParseFlashLoanCompleted(log types.Log) (*BancorFlashLoanCompleted, error) { event := new(BancorFlashLoanCompleted) if err := _Bancor.contract.UnpackLog(event, "FlashLoanCompleted", log); err != nil { @@ -1540,7 +1540,7 @@ type BancorFundsMigrated struct { // FilterFundsMigrated is a free log retrieval operation binding the contract event 0x102bce4e43a6a8cf0306fde6154221c1f5460f64ba63b92b156bce998ef0db56. // -// Solidity: event FundsMigrated(bytes32 indexed contextId, address indexed token, address indexed provider, uint256 amount, uint256 availableAmount, uint256 originalAmount) +// Solidity: event FundsMigrated(bytes32 indexed contextId, address indexed zcntoken, address indexed provider, uint256 amount, uint256 availableAmount, uint256 originalAmount) func (_Bancor *BancorFilterer) FilterFundsMigrated(opts *bind.FilterOpts, contextId [][32]byte, token []common.Address, provider []common.Address) (*BancorFundsMigratedIterator, error) { var contextIdRule []interface{} @@ -1565,7 +1565,7 @@ func (_Bancor *BancorFilterer) FilterFundsMigrated(opts *bind.FilterOpts, contex // WatchFundsMigrated is a free log subscription operation binding the contract event 0x102bce4e43a6a8cf0306fde6154221c1f5460f64ba63b92b156bce998ef0db56. // -// Solidity: event FundsMigrated(bytes32 indexed contextId, address indexed token, address indexed provider, uint256 amount, uint256 availableAmount, uint256 originalAmount) +// Solidity: event FundsMigrated(bytes32 indexed contextId, address indexed zcntoken, address indexed provider, uint256 amount, uint256 availableAmount, uint256 originalAmount) func (_Bancor *BancorFilterer) WatchFundsMigrated(opts *bind.WatchOpts, sink chan<- *BancorFundsMigrated, contextId [][32]byte, token []common.Address, provider []common.Address) (event.Subscription, error) { var contextIdRule []interface{} @@ -1615,7 +1615,7 @@ func (_Bancor *BancorFilterer) WatchFundsMigrated(opts *bind.WatchOpts, sink cha // ParseFundsMigrated is a log parse operation binding the contract event 0x102bce4e43a6a8cf0306fde6154221c1f5460f64ba63b92b156bce998ef0db56. // -// Solidity: event FundsMigrated(bytes32 indexed contextId, address indexed token, address indexed provider, uint256 amount, uint256 availableAmount, uint256 originalAmount) +// Solidity: event FundsMigrated(bytes32 indexed contextId, address indexed zcntoken, address indexed provider, uint256 amount, uint256 availableAmount, uint256 originalAmount) func (_Bancor *BancorFilterer) ParseFundsMigrated(log types.Log) (*BancorFundsMigrated, error) { event := new(BancorFundsMigrated) if err := _Bancor.contract.UnpackLog(event, "FundsMigrated", log); err != nil { @@ -1992,7 +1992,7 @@ type BancorPOLWithdrawn struct { // FilterPOLWithdrawn is a free log retrieval operation binding the contract event 0x5ad7a2184454b6259cd118e4041a953dc9d6498302bbe528e4f967bed9197129. // -// Solidity: event POLWithdrawn(address indexed caller, address indexed token, uint256 polTokenAmount, uint256 userReward) +// Solidity: event POLWithdrawn(address indexed caller, address indexed zcntoken, uint256 polTokenAmount, uint256 userReward) func (_Bancor *BancorFilterer) FilterPOLWithdrawn(opts *bind.FilterOpts, caller []common.Address, token []common.Address) (*BancorPOLWithdrawnIterator, error) { var callerRule []interface{} @@ -2013,7 +2013,7 @@ func (_Bancor *BancorFilterer) FilterPOLWithdrawn(opts *bind.FilterOpts, caller // WatchPOLWithdrawn is a free log subscription operation binding the contract event 0x5ad7a2184454b6259cd118e4041a953dc9d6498302bbe528e4f967bed9197129. // -// Solidity: event POLWithdrawn(address indexed caller, address indexed token, uint256 polTokenAmount, uint256 userReward) +// Solidity: event POLWithdrawn(address indexed caller, address indexed zcntoken, uint256 polTokenAmount, uint256 userReward) func (_Bancor *BancorFilterer) WatchPOLWithdrawn(opts *bind.WatchOpts, sink chan<- *BancorPOLWithdrawn, caller []common.Address, token []common.Address) (event.Subscription, error) { var callerRule []interface{} @@ -2059,7 +2059,7 @@ func (_Bancor *BancorFilterer) WatchPOLWithdrawn(opts *bind.WatchOpts, sink chan // ParsePOLWithdrawn is a log parse operation binding the contract event 0x5ad7a2184454b6259cd118e4041a953dc9d6498302bbe528e4f967bed9197129. // -// Solidity: event POLWithdrawn(address indexed caller, address indexed token, uint256 polTokenAmount, uint256 userReward) +// Solidity: event POLWithdrawn(address indexed caller, address indexed zcntoken, uint256 polTokenAmount, uint256 userReward) func (_Bancor *BancorFilterer) ParsePOLWithdrawn(log types.Log) (*BancorPOLWithdrawn, error) { event := new(BancorPOLWithdrawn) if err := _Bancor.contract.UnpackLog(event, "POLWithdrawn", log); err != nil { diff --git a/zcnbridge/ethereum/bancortoken/bancortoken.go b/zcnbridge/ethereum/bancortoken/bancortoken.go new file mode 100644 index 000000000..f07d2c95d --- /dev/null +++ b/zcnbridge/ethereum/bancortoken/bancortoken.go @@ -0,0 +1,1556 @@ +// Code generated - DO NOT EDIT. +// This file is a generated binding and any manual changes will be lost. + +package bancortoken + +import ( + "errors" + "math/big" + "strings" + + ethereum "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/event" +) + +// Reference imports to suppress errors if they are not otherwise used. +var ( + _ = errors.New + _ = big.NewInt + _ = strings.NewReader + _ = ethereum.NotFound + _ = bind.Bind + _ = common.Big1 + _ = types.BloomLookup + _ = event.NewSubscription + _ = abi.ConvertType +) + +// BancortokenMetaData contains all meta data concerning the Bancortoken contract. +var BancortokenMetaData = &bind.MetaData{ + ABI: "[{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_disable\",\"type\":\"bool\"}],\"name\":\"disableTransfers\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"version\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"standard\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_token\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_amount\",\"type\":\"uint256\"}],\"name\":\"withdrawTokens\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"acceptOwnership\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_amount\",\"type\":\"uint256\"}],\"name\":\"issue\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_amount\",\"type\":\"uint256\"}],\"name\":\"destroy\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"transfersEnabled\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"newOwner\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"},{\"name\":\"\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"_name\",\"type\":\"string\"},{\"name\":\"_symbol\",\"type\":\"string\"},{\"name\":\"_decimals\",\"type\":\"uint8\"}],\"payable\":false,\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"_token\",\"type\":\"address\"}],\"name\":\"NewSmartToken\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"_amount\",\"type\":\"uint256\"}],\"name\":\"Issuance\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"_amount\",\"type\":\"uint256\"}],\"name\":\"Destruction\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"_prevOwner\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_newOwner\",\"type\":\"address\"}],\"name\":\"OwnerUpdate\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_spender\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"}]", +} + +// BancortokenABI is the input ABI used to generate the binding from. +// Deprecated: Use BancortokenMetaData.ABI instead. +var BancortokenABI = BancortokenMetaData.ABI + +// Bancortoken is an auto generated Go binding around an Ethereum contract. +type Bancortoken struct { + BancortokenCaller // Read-only binding to the contract + BancortokenTransactor // Write-only binding to the contract + BancortokenFilterer // Log filterer for contract events +} + +// BancortokenCaller is an auto generated read-only Go binding around an Ethereum contract. +type BancortokenCaller struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// BancortokenTransactor is an auto generated write-only Go binding around an Ethereum contract. +type BancortokenTransactor struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// BancortokenFilterer is an auto generated log filtering Go binding around an Ethereum contract events. +type BancortokenFilterer struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// BancortokenSession is an auto generated Go binding around an Ethereum contract, +// with pre-set call and transact options. +type BancortokenSession struct { + Contract *Bancortoken // Generic contract binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// BancortokenCallerSession is an auto generated read-only Go binding around an Ethereum contract, +// with pre-set call options. +type BancortokenCallerSession struct { + Contract *BancortokenCaller // Generic contract caller binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session +} + +// BancortokenTransactorSession is an auto generated write-only Go binding around an Ethereum contract, +// with pre-set transact options. +type BancortokenTransactorSession struct { + Contract *BancortokenTransactor // Generic contract transactor binding to set the session for + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// BancortokenRaw is an auto generated low-level Go binding around an Ethereum contract. +type BancortokenRaw struct { + Contract *Bancortoken // Generic contract binding to access the raw methods on +} + +// BancortokenCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. +type BancortokenCallerRaw struct { + Contract *BancortokenCaller // Generic read-only contract binding to access the raw methods on +} + +// BancortokenTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. +type BancortokenTransactorRaw struct { + Contract *BancortokenTransactor // Generic write-only contract binding to access the raw methods on +} + +// NewBancortoken creates a new instance of Bancortoken, bound to a specific deployed contract. +func NewBancortoken(address common.Address, backend bind.ContractBackend) (*Bancortoken, error) { + contract, err := bindBancortoken(address, backend, backend, backend) + if err != nil { + return nil, err + } + return &Bancortoken{BancortokenCaller: BancortokenCaller{contract: contract}, BancortokenTransactor: BancortokenTransactor{contract: contract}, BancortokenFilterer: BancortokenFilterer{contract: contract}}, nil +} + +// NewBancortokenCaller creates a new read-only instance of Bancortoken, bound to a specific deployed contract. +func NewBancortokenCaller(address common.Address, caller bind.ContractCaller) (*BancortokenCaller, error) { + contract, err := bindBancortoken(address, caller, nil, nil) + if err != nil { + return nil, err + } + return &BancortokenCaller{contract: contract}, nil +} + +// NewBancortokenTransactor creates a new write-only instance of Bancortoken, bound to a specific deployed contract. +func NewBancortokenTransactor(address common.Address, transactor bind.ContractTransactor) (*BancortokenTransactor, error) { + contract, err := bindBancortoken(address, nil, transactor, nil) + if err != nil { + return nil, err + } + return &BancortokenTransactor{contract: contract}, nil +} + +// NewBancortokenFilterer creates a new log filterer instance of Bancortoken, bound to a specific deployed contract. +func NewBancortokenFilterer(address common.Address, filterer bind.ContractFilterer) (*BancortokenFilterer, error) { + contract, err := bindBancortoken(address, nil, nil, filterer) + if err != nil { + return nil, err + } + return &BancortokenFilterer{contract: contract}, nil +} + +// bindBancortoken binds a generic wrapper to an already deployed contract. +func bindBancortoken(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { + parsed, err := BancortokenMetaData.GetAbi() + if err != nil { + return nil, err + } + return bind.NewBoundContract(address, *parsed, caller, transactor, filterer), nil +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_Bancortoken *BancortokenRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _Bancortoken.Contract.BancortokenCaller.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_Bancortoken *BancortokenRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Bancortoken.Contract.BancortokenTransactor.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_Bancortoken *BancortokenRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _Bancortoken.Contract.BancortokenTransactor.contract.Transact(opts, method, params...) +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_Bancortoken *BancortokenCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _Bancortoken.Contract.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_Bancortoken *BancortokenTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Bancortoken.Contract.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_Bancortoken *BancortokenTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _Bancortoken.Contract.contract.Transact(opts, method, params...) +} + +// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. +// +// Solidity: function allowance(address , address ) returns(uint256) +func (_Bancortoken *BancortokenCaller) Allowance(opts *bind.CallOpts, arg0 common.Address, arg1 common.Address) (*big.Int, error) { + var out []interface{} + err := _Bancortoken.contract.Call(opts, &out, "allowance", arg0, arg1) + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. +// +// Solidity: function allowance(address , address ) returns(uint256) +func (_Bancortoken *BancortokenSession) Allowance(arg0 common.Address, arg1 common.Address) (*big.Int, error) { + return _Bancortoken.Contract.Allowance(&_Bancortoken.CallOpts, arg0, arg1) +} + +// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. +// +// Solidity: function allowance(address , address ) returns(uint256) +func (_Bancortoken *BancortokenCallerSession) Allowance(arg0 common.Address, arg1 common.Address) (*big.Int, error) { + return _Bancortoken.Contract.Allowance(&_Bancortoken.CallOpts, arg0, arg1) +} + +// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. +// +// Solidity: function balanceOf(address ) returns(uint256) +func (_Bancortoken *BancortokenCaller) BalanceOf(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) { + var out []interface{} + err := _Bancortoken.contract.Call(opts, &out, "balanceOf", arg0) + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. +// +// Solidity: function balanceOf(address ) returns(uint256) +func (_Bancortoken *BancortokenSession) BalanceOf(arg0 common.Address) (*big.Int, error) { + return _Bancortoken.Contract.BalanceOf(&_Bancortoken.CallOpts, arg0) +} + +// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. +// +// Solidity: function balanceOf(address ) returns(uint256) +func (_Bancortoken *BancortokenCallerSession) BalanceOf(arg0 common.Address) (*big.Int, error) { + return _Bancortoken.Contract.BalanceOf(&_Bancortoken.CallOpts, arg0) +} + +// Decimals is a free data retrieval call binding the contract method 0x313ce567. +// +// Solidity: function decimals() returns(uint8) +func (_Bancortoken *BancortokenCaller) Decimals(opts *bind.CallOpts) (uint8, error) { + var out []interface{} + err := _Bancortoken.contract.Call(opts, &out, "decimals") + + if err != nil { + return *new(uint8), err + } + + out0 := *abi.ConvertType(out[0], new(uint8)).(*uint8) + + return out0, err + +} + +// Decimals is a free data retrieval call binding the contract method 0x313ce567. +// +// Solidity: function decimals() returns(uint8) +func (_Bancortoken *BancortokenSession) Decimals() (uint8, error) { + return _Bancortoken.Contract.Decimals(&_Bancortoken.CallOpts) +} + +// Decimals is a free data retrieval call binding the contract method 0x313ce567. +// +// Solidity: function decimals() returns(uint8) +func (_Bancortoken *BancortokenCallerSession) Decimals() (uint8, error) { + return _Bancortoken.Contract.Decimals(&_Bancortoken.CallOpts) +} + +// Name is a free data retrieval call binding the contract method 0x06fdde03. +// +// Solidity: function name() returns(string) +func (_Bancortoken *BancortokenCaller) Name(opts *bind.CallOpts) (string, error) { + var out []interface{} + err := _Bancortoken.contract.Call(opts, &out, "name") + + if err != nil { + return *new(string), err + } + + out0 := *abi.ConvertType(out[0], new(string)).(*string) + + return out0, err + +} + +// Name is a free data retrieval call binding the contract method 0x06fdde03. +// +// Solidity: function name() returns(string) +func (_Bancortoken *BancortokenSession) Name() (string, error) { + return _Bancortoken.Contract.Name(&_Bancortoken.CallOpts) +} + +// Name is a free data retrieval call binding the contract method 0x06fdde03. +// +// Solidity: function name() returns(string) +func (_Bancortoken *BancortokenCallerSession) Name() (string, error) { + return _Bancortoken.Contract.Name(&_Bancortoken.CallOpts) +} + +// NewOwner is a free data retrieval call binding the contract method 0xd4ee1d90. +// +// Solidity: function newOwner() returns(address) +func (_Bancortoken *BancortokenCaller) NewOwner(opts *bind.CallOpts) (common.Address, error) { + var out []interface{} + err := _Bancortoken.contract.Call(opts, &out, "newOwner") + + if err != nil { + return *new(common.Address), err + } + + out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) + + return out0, err + +} + +// NewOwner is a free data retrieval call binding the contract method 0xd4ee1d90. +// +// Solidity: function newOwner() returns(address) +func (_Bancortoken *BancortokenSession) NewOwner() (common.Address, error) { + return _Bancortoken.Contract.NewOwner(&_Bancortoken.CallOpts) +} + +// NewOwner is a free data retrieval call binding the contract method 0xd4ee1d90. +// +// Solidity: function newOwner() returns(address) +func (_Bancortoken *BancortokenCallerSession) NewOwner() (common.Address, error) { + return _Bancortoken.Contract.NewOwner(&_Bancortoken.CallOpts) +} + +// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. +// +// Solidity: function owner() returns(address) +func (_Bancortoken *BancortokenCaller) Owner(opts *bind.CallOpts) (common.Address, error) { + var out []interface{} + err := _Bancortoken.contract.Call(opts, &out, "owner") + + if err != nil { + return *new(common.Address), err + } + + out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) + + return out0, err + +} + +// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. +// +// Solidity: function owner() returns(address) +func (_Bancortoken *BancortokenSession) Owner() (common.Address, error) { + return _Bancortoken.Contract.Owner(&_Bancortoken.CallOpts) +} + +// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. +// +// Solidity: function owner() returns(address) +func (_Bancortoken *BancortokenCallerSession) Owner() (common.Address, error) { + return _Bancortoken.Contract.Owner(&_Bancortoken.CallOpts) +} + +// Standard is a free data retrieval call binding the contract method 0x5a3b7e42. +// +// Solidity: function standard() returns(string) +func (_Bancortoken *BancortokenCaller) Standard(opts *bind.CallOpts) (string, error) { + var out []interface{} + err := _Bancortoken.contract.Call(opts, &out, "standard") + + if err != nil { + return *new(string), err + } + + out0 := *abi.ConvertType(out[0], new(string)).(*string) + + return out0, err + +} + +// Standard is a free data retrieval call binding the contract method 0x5a3b7e42. +// +// Solidity: function standard() returns(string) +func (_Bancortoken *BancortokenSession) Standard() (string, error) { + return _Bancortoken.Contract.Standard(&_Bancortoken.CallOpts) +} + +// Standard is a free data retrieval call binding the contract method 0x5a3b7e42. +// +// Solidity: function standard() returns(string) +func (_Bancortoken *BancortokenCallerSession) Standard() (string, error) { + return _Bancortoken.Contract.Standard(&_Bancortoken.CallOpts) +} + +// Symbol is a free data retrieval call binding the contract method 0x95d89b41. +// +// Solidity: function symbol() returns(string) +func (_Bancortoken *BancortokenCaller) Symbol(opts *bind.CallOpts) (string, error) { + var out []interface{} + err := _Bancortoken.contract.Call(opts, &out, "symbol") + + if err != nil { + return *new(string), err + } + + out0 := *abi.ConvertType(out[0], new(string)).(*string) + + return out0, err + +} + +// Symbol is a free data retrieval call binding the contract method 0x95d89b41. +// +// Solidity: function symbol() returns(string) +func (_Bancortoken *BancortokenSession) Symbol() (string, error) { + return _Bancortoken.Contract.Symbol(&_Bancortoken.CallOpts) +} + +// Symbol is a free data retrieval call binding the contract method 0x95d89b41. +// +// Solidity: function symbol() returns(string) +func (_Bancortoken *BancortokenCallerSession) Symbol() (string, error) { + return _Bancortoken.Contract.Symbol(&_Bancortoken.CallOpts) +} + +// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. +// +// Solidity: function totalSupply() returns(uint256) +func (_Bancortoken *BancortokenCaller) TotalSupply(opts *bind.CallOpts) (*big.Int, error) { + var out []interface{} + err := _Bancortoken.contract.Call(opts, &out, "totalSupply") + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. +// +// Solidity: function totalSupply() returns(uint256) +func (_Bancortoken *BancortokenSession) TotalSupply() (*big.Int, error) { + return _Bancortoken.Contract.TotalSupply(&_Bancortoken.CallOpts) +} + +// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. +// +// Solidity: function totalSupply() returns(uint256) +func (_Bancortoken *BancortokenCallerSession) TotalSupply() (*big.Int, error) { + return _Bancortoken.Contract.TotalSupply(&_Bancortoken.CallOpts) +} + +// TransfersEnabled is a free data retrieval call binding the contract method 0xbef97c87. +// +// Solidity: function transfersEnabled() returns(bool) +func (_Bancortoken *BancortokenCaller) TransfersEnabled(opts *bind.CallOpts) (bool, error) { + var out []interface{} + err := _Bancortoken.contract.Call(opts, &out, "transfersEnabled") + + if err != nil { + return *new(bool), err + } + + out0 := *abi.ConvertType(out[0], new(bool)).(*bool) + + return out0, err + +} + +// TransfersEnabled is a free data retrieval call binding the contract method 0xbef97c87. +// +// Solidity: function transfersEnabled() returns(bool) +func (_Bancortoken *BancortokenSession) TransfersEnabled() (bool, error) { + return _Bancortoken.Contract.TransfersEnabled(&_Bancortoken.CallOpts) +} + +// TransfersEnabled is a free data retrieval call binding the contract method 0xbef97c87. +// +// Solidity: function transfersEnabled() returns(bool) +func (_Bancortoken *BancortokenCallerSession) TransfersEnabled() (bool, error) { + return _Bancortoken.Contract.TransfersEnabled(&_Bancortoken.CallOpts) +} + +// Version is a free data retrieval call binding the contract method 0x54fd4d50. +// +// Solidity: function version() returns(string) +func (_Bancortoken *BancortokenCaller) Version(opts *bind.CallOpts) (string, error) { + var out []interface{} + err := _Bancortoken.contract.Call(opts, &out, "version") + + if err != nil { + return *new(string), err + } + + out0 := *abi.ConvertType(out[0], new(string)).(*string) + + return out0, err + +} + +// Version is a free data retrieval call binding the contract method 0x54fd4d50. +// +// Solidity: function version() returns(string) +func (_Bancortoken *BancortokenSession) Version() (string, error) { + return _Bancortoken.Contract.Version(&_Bancortoken.CallOpts) +} + +// Version is a free data retrieval call binding the contract method 0x54fd4d50. +// +// Solidity: function version() returns(string) +func (_Bancortoken *BancortokenCallerSession) Version() (string, error) { + return _Bancortoken.Contract.Version(&_Bancortoken.CallOpts) +} + +// AcceptOwnership is a paid mutator transaction binding the contract method 0x79ba5097. +// +// Solidity: function acceptOwnership() returns() +func (_Bancortoken *BancortokenTransactor) AcceptOwnership(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Bancortoken.contract.Transact(opts, "acceptOwnership") +} + +// AcceptOwnership is a paid mutator transaction binding the contract method 0x79ba5097. +// +// Solidity: function acceptOwnership() returns() +func (_Bancortoken *BancortokenSession) AcceptOwnership() (*types.Transaction, error) { + return _Bancortoken.Contract.AcceptOwnership(&_Bancortoken.TransactOpts) +} + +// AcceptOwnership is a paid mutator transaction binding the contract method 0x79ba5097. +// +// Solidity: function acceptOwnership() returns() +func (_Bancortoken *BancortokenTransactorSession) AcceptOwnership() (*types.Transaction, error) { + return _Bancortoken.Contract.AcceptOwnership(&_Bancortoken.TransactOpts) +} + +// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. +// +// Solidity: function approve(address _spender, uint256 _value) returns(bool success) +func (_Bancortoken *BancortokenTransactor) Approve(opts *bind.TransactOpts, _spender common.Address, _value *big.Int) (*types.Transaction, error) { + return _Bancortoken.contract.Transact(opts, "approve", _spender, _value) +} + +// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. +// +// Solidity: function approve(address _spender, uint256 _value) returns(bool success) +func (_Bancortoken *BancortokenSession) Approve(_spender common.Address, _value *big.Int) (*types.Transaction, error) { + return _Bancortoken.Contract.Approve(&_Bancortoken.TransactOpts, _spender, _value) +} + +// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. +// +// Solidity: function approve(address _spender, uint256 _value) returns(bool success) +func (_Bancortoken *BancortokenTransactorSession) Approve(_spender common.Address, _value *big.Int) (*types.Transaction, error) { + return _Bancortoken.Contract.Approve(&_Bancortoken.TransactOpts, _spender, _value) +} + +// Destroy is a paid mutator transaction binding the contract method 0xa24835d1. +// +// Solidity: function destroy(address _from, uint256 _amount) returns() +func (_Bancortoken *BancortokenTransactor) Destroy(opts *bind.TransactOpts, _from common.Address, _amount *big.Int) (*types.Transaction, error) { + return _Bancortoken.contract.Transact(opts, "destroy", _from, _amount) +} + +// Destroy is a paid mutator transaction binding the contract method 0xa24835d1. +// +// Solidity: function destroy(address _from, uint256 _amount) returns() +func (_Bancortoken *BancortokenSession) Destroy(_from common.Address, _amount *big.Int) (*types.Transaction, error) { + return _Bancortoken.Contract.Destroy(&_Bancortoken.TransactOpts, _from, _amount) +} + +// Destroy is a paid mutator transaction binding the contract method 0xa24835d1. +// +// Solidity: function destroy(address _from, uint256 _amount) returns() +func (_Bancortoken *BancortokenTransactorSession) Destroy(_from common.Address, _amount *big.Int) (*types.Transaction, error) { + return _Bancortoken.Contract.Destroy(&_Bancortoken.TransactOpts, _from, _amount) +} + +// DisableTransfers is a paid mutator transaction binding the contract method 0x1608f18f. +// +// Solidity: function disableTransfers(bool _disable) returns() +func (_Bancortoken *BancortokenTransactor) DisableTransfers(opts *bind.TransactOpts, _disable bool) (*types.Transaction, error) { + return _Bancortoken.contract.Transact(opts, "disableTransfers", _disable) +} + +// DisableTransfers is a paid mutator transaction binding the contract method 0x1608f18f. +// +// Solidity: function disableTransfers(bool _disable) returns() +func (_Bancortoken *BancortokenSession) DisableTransfers(_disable bool) (*types.Transaction, error) { + return _Bancortoken.Contract.DisableTransfers(&_Bancortoken.TransactOpts, _disable) +} + +// DisableTransfers is a paid mutator transaction binding the contract method 0x1608f18f. +// +// Solidity: function disableTransfers(bool _disable) returns() +func (_Bancortoken *BancortokenTransactorSession) DisableTransfers(_disable bool) (*types.Transaction, error) { + return _Bancortoken.Contract.DisableTransfers(&_Bancortoken.TransactOpts, _disable) +} + +// Issue is a paid mutator transaction binding the contract method 0x867904b4. +// +// Solidity: function issue(address _to, uint256 _amount) returns() +func (_Bancortoken *BancortokenTransactor) Issue(opts *bind.TransactOpts, _to common.Address, _amount *big.Int) (*types.Transaction, error) { + return _Bancortoken.contract.Transact(opts, "issue", _to, _amount) +} + +// Issue is a paid mutator transaction binding the contract method 0x867904b4. +// +// Solidity: function issue(address _to, uint256 _amount) returns() +func (_Bancortoken *BancortokenSession) Issue(_to common.Address, _amount *big.Int) (*types.Transaction, error) { + return _Bancortoken.Contract.Issue(&_Bancortoken.TransactOpts, _to, _amount) +} + +// Issue is a paid mutator transaction binding the contract method 0x867904b4. +// +// Solidity: function issue(address _to, uint256 _amount) returns() +func (_Bancortoken *BancortokenTransactorSession) Issue(_to common.Address, _amount *big.Int) (*types.Transaction, error) { + return _Bancortoken.Contract.Issue(&_Bancortoken.TransactOpts, _to, _amount) +} + +// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. +// +// Solidity: function transfer(address _to, uint256 _value) returns(bool success) +func (_Bancortoken *BancortokenTransactor) Transfer(opts *bind.TransactOpts, _to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Bancortoken.contract.Transact(opts, "transfer", _to, _value) +} + +// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. +// +// Solidity: function transfer(address _to, uint256 _value) returns(bool success) +func (_Bancortoken *BancortokenSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Bancortoken.Contract.Transfer(&_Bancortoken.TransactOpts, _to, _value) +} + +// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. +// +// Solidity: function transfer(address _to, uint256 _value) returns(bool success) +func (_Bancortoken *BancortokenTransactorSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Bancortoken.Contract.Transfer(&_Bancortoken.TransactOpts, _to, _value) +} + +// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. +// +// Solidity: function transferFrom(address _from, address _to, uint256 _value) returns(bool success) +func (_Bancortoken *BancortokenTransactor) TransferFrom(opts *bind.TransactOpts, _from common.Address, _to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Bancortoken.contract.Transact(opts, "transferFrom", _from, _to, _value) +} + +// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. +// +// Solidity: function transferFrom(address _from, address _to, uint256 _value) returns(bool success) +func (_Bancortoken *BancortokenSession) TransferFrom(_from common.Address, _to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Bancortoken.Contract.TransferFrom(&_Bancortoken.TransactOpts, _from, _to, _value) +} + +// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. +// +// Solidity: function transferFrom(address _from, address _to, uint256 _value) returns(bool success) +func (_Bancortoken *BancortokenTransactorSession) TransferFrom(_from common.Address, _to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Bancortoken.Contract.TransferFrom(&_Bancortoken.TransactOpts, _from, _to, _value) +} + +// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. +// +// Solidity: function transferOwnership(address _newOwner) returns() +func (_Bancortoken *BancortokenTransactor) TransferOwnership(opts *bind.TransactOpts, _newOwner common.Address) (*types.Transaction, error) { + return _Bancortoken.contract.Transact(opts, "transferOwnership", _newOwner) +} + +// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. +// +// Solidity: function transferOwnership(address _newOwner) returns() +func (_Bancortoken *BancortokenSession) TransferOwnership(_newOwner common.Address) (*types.Transaction, error) { + return _Bancortoken.Contract.TransferOwnership(&_Bancortoken.TransactOpts, _newOwner) +} + +// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. +// +// Solidity: function transferOwnership(address _newOwner) returns() +func (_Bancortoken *BancortokenTransactorSession) TransferOwnership(_newOwner common.Address) (*types.Transaction, error) { + return _Bancortoken.Contract.TransferOwnership(&_Bancortoken.TransactOpts, _newOwner) +} + +// WithdrawTokens is a paid mutator transaction binding the contract method 0x5e35359e. +// +// Solidity: function withdrawTokens(address _token, address _to, uint256 _amount) returns() +func (_Bancortoken *BancortokenTransactor) WithdrawTokens(opts *bind.TransactOpts, _token common.Address, _to common.Address, _amount *big.Int) (*types.Transaction, error) { + return _Bancortoken.contract.Transact(opts, "withdrawTokens", _token, _to, _amount) +} + +// WithdrawTokens is a paid mutator transaction binding the contract method 0x5e35359e. +// +// Solidity: function withdrawTokens(address _token, address _to, uint256 _amount) returns() +func (_Bancortoken *BancortokenSession) WithdrawTokens(_token common.Address, _to common.Address, _amount *big.Int) (*types.Transaction, error) { + return _Bancortoken.Contract.WithdrawTokens(&_Bancortoken.TransactOpts, _token, _to, _amount) +} + +// WithdrawTokens is a paid mutator transaction binding the contract method 0x5e35359e. +// +// Solidity: function withdrawTokens(address _token, address _to, uint256 _amount) returns() +func (_Bancortoken *BancortokenTransactorSession) WithdrawTokens(_token common.Address, _to common.Address, _amount *big.Int) (*types.Transaction, error) { + return _Bancortoken.Contract.WithdrawTokens(&_Bancortoken.TransactOpts, _token, _to, _amount) +} + +// BancortokenApprovalIterator is returned from FilterApproval and is used to iterate over the raw logs and unpacked data for Approval events raised by the Bancortoken contract. +type BancortokenApprovalIterator struct { + Event *BancortokenApproval // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancortokenApprovalIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancortokenApproval) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancortokenApproval) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancortokenApprovalIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancortokenApprovalIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancortokenApproval represents a Approval event raised by the Bancortoken contract. +type BancortokenApproval struct { + Owner common.Address + Spender common.Address + Value *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterApproval is a free log retrieval operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. +// +// Solidity: event Approval(address indexed _owner, address indexed _spender, uint256 _value) +func (_Bancortoken *BancortokenFilterer) FilterApproval(opts *bind.FilterOpts, _owner []common.Address, _spender []common.Address) (*BancortokenApprovalIterator, error) { + + var _ownerRule []interface{} + for _, _ownerItem := range _owner { + _ownerRule = append(_ownerRule, _ownerItem) + } + var _spenderRule []interface{} + for _, _spenderItem := range _spender { + _spenderRule = append(_spenderRule, _spenderItem) + } + + logs, sub, err := _Bancortoken.contract.FilterLogs(opts, "Approval", _ownerRule, _spenderRule) + if err != nil { + return nil, err + } + return &BancortokenApprovalIterator{contract: _Bancortoken.contract, event: "Approval", logs: logs, sub: sub}, nil +} + +// WatchApproval is a free log subscription operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. +// +// Solidity: event Approval(address indexed _owner, address indexed _spender, uint256 _value) +func (_Bancortoken *BancortokenFilterer) WatchApproval(opts *bind.WatchOpts, sink chan<- *BancortokenApproval, _owner []common.Address, _spender []common.Address) (event.Subscription, error) { + + var _ownerRule []interface{} + for _, _ownerItem := range _owner { + _ownerRule = append(_ownerRule, _ownerItem) + } + var _spenderRule []interface{} + for _, _spenderItem := range _spender { + _spenderRule = append(_spenderRule, _spenderItem) + } + + logs, sub, err := _Bancortoken.contract.WatchLogs(opts, "Approval", _ownerRule, _spenderRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancortokenApproval) + if err := _Bancortoken.contract.UnpackLog(event, "Approval", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseApproval is a log parse operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. +// +// Solidity: event Approval(address indexed _owner, address indexed _spender, uint256 _value) +func (_Bancortoken *BancortokenFilterer) ParseApproval(log types.Log) (*BancortokenApproval, error) { + event := new(BancortokenApproval) + if err := _Bancortoken.contract.UnpackLog(event, "Approval", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancortokenDestructionIterator is returned from FilterDestruction and is used to iterate over the raw logs and unpacked data for Destruction events raised by the Bancortoken contract. +type BancortokenDestructionIterator struct { + Event *BancortokenDestruction // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancortokenDestructionIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancortokenDestruction) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancortokenDestruction) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancortokenDestructionIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancortokenDestructionIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancortokenDestruction represents a Destruction event raised by the Bancortoken contract. +type BancortokenDestruction struct { + Amount *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterDestruction is a free log retrieval operation binding the contract event 0x9a1b418bc061a5d80270261562e6986a35d995f8051145f277be16103abd3453. +// +// Solidity: event Destruction(uint256 _amount) +func (_Bancortoken *BancortokenFilterer) FilterDestruction(opts *bind.FilterOpts) (*BancortokenDestructionIterator, error) { + + logs, sub, err := _Bancortoken.contract.FilterLogs(opts, "Destruction") + if err != nil { + return nil, err + } + return &BancortokenDestructionIterator{contract: _Bancortoken.contract, event: "Destruction", logs: logs, sub: sub}, nil +} + +// WatchDestruction is a free log subscription operation binding the contract event 0x9a1b418bc061a5d80270261562e6986a35d995f8051145f277be16103abd3453. +// +// Solidity: event Destruction(uint256 _amount) +func (_Bancortoken *BancortokenFilterer) WatchDestruction(opts *bind.WatchOpts, sink chan<- *BancortokenDestruction) (event.Subscription, error) { + + logs, sub, err := _Bancortoken.contract.WatchLogs(opts, "Destruction") + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancortokenDestruction) + if err := _Bancortoken.contract.UnpackLog(event, "Destruction", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseDestruction is a log parse operation binding the contract event 0x9a1b418bc061a5d80270261562e6986a35d995f8051145f277be16103abd3453. +// +// Solidity: event Destruction(uint256 _amount) +func (_Bancortoken *BancortokenFilterer) ParseDestruction(log types.Log) (*BancortokenDestruction, error) { + event := new(BancortokenDestruction) + if err := _Bancortoken.contract.UnpackLog(event, "Destruction", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancortokenIssuanceIterator is returned from FilterIssuance and is used to iterate over the raw logs and unpacked data for Issuance events raised by the Bancortoken contract. +type BancortokenIssuanceIterator struct { + Event *BancortokenIssuance // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancortokenIssuanceIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancortokenIssuance) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancortokenIssuance) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancortokenIssuanceIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancortokenIssuanceIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancortokenIssuance represents a Issuance event raised by the Bancortoken contract. +type BancortokenIssuance struct { + Amount *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterIssuance is a free log retrieval operation binding the contract event 0x9386c90217c323f58030f9dadcbc938f807a940f4ff41cd4cead9562f5da7dc3. +// +// Solidity: event Issuance(uint256 _amount) +func (_Bancortoken *BancortokenFilterer) FilterIssuance(opts *bind.FilterOpts) (*BancortokenIssuanceIterator, error) { + + logs, sub, err := _Bancortoken.contract.FilterLogs(opts, "Issuance") + if err != nil { + return nil, err + } + return &BancortokenIssuanceIterator{contract: _Bancortoken.contract, event: "Issuance", logs: logs, sub: sub}, nil +} + +// WatchIssuance is a free log subscription operation binding the contract event 0x9386c90217c323f58030f9dadcbc938f807a940f4ff41cd4cead9562f5da7dc3. +// +// Solidity: event Issuance(uint256 _amount) +func (_Bancortoken *BancortokenFilterer) WatchIssuance(opts *bind.WatchOpts, sink chan<- *BancortokenIssuance) (event.Subscription, error) { + + logs, sub, err := _Bancortoken.contract.WatchLogs(opts, "Issuance") + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancortokenIssuance) + if err := _Bancortoken.contract.UnpackLog(event, "Issuance", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseIssuance is a log parse operation binding the contract event 0x9386c90217c323f58030f9dadcbc938f807a940f4ff41cd4cead9562f5da7dc3. +// +// Solidity: event Issuance(uint256 _amount) +func (_Bancortoken *BancortokenFilterer) ParseIssuance(log types.Log) (*BancortokenIssuance, error) { + event := new(BancortokenIssuance) + if err := _Bancortoken.contract.UnpackLog(event, "Issuance", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancortokenNewSmartTokenIterator is returned from FilterNewSmartToken and is used to iterate over the raw logs and unpacked data for NewSmartToken events raised by the Bancortoken contract. +type BancortokenNewSmartTokenIterator struct { + Event *BancortokenNewSmartToken // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancortokenNewSmartTokenIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancortokenNewSmartToken) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancortokenNewSmartToken) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancortokenNewSmartTokenIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancortokenNewSmartTokenIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancortokenNewSmartToken represents a NewSmartToken event raised by the Bancortoken contract. +type BancortokenNewSmartToken struct { + Token common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterNewSmartToken is a free log retrieval operation binding the contract event 0xf4cd1f8571e8d9c97ffcb81558807ab73f9803d54de5da6a0420593c82a4a9f0. +// +// Solidity: event NewSmartToken(address _token) +func (_Bancortoken *BancortokenFilterer) FilterNewSmartToken(opts *bind.FilterOpts) (*BancortokenNewSmartTokenIterator, error) { + + logs, sub, err := _Bancortoken.contract.FilterLogs(opts, "NewSmartToken") + if err != nil { + return nil, err + } + return &BancortokenNewSmartTokenIterator{contract: _Bancortoken.contract, event: "NewSmartToken", logs: logs, sub: sub}, nil +} + +// WatchNewSmartToken is a free log subscription operation binding the contract event 0xf4cd1f8571e8d9c97ffcb81558807ab73f9803d54de5da6a0420593c82a4a9f0. +// +// Solidity: event NewSmartToken(address _token) +func (_Bancortoken *BancortokenFilterer) WatchNewSmartToken(opts *bind.WatchOpts, sink chan<- *BancortokenNewSmartToken) (event.Subscription, error) { + + logs, sub, err := _Bancortoken.contract.WatchLogs(opts, "NewSmartToken") + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancortokenNewSmartToken) + if err := _Bancortoken.contract.UnpackLog(event, "NewSmartToken", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseNewSmartToken is a log parse operation binding the contract event 0xf4cd1f8571e8d9c97ffcb81558807ab73f9803d54de5da6a0420593c82a4a9f0. +// +// Solidity: event NewSmartToken(address _token) +func (_Bancortoken *BancortokenFilterer) ParseNewSmartToken(log types.Log) (*BancortokenNewSmartToken, error) { + event := new(BancortokenNewSmartToken) + if err := _Bancortoken.contract.UnpackLog(event, "NewSmartToken", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancortokenOwnerUpdateIterator is returned from FilterOwnerUpdate and is used to iterate over the raw logs and unpacked data for OwnerUpdate events raised by the Bancortoken contract. +type BancortokenOwnerUpdateIterator struct { + Event *BancortokenOwnerUpdate // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancortokenOwnerUpdateIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancortokenOwnerUpdate) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancortokenOwnerUpdate) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancortokenOwnerUpdateIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancortokenOwnerUpdateIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancortokenOwnerUpdate represents a OwnerUpdate event raised by the Bancortoken contract. +type BancortokenOwnerUpdate struct { + PrevOwner common.Address + NewOwner common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterOwnerUpdate is a free log retrieval operation binding the contract event 0x343765429aea5a34b3ff6a3785a98a5abb2597aca87bfbb58632c173d585373a. +// +// Solidity: event OwnerUpdate(address _prevOwner, address _newOwner) +func (_Bancortoken *BancortokenFilterer) FilterOwnerUpdate(opts *bind.FilterOpts) (*BancortokenOwnerUpdateIterator, error) { + + logs, sub, err := _Bancortoken.contract.FilterLogs(opts, "OwnerUpdate") + if err != nil { + return nil, err + } + return &BancortokenOwnerUpdateIterator{contract: _Bancortoken.contract, event: "OwnerUpdate", logs: logs, sub: sub}, nil +} + +// WatchOwnerUpdate is a free log subscription operation binding the contract event 0x343765429aea5a34b3ff6a3785a98a5abb2597aca87bfbb58632c173d585373a. +// +// Solidity: event OwnerUpdate(address _prevOwner, address _newOwner) +func (_Bancortoken *BancortokenFilterer) WatchOwnerUpdate(opts *bind.WatchOpts, sink chan<- *BancortokenOwnerUpdate) (event.Subscription, error) { + + logs, sub, err := _Bancortoken.contract.WatchLogs(opts, "OwnerUpdate") + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancortokenOwnerUpdate) + if err := _Bancortoken.contract.UnpackLog(event, "OwnerUpdate", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseOwnerUpdate is a log parse operation binding the contract event 0x343765429aea5a34b3ff6a3785a98a5abb2597aca87bfbb58632c173d585373a. +// +// Solidity: event OwnerUpdate(address _prevOwner, address _newOwner) +func (_Bancortoken *BancortokenFilterer) ParseOwnerUpdate(log types.Log) (*BancortokenOwnerUpdate, error) { + event := new(BancortokenOwnerUpdate) + if err := _Bancortoken.contract.UnpackLog(event, "OwnerUpdate", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancortokenTransferIterator is returned from FilterTransfer and is used to iterate over the raw logs and unpacked data for Transfer events raised by the Bancortoken contract. +type BancortokenTransferIterator struct { + Event *BancortokenTransfer // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancortokenTransferIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancortokenTransfer) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancortokenTransfer) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancortokenTransferIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancortokenTransferIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancortokenTransfer represents a Transfer event raised by the Bancortoken contract. +type BancortokenTransfer struct { + From common.Address + To common.Address + Value *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterTransfer is a free log retrieval operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. +// +// Solidity: event Transfer(address indexed _from, address indexed _to, uint256 _value) +func (_Bancortoken *BancortokenFilterer) FilterTransfer(opts *bind.FilterOpts, _from []common.Address, _to []common.Address) (*BancortokenTransferIterator, error) { + + var _fromRule []interface{} + for _, _fromItem := range _from { + _fromRule = append(_fromRule, _fromItem) + } + var _toRule []interface{} + for _, _toItem := range _to { + _toRule = append(_toRule, _toItem) + } + + logs, sub, err := _Bancortoken.contract.FilterLogs(opts, "Transfer", _fromRule, _toRule) + if err != nil { + return nil, err + } + return &BancortokenTransferIterator{contract: _Bancortoken.contract, event: "Transfer", logs: logs, sub: sub}, nil +} + +// WatchTransfer is a free log subscription operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. +// +// Solidity: event Transfer(address indexed _from, address indexed _to, uint256 _value) +func (_Bancortoken *BancortokenFilterer) WatchTransfer(opts *bind.WatchOpts, sink chan<- *BancortokenTransfer, _from []common.Address, _to []common.Address) (event.Subscription, error) { + + var _fromRule []interface{} + for _, _fromItem := range _from { + _fromRule = append(_fromRule, _fromItem) + } + var _toRule []interface{} + for _, _toItem := range _to { + _toRule = append(_toRule, _toItem) + } + + logs, sub, err := _Bancortoken.contract.WatchLogs(opts, "Transfer", _fromRule, _toRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancortokenTransfer) + if err := _Bancortoken.contract.UnpackLog(event, "Transfer", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseTransfer is a log parse operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. +// +// Solidity: event Transfer(address indexed _from, address indexed _to, uint256 _value) +func (_Bancortoken *BancortokenFilterer) ParseTransfer(log types.Log) (*BancortokenTransfer, error) { + event := new(BancortokenTransfer) + if err := _Bancortoken.contract.UnpackLog(event, "Transfer", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} \ No newline at end of file diff --git a/zcnbridge/ethereum/token/token.go b/zcnbridge/ethereum/zcntoken/zcntoken.go similarity index 99% rename from zcnbridge/ethereum/token/token.go rename to zcnbridge/ethereum/zcntoken/zcntoken.go index 25d2e740d..0caf78343 100644 --- a/zcnbridge/ethereum/token/token.go +++ b/zcnbridge/ethereum/zcntoken/zcntoken.go @@ -1,7 +1,7 @@ // Code generated - DO NOT EDIT. // This file is a generated binding and any manual changes will be lost. -package token +package zcntoken import ( "errors" From 6c5dafc9ddc696ea589f7b7a549318c7ee431e9c Mon Sep 17 00:00:00 2001 From: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Date: Tue, 21 Nov 2023 12:06:10 +0530 Subject: [PATCH 105/134] change hasher (#1288) * change hasher * set max proc to 1 * set batch size to 2 * revert hasher lib changes * increase batch size to 4 * set batch size to 2 * fix build * update chunk reader * run gc * add sleep and decrease batch size * change blake3 * fix operation slice * fix batch size * increase sleep time * add memory pool * increase swg for wasm * reuse chunk reader * fix read chunk * rmv unused package * Remove sleep and GOMAXPROCS=1 * Increase batch size a little --------- Co-authored-by: peterlimg --- core/version/version.go | 3 ++- wasmsdk/blobber.go | 1 - wasmsdk/sdk.go | 2 +- zboxcore/sdk/allocation.go | 8 +++++--- zboxcore/sdk/chunked_upload_chunk_reader.go | 2 +- zboxcore/sdk/downloadworker.go | 3 ++- 6 files changed, 11 insertions(+), 8 deletions(-) diff --git a/core/version/version.go b/core/version/version.go index 459a91ad3..6655d402c 100644 --- a/core/version/version.go +++ b/core/version/version.go @@ -2,4 +2,5 @@ //====== THIS IS AUTOGENERATED FILE. DO NOT MODIFY ======== package version -const VERSIONSTR = "v1.10.0-100-gf600e64b" +const VERSIONSTR = "v1.10.0-141-gf81a4b84" + diff --git a/wasmsdk/blobber.go b/wasmsdk/blobber.go index c0b23d83f..ba23a2a37 100644 --- a/wasmsdk/blobber.go +++ b/wasmsdk/blobber.go @@ -516,7 +516,6 @@ func bulkUpload(jsonBulkUploadOptions string) ([]BulkUploadResult, error) { if err != nil { return nil, err } - n := len(options) wait := make(chan BulkUploadResult, 1) diff --git a/wasmsdk/sdk.go b/wasmsdk/sdk.go index e3daac0f1..b616d48ee 100644 --- a/wasmsdk/sdk.go +++ b/wasmsdk/sdk.go @@ -45,7 +45,7 @@ func initSDKs(chainID, blockWorker, signatureScheme string, fmt.Println("wasm: InitZCNSDK ", err) return err } - + sdk.SetWasm() return nil } diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 2c0b25422..6891c47c8 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -237,6 +237,8 @@ func GetWritePriceRange() (PriceRange, error) { func SetWasm() { IsWasm = true + BatchSize = 5 + MultiOpBatchSize = 7 } func getPriceRange(name string) (PriceRange, error) { @@ -834,9 +836,9 @@ func (a *Allocation) DoMultiOperation(operations []OperationRequest) error { fmt.Sprintf("Multioperation: create connection failed. Required consensus %d got %d", mo.consensusThresh, mo.operationMask.CountOnes())) } - ops := 0 + for ; i < len(operations); i++ { - if ops > MultiOpBatchSize { + if len(mo.operations) >= MultiOpBatchSize { // max batch size reached, commit connectionID = zboxutil.NewConnectionId() break @@ -890,7 +892,6 @@ func (a *Allocation) DoMultiOperation(operations []OperationRequest) error { connectionID = newConnectionID break } - ops++ err = operation.Verify(a) if err != nil { return err @@ -908,6 +909,7 @@ func (a *Allocation) DoMultiOperation(operations []OperationRequest) error { if err != nil { return err } + mo.operations = nil } } return nil diff --git a/zboxcore/sdk/chunked_upload_chunk_reader.go b/zboxcore/sdk/chunked_upload_chunk_reader.go index 00417a188..f41d2f1eb 100644 --- a/zboxcore/sdk/chunked_upload_chunk_reader.go +++ b/zboxcore/sdk/chunked_upload_chunk_reader.go @@ -110,6 +110,7 @@ func createChunkReader(fileReader io.Reader, size, chunkSize int64, dataShards i } r.chunkDataSizePerRead = r.chunkDataSize * int64(dataShards) + // TODO: enable this for concurrent hashing // r.hasherWG.Add(1) // go r.hashData() return r, nil @@ -151,7 +152,6 @@ func (r *chunkedUploadChunkReader) Next() (*ChunkData, error) { ReadSize: 0, FragmentSize: 0, } - chunkBytes := make([]byte, r.chunkDataSizePerRead) readLen, err := r.fileReader.Read(chunkBytes) if err != nil { diff --git a/zboxcore/sdk/downloadworker.go b/zboxcore/sdk/downloadworker.go index d6fdb112d..abc58c18f 100644 --- a/zboxcore/sdk/downloadworker.go +++ b/zboxcore/sdk/downloadworker.go @@ -17,6 +17,8 @@ import ( "sync/atomic" "time" + "github.com/minio/sha256-simd" + "github.com/0chain/errors" "github.com/0chain/gosdk/core/common" "github.com/0chain/gosdk/core/sys" @@ -29,7 +31,6 @@ import ( "github.com/0chain/gosdk/zboxcore/marker" "github.com/0chain/gosdk/zboxcore/zboxutil" "github.com/klauspost/reedsolomon" - "github.com/minio/sha256-simd" "go.dedis.ch/kyber/v3/group/edwards25519" "golang.org/x/sync/errgroup" ) From 9d9f24900375f6e31397bc905a67f3bec854f7f7 Mon Sep 17 00:00:00 2001 From: peterlimg <54137706+peterlimg@users.noreply.github.com> Date: Wed, 22 Nov 2023 22:51:47 +1100 Subject: [PATCH 106/134] Import eth wallet with index (#1292) * Add import account address index * Make it optional --- zcnbridge/keystore.go | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/zcnbridge/keystore.go b/zcnbridge/keystore.go index 477cd54d1..4a98e63fa 100644 --- a/zcnbridge/keystore.go +++ b/zcnbridge/keystore.go @@ -126,7 +126,7 @@ func CreateKeyStorage(homedir, password string) error { } // ImportAccount imports account using mnemonic -func ImportAccount(homedir, mnemonic, password string) (string, error) { +func ImportAccount(homedir, mnemonic, password string, addrIndex ...int) (string, error) { // 1. Create storage and account if it doesn't exist and add account to it keyDir := path.Join(homedir, EthereumWalletStorageDir) @@ -139,7 +139,12 @@ func ImportAccount(homedir, mnemonic, password string) (string, error) { return "", errors.Wrap(err, "failed to import from mnemonic") } - pathD := hdw.MustParseDerivationPath("m/44'/60'/0'/0/0") + var addrIdx int + if len(addrIndex) > 0 { + addrIdx = addrIndex[0] + } + + pathD := hdw.MustParseDerivationPath(fmt.Sprintf("m/44'/60'/0'/0/%d", addrIdx)) account, err := wallet.Derive(pathD, true) if err != nil { return "", errors.Wrap(err, "failed parse derivation path") From bf2d3ec27f449d2a73530c59f410364f887ef3ca Mon Sep 17 00:00:00 2001 From: peterlimg <54137706+peterlimg@users.noreply.github.com> Date: Thu, 23 Nov 2023 21:27:34 +1100 Subject: [PATCH 107/134] Feat/import-account-idx (#1294) * Add import account address index * Make it optional * Add account index option --- zcnbridge/keystore.go | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/zcnbridge/keystore.go b/zcnbridge/keystore.go index 4a98e63fa..6708afa7e 100644 --- a/zcnbridge/keystore.go +++ b/zcnbridge/keystore.go @@ -125,8 +125,13 @@ func CreateKeyStorage(homedir, password string) error { return nil } +type AccountAddressIndex struct { + AccountIndex int + AddressIndex int +} + // ImportAccount imports account using mnemonic -func ImportAccount(homedir, mnemonic, password string, addrIndex ...int) (string, error) { +func ImportAccount(homedir, mnemonic, password string, accountAddrIndex ...AccountAddressIndex) (string, error) { // 1. Create storage and account if it doesn't exist and add account to it keyDir := path.Join(homedir, EthereumWalletStorageDir) @@ -139,12 +144,12 @@ func ImportAccount(homedir, mnemonic, password string, addrIndex ...int) (string return "", errors.Wrap(err, "failed to import from mnemonic") } - var addrIdx int - if len(addrIndex) > 0 { - addrIdx = addrIndex[0] + var aai AccountAddressIndex + if len(accountAddrIndex) > 0 { + aai = accountAddrIndex[0] } - pathD := hdw.MustParseDerivationPath(fmt.Sprintf("m/44'/60'/0'/0/%d", addrIdx)) + pathD := hdw.MustParseDerivationPath(fmt.Sprintf("m/44'/60'/0'/%d/%d", aai.AccountIndex, aai.AddressIndex)) account, err := wallet.Derive(pathD, true) if err != nil { return "", errors.Wrap(err, "failed parse derivation path") From 434dd6a471f920c3f2be81bbf1862d9164d02948 Mon Sep 17 00:00:00 2001 From: peterlimg <54137706+peterlimg@users.noreply.github.com> Date: Fri, 24 Nov 2023 03:04:46 +1100 Subject: [PATCH 108/134] Add account bip32 option (#1295) --- zcnbridge/keystore.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/zcnbridge/keystore.go b/zcnbridge/keystore.go index 6708afa7e..101662b59 100644 --- a/zcnbridge/keystore.go +++ b/zcnbridge/keystore.go @@ -128,6 +128,7 @@ func CreateKeyStorage(homedir, password string) error { type AccountAddressIndex struct { AccountIndex int AddressIndex int + Bip32 bool } // ImportAccount imports account using mnemonic @@ -149,7 +150,13 @@ func ImportAccount(homedir, mnemonic, password string, accountAddrIndex ...Accou aai = accountAddrIndex[0] } - pathD := hdw.MustParseDerivationPath(fmt.Sprintf("m/44'/60'/0'/%d/%d", aai.AccountIndex, aai.AddressIndex)) + var pathD accounts.DerivationPath + if aai.Bip32 { + pathD = hdw.MustParseDerivationPath(fmt.Sprintf("m/44'/60'/0'/%d", aai.AddressIndex)) + } else { + pathD = hdw.MustParseDerivationPath(fmt.Sprintf("m/44'/60'/%d'/0/%d", aai.AccountIndex, aai.AddressIndex)) + } + account, err := wallet.Derive(pathD, true) if err != nil { return "", errors.Wrap(err, "failed parse derivation path") From 5a931d29f60ac4867968343b42e4f4e5b0bd42aa Mon Sep 17 00:00:00 2001 From: Jayash Satolia <73050737+Jayashsatolia403@users.noreply.github.com> Date: Fri, 24 Nov 2023 19:46:10 +0530 Subject: [PATCH 109/134] Fix allocation min lock (#1297) --- zboxcore/sdk/sdk.go | 22 ++-------------------- 1 file changed, 2 insertions(+), 20 deletions(-) diff --git a/zboxcore/sdk/sdk.go b/zboxcore/sdk/sdk.go index 191f95077..e9e723e17 100644 --- a/zboxcore/sdk/sdk.go +++ b/zboxcore/sdk/sdk.go @@ -1571,28 +1571,10 @@ func GetAllocationMinLock( ) (int64, error) { baSize := int64(math.Ceil(float64(size) / float64(datashards))) totalSize := baSize * int64(datashards+parityshards) - config, err := GetStorageSCConfig() - if err != nil { - return 0, err - } - t := config.Fields["time_unit"] - timeunitStr, ok := t.(string) - if !ok { - return 0, fmt.Errorf("bad time_unit type") - } - timeunit, err := time.ParseDuration(timeunitStr) - if err != nil { - return 0, fmt.Errorf("bad time_unit format") - } - - expiry := common.Timestamp(time.Now().Add(timeunit).Unix()) - duration := expiry / common.Timestamp(timeunit.Milliseconds()) - if expiry%common.Timestamp(timeunit.Milliseconds()) != 0 { - duration++ - } sizeInGB := float64(totalSize) / GB - cost := float64(duration) * (sizeInGB*float64(writePrice.Max) + sizeInGB*float64(readPrice.Max)) + + cost := sizeInGB * float64(writePrice.Max) coin, err := currency.Float64ToCoin(cost) if err != nil { return 0, err From c60152672ab44d1b7ad2f88391cc80bee3e19884 Mon Sep 17 00:00:00 2001 From: Manohar Reddy Date: Sun, 26 Nov 2023 16:04:58 +0000 Subject: [PATCH 110/134] create PRs to dependent repos when a PR is merged to sprint branches (#1283) * create PRs to dependent repos when a PR is merged to sprint branches * add branch name * move wasm-build to build-sdk.yml * cleanup sdk-release.yml --- .github/workflows/build-sdks.yml | 47 +++++++++++++---- .github/workflows/sdk-release.yml | 85 ++----------------------------- 2 files changed, 41 insertions(+), 91 deletions(-) diff --git a/.github/workflows/build-sdks.yml b/.github/workflows/build-sdks.yml index d21034514..2069e90b1 100644 --- a/.github/workflows/build-sdks.yml +++ b/.github/workflows/build-sdks.yml @@ -62,10 +62,10 @@ jobs: echo "::set-output name=RELEASE::false" echo "::set-output name=TAG::none" - + elif [[ ${tag} = v*\.*\.* ]] ; then echo "> 0Chain: trigger from git event" - + # upload output on release echo "::set-output name=RELEASE::true" echo "::set-output name=TAG::${tag}" @@ -159,17 +159,17 @@ jobs: run: | tag=$(echo ${GITHUB_REF#refs/tags/}) echo ${tag} - + if [[ "${{github.event_name}}" = "workflow_dispatch" ]]; then echo "> 0Chain: trigger from workflow_dispatch" echo "::set-output name=RELEASE::false" echo "::set-output name=TAG::none" - - + + elif [[ ${tag} = v*\.*\.* ]] ; then echo "> 0Chain: trigger from git event" - + # upload output on release echo "::set-output name=RELEASE::true" echo "::set-output name=TAG::${tag}" @@ -237,10 +237,10 @@ jobs: echo "::set-output name=RELEASE::false" echo "::set-output name=TAG::none" - + elif [[ ${tag} = v*\.*\.* ]] ; then echo "> 0Chain: trigger from git event" - + # upload output on release echo "::set-output name=RELEASE::true" echo "::set-output name=TAG::${tag}" @@ -263,7 +263,6 @@ jobs: path: | zcncore-macos.tar.gz - build-windows: name: Build-windows runs-on: [self-hosted, arc-runner] @@ -306,10 +305,10 @@ jobs: echo "::set-output name=RELEASE::false" echo "::set-output name=TAG::none" - + elif [[ ${tag} = v*\.*\.* ]] ; then echo "> 0Chain: trigger from git event" - + # upload output on release echo "::set-output name=RELEASE::true" echo "::set-output name=TAG::${tag}" @@ -331,3 +330,29 @@ jobs: name: zcn-windows path: | zcn-windows.zip + + build-wasm: + name: Build-wasm + runs-on: [self-hosted, arc-runner] + steps: + - name: Set up Go 1.20 + uses: actions/setup-go@v2 + with: + go-version: ^1.20 + + - name: Checkout + uses: actions/checkout@v2 + + - name: Install dependencies + run: | + sudo apt-get update + sudo apt-get -y install build-essential nghttp2 libnghttp2-dev libssl-dev wget + + - name: Build + run: docker run --rm -v $PWD:/gosdk -w /gosdk golang:1.20 make wasm-build + + - name: 'Upload Artifact' + uses: actions/upload-artifact@v3 + with: + name: zcn.wasm + path: zcn.wasm diff --git a/.github/workflows/sdk-release.yml b/.github/workflows/sdk-release.yml index a1db6e2b4..c76ed6926 100644 --- a/.github/workflows/sdk-release.yml +++ b/.github/workflows/sdk-release.yml @@ -1,4 +1,4 @@ -name: GoSDK & WasmSDK +name: GoSDK Release concurrency: group: "sdk-${{ github.ref }}" @@ -6,10 +6,9 @@ concurrency: on: push: - branches: [ master, staging, qa ] + branches: [ master, staging, qa, sprint-* ] tags: - 'v*.*.*' - pull_request: workflow_dispatch: inputs: version: @@ -20,88 +19,15 @@ env: ACTIONS_ALLOW_UNSECURE_COMMANDS: true jobs: - build: - name: sdk-build - runs-on: [self-hosted, arc-runner] - steps: - - name: Set up Go 1.20 - uses: actions/setup-go@v2 - with: - go-version: ^1.20 - - - name: Checkout - uses: actions/checkout@v2 - - - name: Install dependencies - run: | - sudo apt-get update - sudo apt-get -y install build-essential nghttp2 libnghttp2-dev libssl-dev wget - - - name: Setup Build - id: setup_build - run: | - tag=$(echo ${GITHUB_REF#refs/tags/}) - echo ${tag} - if [[ -n "${{github.event.inputs.version}}" ]]; then - echo "> 0Chain: trigger from workflow_dispatch" - echo "::set-output name=PR::true" - - gosdk="{\"gosdk\":\"${{github.event.inputs.version}}\"}" - echo "::set-output name=SDK::${gosdk}" - elif [[ ${tag} = v*\.*\.* ]] ; then - echo "> 0Chain: trigger from git event" - echo "::set-output name=PR::true" - - gosdk="{\"gosdk\":\"${tag}\"}" - echo "::set-output name=SDK::${gosdk}" - - # upload zcn.wasm on release - echo "::set-output name=RELEASE::true" - echo "::set-output name=TAG::${tag}" - elif [[ ${tag} = "refs/heads/staging" ]] ; then - echo "> 0Chain: trigger from git event" - echo "::set-output name=PR::true" - - gosdk="{\"gosdk\":\"staging\"}" - echo "::set-output name=SDK::${gosdk}" - - # upload zcn.wasm on release - echo "::set-output name=RELEASE::true" - echo "::set-output name=TAG::${tag}" - fi - - - name: Build - run: docker run --rm -v $PWD:/gosdk -w /gosdk golang:1.20 make wasm-build - - - name: Upload binaries to release - uses: svenstaro/upload-release-action@v2 - if: steps.setup_build.outputs.RELEASE == 'true' - with: - repo_token: ${{ secrets.GITHUB_TOKEN }} - file: zcn.wasm - tag: ${{ steps.setup_build.outputs.TAG }} - overwrite: true - file_glob: true - - - name: 'Upload Artifact' - uses: actions/upload-artifact@v3 - with: - name: zcn.wasm - path: zcn.wasm - outputs: - PR: ${{ steps.setup_build.outputs.PR }} - SDK: ${{ steps.setup_build.outputs.SDK }} - TAG: ${{ steps.setup_build.outputs.TAG }} release: name: sdk-release - needs: build - if: needs.build.outputs.PR == 'true' runs-on: [self-hosted, build] steps: - name: start to create pr run: | echo "GoSDK & WebAssembly SDK should be upgraded" + create-pr: name: create-pr strategy: @@ -109,16 +35,15 @@ jobs: max-parallel: 1 matrix: repo: [0nft, 0box, 0dns, zwalletcli, zboxcli, blobber, zs3server, s3-migration, token_bridge_authserver ] - needs: [ build, release ] + needs: [ release ] runs-on: [self-hosted, build] steps: - name: Create PR on ${{ matrix.repo }} uses: convictional/trigger-workflow-and-wait@v1.3.0 - if: needs.build.outputs.PR == 'true' with: owner: 0chain repo: ${{ matrix.repo }} - ref: staging + ref: ${{ github.head_ref || github.ref_name }} github_token: ${{ secrets.GOSDK }} workflow_file_name: gosdk.yml inputs: ${{ needs.build.outputs.SDK }} From 9a527cceb8ea1aee8a7af67a5056c9f4436dc204 Mon Sep 17 00:00:00 2001 From: Tanishq Gupta <52757132+tanishq67@users.noreply.github.com> Date: Sun, 26 Nov 2023 22:07:57 +0600 Subject: [PATCH 111/134] Removed padding from the CryptoJS Encrypt and Decrypt functions functions. (#1300) Co-authored-by: Manohar Reddy --- zcncore/wallet_base.go | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/zcncore/wallet_base.go b/zcncore/wallet_base.go index af4720b7f..98bc9cc4b 100644 --- a/zcncore/wallet_base.go +++ b/zcncore/wallet_base.go @@ -1282,7 +1282,7 @@ func Decrypt(key, text string) (string, error) { func CryptoJsEncrypt(passphrase, message string) (string, error) { o := openssl.New() - enc, err := o.EncryptBytes(pad(passphrase, 32, ","), []byte(message), openssl.DigestMD5Sum) + enc, err := o.EncryptBytes(passphrase, []byte(message), openssl.DigestMD5Sum) if err != nil { return "", err } @@ -1290,16 +1290,9 @@ func CryptoJsEncrypt(passphrase, message string) (string, error) { return string(enc), nil } -func pad(passphrase string, i int, symbol string) string { - if len(passphrase) < i { - return passphrase + strings.Repeat(symbol, i-len(passphrase)) - } - return passphrase -} - func CryptoJsDecrypt(passphrase, encryptedMessage string) (string, error) { o := openssl.New() - dec, err := o.DecryptBytes(pad(passphrase, 32, ","), []byte(encryptedMessage), openssl.DigestMD5Sum) + dec, err := o.DecryptBytes(passphrase, []byte(encryptedMessage), openssl.DigestMD5Sum) if err != nil { return "", err } From f3e660039ff1fd571a236369473af6752858d6b9 Mon Sep 17 00:00:00 2001 From: Jayash Satolia Date: Mon, 27 Nov 2023 00:02:10 +0530 Subject: [PATCH 112/134] Fix allocation min lock --- wasmsdk/allocation.go | 5 ++--- zboxcore/sdk/sdk.go | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/wasmsdk/allocation.go b/wasmsdk/allocation.go index 276ccd3dc..2190afc8d 100644 --- a/wasmsdk/allocation.go +++ b/wasmsdk/allocation.go @@ -214,12 +214,11 @@ func updateAllocation(allocationID string, func getAllocationMinLock(datashards, parityshards int, size int64, - maxreadPrice, maxwritePrice uint64, + maxwritePrice uint64, ) (int64, error) { - readPrice := sdk.PriceRange{Min: 0, Max: maxreadPrice} writePrice := sdk.PriceRange{Min: 0, Max: maxwritePrice} - value, err := sdk.GetAllocationMinLock(datashards, parityshards, size, readPrice, writePrice) + value, err := sdk.GetAllocationMinLock(datashards, parityshards, size, writePrice) if err != nil { sdkLogger.Error(err) return 0, err diff --git a/zboxcore/sdk/sdk.go b/zboxcore/sdk/sdk.go index e9e723e17..b78856d9b 100644 --- a/zboxcore/sdk/sdk.go +++ b/zboxcore/sdk/sdk.go @@ -1567,7 +1567,7 @@ func CommitToFabric(metaTxnData, fabricConfigJSON string) (string, error) { func GetAllocationMinLock( datashards, parityshards int, size int64, - readPrice, writePrice PriceRange, + writePrice PriceRange, ) (int64, error) { baSize := int64(math.Ceil(float64(size) / float64(datashards))) totalSize := baSize * int64(datashards+parityshards) From 9857209b8c472418e9c7b0872e54ab354e661933 Mon Sep 17 00:00:00 2001 From: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Date: Tue, 28 Nov 2023 18:53:24 +0530 Subject: [PATCH 113/134] change chunkNumber for wasm (#1304) * change numBlock for wasm * change numBlocks * revert sdk changes --- wasmsdk/blobber.go | 6 ++++++ zboxcore/sdk/chunked_upload.go | 1 + 2 files changed, 7 insertions(+) diff --git a/wasmsdk/blobber.go b/wasmsdk/blobber.go index ba23a2a37..64a05e175 100644 --- a/wasmsdk/blobber.go +++ b/wasmsdk/blobber.go @@ -625,6 +625,9 @@ func multiUpload(jsonBulkUploadOptions string) (MultiUploadResult, error) { if numBlocks < 1 { numBlocks = 100 } + if allocationObj.DataShards > 7 { + numBlocks = 60 + } options := []sdk.ChunkedUploadOption{ sdk.WithThumbnail(option.ThumbnailBytes.Buffer), sdk.WithEncrypt(encrypt), @@ -711,6 +714,9 @@ func uploadWithJsFuncs(allocationID, remotePath string, readChunkFuncName string if numBlocks < 1 { numBlocks = 100 } + if allocationObj.DataShards > 7 { + numBlocks = 60 + } ChunkedUpload, err := sdk.CreateChunkedUpload("/", allocationObj, fileMeta, fileReader, isUpdate, isRepair, webStreaming, zboxutil.NewConnectionId(), sdk.WithThumbnail(thumbnailBytes), diff --git a/zboxcore/sdk/chunked_upload.go b/zboxcore/sdk/chunked_upload.go index 2116000f5..5b54d47ee 100644 --- a/zboxcore/sdk/chunked_upload.go +++ b/zboxcore/sdk/chunked_upload.go @@ -207,6 +207,7 @@ func CreateChunkedUpload( for _, opt := range opts { opt(su) } + if su.progressStorer == nil { su.progressStorer = createFsChunkedUploadProgress(context.Background()) } From 5737a993b42855b1f8ab51769d41c83bbaf177d9 Mon Sep 17 00:00:00 2001 From: Yaroslav Svitlytskyi <53532703+YarikRevich@users.noreply.github.com> Date: Wed, 29 Nov 2023 13:11:29 +0100 Subject: [PATCH 114/134] Feature: implement fork per run strategy (#1299) * feature: added fork creation * fix: fixed bug * feature: improved Tenderly fork creation flow --- .github/workflows/system_tests.yml | 3 +- .github/workflows/tests.yml | 98 +++++++++++++++++++++++++++++- 2 files changed, 96 insertions(+), 5 deletions(-) diff --git a/.github/workflows/system_tests.yml b/.github/workflows/system_tests.yml index 5a22964a9..a25e0cbfe 100644 --- a/.github/workflows/system_tests.yml +++ b/.github/workflows/system_tests.yml @@ -45,11 +45,10 @@ jobs: DEV8KC: ${{ secrets.DEV8KC }} DEV9KC: ${{ secrets.DEV9KC }} SUBGRAPH_API_URL: ${{ secrets.SUBGRAPH_API_URL }} - TENDERLY_FORK_ID: ${{ secrets.TENDERLY_FORK_ID }} + TENDERLY_SECRET: ${{ secrets.TENDERLY_SECRET }} DEVOPS_CHANNEL_WEBHOOK_URL: ${{ secrets.DEVOPS_CHANNEL_WEBHOOK_URL }} GRAPHNODE_SC: ${{ secrets.GRAPHNODE_SC }} GRAPHNODE_NETWORK: ${{ secrets.GRAPHNODE_NETWORK }} - GRAPHNODE_ETHEREUM_NODE_URL: https://rpc.tenderly.co/fork/${{ secrets.TENDERLY_FORK_ID }} S3_ACCESS_KEY: ${{ secrets.S3_ACCESS_KEY }} S3_SECRET_KEY: ${{ secrets.S3_SECRET_KEY }} diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 762fcb83c..deb91074b 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -108,6 +108,90 @@ jobs: echo "NETWORK_URL=$(echo dev-${RUNNER_NAME:(-1)}.devnet-0chain.net)" >> $GITHUB_ENV echo "RUNNER_NUMBER=${RUNNER_NAME:(-1)}" >> $GITHUB_ENV + - name: 'Setup jq' + uses: dcarbone/install-jq-action@v2.1.0 + with: + version: '1.7' + force: 'false' + + - name: "Create Tenderly fork" + run: | + echo "TENDERLY_CREATION_INFO=$(curl -X POST \ + -H "x-access-key: ${{ secrets.TENDERLY_SECRET }}" \ + -H "Content-Type: application/json" \ + -d '{"alias":"mainnet-dev-${{ env.RUNNER_NUMBER }}-${{ github.run_id }}", "description":"", "network_id":"1"}' \ + https://api.tenderly.co/api/v1/account/zus_network/project/project/fork)" >> $GITHUB_ENV + + - name: "Parse Tenderly fork creation transaction result" + run: | + echo "TENDERLY_FORK_ID=$(echo '${{ env.TENDERLY_CREATION_INFO }}' | jq -r '.simulation_fork.id')" >> $GITHUB_ENV + echo "TENDERLY_ROOT_TRANSACTION_ID=$(echo '${{ env.TENDERLY_CREATION_INFO }}' | jq -r '.root_transaction.id')" >> $GITHUB_ENV + + - name: "Retrieve Tenderly fork block number" + run: | + echo "TENDERLY_FORK_BLOCK_NUMBER=$(curl -X GET \ + -H "x-access-key: ${{ secrets.TENDERLY_SECRET }}" \ + -H "Content-Type: application/json" \ + https://api.tenderly.co/api/v1/network/1/block-number | jq -r '.block_number')" >> $GITHUB_ENV + + echo "TENDERLY_FORK_BLOCK_NUMBER=$((${{ env.TENDERLY_FORK_BLOCK_NUMBER }} + 1))" >> GITHUB_ENV + + - name: "Transfer Bridge ownership in Tenderly fork" + run: | + echo "TENDERLY_ROOT_TRANSACTION_ID=$(curl -X POST \ + -H "x-access-key: ${{ secrets.TENDERLY_SECRET }}" \ + -H "Content-Type: application/json" \ + -d '{ + "network_id": "1", + "block_number": ${{ env.TENDERLY_FORK_BLOCK_NUMBER }}, + "transaction_index": null, + "from": "0xed8f3170db6d1a71c8fa6d8d73cc2c51db95d5a4", + "input": "0xf2fde38b0000000000000000000000008e25cfd9bd6c0ca67a5522cd920b3c66d39d6e97", + "to": "0x7700d773022b19622095118fadf46f7b9448be9b", + "gas": 8000000, + "gas_price": "0", + "value": "0", + "access_list": [], + "generate_access_list": true, + "save": true, + "source": "dashboard", + "block_header": null, + "root": "${{ env.TENDERLY_ROOT_TRANSACTION_ID }}", + "skip_fork_head_update": false, + "alias": "", + "description": "Transfer ownership to 0x8E25cfd9bd6c0ca67a5522cd920b3c66D39d6E97" + }' \ + https://api.tenderly.co/api/v1/account/zus_network/project/project/fork/${{ env.TENDERLY_FORK_ID }}/simulate | jq -r '.simulation.id')" >> $GITHUB_ENV + + echo "TENDERLY_FORK_BLOCK_NUMBER=$((${{ env.TENDERLY_FORK_BLOCK_NUMBER }} + 1))" >> GITHUB_ENV + + - name: "Transfer Authorizers ownership in Tenderly fork" + run: | + curl -X POST \ + -H "x-access-key: ${{ secrets.TENDERLY_SECRET }}" \ + -H "Content-Type: application/json" \ + -d '{ + "network_id": "1", + "block_number": ${{ env.TENDERLY_FORK_BLOCK_NUMBER }}, + "transaction_index": null, + "from": "0xed8f3170db6d1a71c8fa6d8d73cc2c51db95d5a4", + "input": "0xf2fde38b0000000000000000000000008e25cfd9bd6c0ca67a5522cd920b3c66d39d6e97", + "to": "0x481dab4407b9880de0a68dc62e6af611c4949e42", + "gas": 8000000, + "gas_price": "0", + "value": "0", + "access_list": [], + "generate_access_list": true, + "save": true, + "source": "dashboard", + "block_header": null, + "root": "${{ env.TENDERLY_ROOT_TRANSACTION_ID }}", + "skip_fork_head_update": false, + "alias": "", + "description": "Transfer ownership to 0x8E25cfd9bd6c0ca67a5522cd920b3c66D39d6E97" + }' \ + https://api.tenderly.co/api/v1/account/zus_network/project/project/fork/${{ env.TENDERLY_FORK_ID }}/simulate + - name: "Deploy 0Chain" uses: 0chain/actions/deploy-0chain@master with: @@ -116,10 +200,10 @@ jobs: teardown_condition: "TESTS_PASSED" custom_go_sdk_version: ${{ env.CURRENT_BRANCH_HEAD }} SUBGRAPH_API_URL: ${{ secrets.SUBGRAPH_API_URL }} - TENDERLY_FORK_ID: ${{ secrets.TENDERLY_FORK_ID }} + TENDERLY_FORK_ID: ${{ env.TENDERLY_FORK_ID }} graphnode_sc: ${{ secrets.GRAPHNODE_SC }} graphnode_network: ${{ secrets.GRAPHNODE_NETWORK }} - graphnode_ethereum_node_url: https://rpc.tenderly.co/fork/${{ secrets.TENDERLY_FORK_ID }} + graphnode_ethereum_node_url: https://rpc.tenderly.co/fork/${{ env.TENDERLY_FORK_ID }} svc_account_secret: ${{ secrets.SVC_ACCOUNT_SECRET }} - name: "Run System tests" @@ -135,11 +219,19 @@ jobs: retry_failures: true run_frontend_tests: true run_smoke_tests: ${{ github.ref != 'refs/heads/staging' && github.base_ref != 'staging' && github.ref != 'refs/heads/master' && github.base_ref != 'master' }} - TENDERLY_FORK_ID: ${{ secrets.TENDERLY_FORK_ID }} + TENDERLY_FORK_ID: ${{ env.TENDERLY_FORK_ID }} DEVOPS_CHANNEL_WEBHOOK_URL: ${{ secrets.DEVOPS_CHANNEL_WEBHOOK_URL }} S3_ACCESS_KEY: ${{ secrets.S3_ACCESS_KEY }} S3_SECRET_KEY: ${{ secrets.S3_SECRET_KEY }} + - name: "Remove Tenderly fork" + if: always() + run: | + curl -X DELETE \ + -H "x-access-key: ${{ secrets.TENDERLY_SECRET }}" \ + -H "Content-Type: application/json" \ + https://api.tenderly.co/api/v1/account/zus_network/project/project/fork/${{ env.TENDERLY_FORK_ID }} + - name: "Set PR status as ${{ job.status }}" if: ${{ (success() || failure()) && steps.findPr.outputs.number }} uses: 0chain/actions/set-pr-status@master From 4b1b20574309c89c6a1181687ee6929caf3f16a7 Mon Sep 17 00:00:00 2001 From: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Date: Thu, 30 Nov 2023 23:41:33 +0530 Subject: [PATCH 115/134] fix parse error (#1309) * fix parse error * fix log * add swg --- wasmsdk/blobber.go | 6 ++---- zboxcore/sdk/allocation.go | 9 ++++----- zboxcore/sdk/chunked_upload.go | 9 +++++---- zboxcore/sdk/listworker.go | 2 +- zboxcore/sdk/multi_operation_worker.go | 2 +- 5 files changed, 13 insertions(+), 15 deletions(-) diff --git a/wasmsdk/blobber.go b/wasmsdk/blobber.go index 64a05e175..b79ec55c9 100644 --- a/wasmsdk/blobber.go +++ b/wasmsdk/blobber.go @@ -28,8 +28,6 @@ import ( const FileOperationInsert = "insert" -var allocObj *sdk.Allocation - func listObjects(allocationID string, remotePath string) (*sdk.ListResult, error) { alloc, err := getAllocation(allocationID) if err != nil { @@ -626,7 +624,7 @@ func multiUpload(jsonBulkUploadOptions string) (MultiUploadResult, error) { numBlocks = 100 } if allocationObj.DataShards > 7 { - numBlocks = 60 + numBlocks = 50 } options := []sdk.ChunkedUploadOption{ sdk.WithThumbnail(option.ThumbnailBytes.Buffer), @@ -715,7 +713,7 @@ func uploadWithJsFuncs(allocationID, remotePath string, readChunkFuncName string numBlocks = 100 } if allocationObj.DataShards > 7 { - numBlocks = 60 + numBlocks = 50 } ChunkedUpload, err := sdk.CreateChunkedUpload("/", allocationObj, fileMeta, fileReader, isUpdate, isRepair, webStreaming, zboxutil.NewConnectionId(), diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 6891c47c8..93e87320c 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -237,8 +237,8 @@ func GetWritePriceRange() (PriceRange, error) { func SetWasm() { IsWasm = true - BatchSize = 5 - MultiOpBatchSize = 7 + BatchSize = 3 + MultiOpBatchSize = 5 } func getPriceRange(name string) (PriceRange, error) { @@ -466,6 +466,7 @@ func (a *Allocation) EncryptAndUploadFileWithThumbnail( } func (a *Allocation) StartMultiUpload(workdir string, localPaths []string, fileNames []string, thumbnailPaths []string, encrypts []bool, chunkNumbers []int, remotePaths []string, isUpdate []bool, isWebstreaming []bool, status StatusCallback) error { + l.Logger.Debug("Initialize batch: ", BatchSize, MultiOpBatchSize) if len(localPaths) != len(thumbnailPaths) { return errors.New("invalid_value", "length of localpaths and thumbnailpaths must be equal") } @@ -793,10 +794,9 @@ func (a *Allocation) DoMultiOperation(operations []OperationRequest) error { return notInitialized } connectionID := zboxutil.NewConnectionId() - + var mo MultiOperation for i := 0; i < len(operations); { // resetting multi operation and previous paths for every batch - var mo MultiOperation mo.allocationObj = a mo.operationMask = zboxutil.NewUint128(0) mo.maskMU = &sync.Mutex{} @@ -807,7 +807,6 @@ func (a *Allocation) DoMultiOperation(operations []OperationRequest) error { consensusThresh: a.consensusThreshold, fullconsensus: a.fullconsensus, } - previousPaths := make(map[string]bool) connectionErrors := make([]error, len(mo.allocationObj.Blobbers)) diff --git a/zboxcore/sdk/chunked_upload.go b/zboxcore/sdk/chunked_upload.go index 5b54d47ee..826125714 100644 --- a/zboxcore/sdk/chunked_upload.go +++ b/zboxcore/sdk/chunked_upload.go @@ -30,6 +30,7 @@ import ( "github.com/0chain/gosdk/zboxcore/zboxutil" "github.com/google/uuid" "github.com/klauspost/reedsolomon" + "github.com/remeh/sizedwaitgroup" ) const ( @@ -744,17 +745,17 @@ func (su *ChunkedUpload) uploadProcessor() { return } wgErrors := make(chan error, len(su.blobbers)) - wg := &sync.WaitGroup{} ctx, cancel := context.WithCancel(context.TODO()) defer cancel() su.consensus.Reset() var pos uint64 var errCount int32 + swg := sizedwaitgroup.New(BatchSize) for i := su.uploadMask; !i.Equals64(0); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) { pos = uint64(i.TrailingZeros()) - wg.Add(1) + swg.Add() go func(pos uint64) { - defer wg.Done() + defer swg.Done() err := su.blobbers[pos].sendUploadRequest(ctx, su, uploadData.chunkEndIndex, uploadData.isFinal, su.encryptedKey, uploadData.uploadBody[pos].body, uploadData.uploadBody[pos].formData, pos) if err != nil { @@ -774,7 +775,7 @@ func (su *ChunkedUpload) uploadProcessor() { } }(pos) } - wg.Wait() + swg.Wait() close(wgErrors) for err := range wgErrors { su.removeProgress() diff --git a/zboxcore/sdk/listworker.go b/zboxcore/sdk/listworker.go index 3c1c063e0..b7ae67cf3 100644 --- a/zboxcore/sdk/listworker.go +++ b/zboxcore/sdk/listworker.go @@ -120,7 +120,6 @@ func (req *ListRequest) getListInfoFromBlobber(blobber *blockchain.StorageNode, return errors.Wrap(err, "Error: Resp") } s.WriteString(string(resp_body)) - l.Logger.Debug("List result from Blobber:", string(resp_body)) if resp.StatusCode == http.StatusOK { listResult := &fileref.ListResult{} err = json.Unmarshal(resp_body, listResult) @@ -190,6 +189,7 @@ func (req *ListRequest) getlistFromBlobbers() ([]*listResponse, error) { } func (req *ListRequest) GetListFromBlobbers() (*ListResult, error) { + l.Logger.Debug("Getting list info from blobbers") lR, err := req.getlistFromBlobbers() if err != nil { return nil, err diff --git a/zboxcore/sdk/multi_operation_worker.go b/zboxcore/sdk/multi_operation_worker.go index 8ef41c7de..5ab77bc6f 100644 --- a/zboxcore/sdk/multi_operation_worker.go +++ b/zboxcore/sdk/multi_operation_worker.go @@ -29,7 +29,7 @@ const ( DefaultCreateConnectionTimeOut = 2 * time.Minute ) -var BatchSize = 5 +var BatchSize = 6 type Operationer interface { Process(allocObj *Allocation, connectionID string) ([]fileref.RefEntity, zboxutil.Uint128, error) From ee87ed91fcf28e75b9d7cbeda1a4e1662a84816d Mon Sep 17 00:00:00 2001 From: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Date: Sat, 2 Dec 2023 17:55:57 +0530 Subject: [PATCH 116/134] Fix memory usage (#1311) * fix memory usage * change hasher to sha2 256 * fix unit test * increase numBlocks * fix thumbnail hash --- core/encryption/hash.go | 6 +++--- core/util/fixed_merkle_tree.go | 22 +++++++++++++++++++--- core/util/merkle_tree_interface.go | 4 ++-- core/util/validation_tree.go | 10 +++++----- core/util/validation_tree_test.go | 18 +++++++++--------- go.mod | 1 - go.sum | 7 ------- wasmsdk/blobber.go | 2 +- zboxcore/sdk/allocation.go | 4 ++-- zboxcore/sdk/chunked_upload_hasher.go | 5 ++--- zboxcore/sdk/chunked_upload_option.go | 4 ++-- zboxcore/sdk/downloadworker.go | 5 ++--- zboxcore/zboxutil/transport.go | 3 +-- 13 files changed, 48 insertions(+), 43 deletions(-) diff --git a/core/encryption/hash.go b/core/encryption/hash.go index 5ce9edfe1..088de16c6 100644 --- a/core/encryption/hash.go +++ b/core/encryption/hash.go @@ -4,7 +4,7 @@ import ( "crypto/sha1" "encoding/hex" - "github.com/zeebo/blake3" + "github.com/minio/sha256-simd" "golang.org/x/crypto/sha3" ) @@ -36,7 +36,7 @@ func RawHash(data interface{}) []byte { return hash.Sum(buf) } -func BlakeHash(data interface{}) []byte { +func ShaHash(data interface{}) []byte { var databuf []byte switch dataImpl := data.(type) { case []byte: @@ -48,7 +48,7 @@ func BlakeHash(data interface{}) []byte { default: panic("unknown type") } - hash := blake3.New() + hash := sha256.New() _, _ = hash.Write(databuf) return hash.Sum(nil) } diff --git a/core/util/fixed_merkle_tree.go b/core/util/fixed_merkle_tree.go index 5e3ab1bd2..f076034b5 100644 --- a/core/util/fixed_merkle_tree.go +++ b/core/util/fixed_merkle_tree.go @@ -10,7 +10,7 @@ import ( goError "errors" "github.com/0chain/errors" - "github.com/zeebo/blake3" + "github.com/minio/sha256-simd" ) const ( @@ -20,6 +20,16 @@ const ( FixedMTDepth = 11 ) +var ( + leafPool = sync.Pool{ + New: func() interface{} { + return &leaf{ + h: sha256.New(), + } + }, + } +) + type leaf struct { h hash.Hash } @@ -37,9 +47,14 @@ func (l *leaf) Write(b []byte) (int, error) { } func getNewLeaf() *leaf { - return &leaf{ - h: blake3.New(), + l, ok := leafPool.Get().(*leaf) + if !ok { + return &leaf{ + h: sha256.New(), + } } + l.h.Reset() + return l } // FixedMerkleTree A trusted mekerle tree for outsourcing attack protection. see section 1.8 on whitepager @@ -165,6 +180,7 @@ func (fmt *FixedMerkleTree) CalculateMerkleRoot() { nodes := make([][]byte, len(fmt.Leaves)) for i := 0; i < len(nodes); i++ { nodes[i] = fmt.Leaves[i].GetHashBytes() + leafPool.Put(fmt.Leaves[i]) } for i := 0; i < FixedMTDepth; i++ { diff --git a/core/util/merkle_tree_interface.go b/core/util/merkle_tree_interface.go index 41afeb0f3..cb3e773e6 100644 --- a/core/util/merkle_tree_interface.go +++ b/core/util/merkle_tree_interface.go @@ -4,7 +4,7 @@ import ( "encoding/hex" "github.com/0chain/gosdk/core/encryption" - "github.com/zeebo/blake3" + "github.com/minio/sha256-simd" ) /*MerkleTreeI - a merkle tree interface required for constructing and providing verification */ @@ -41,7 +41,7 @@ func MHashBytes(h1, h2 []byte) []byte { buf := make([]byte, len(h1)+len(h2)) copy(buf, h1) copy(buf[len(h1):], h2) - hash := blake3.New() + hash := sha256.New() _, _ = hash.Write(buf) return hash.Sum(nil) } diff --git a/core/util/validation_tree.go b/core/util/validation_tree.go index c5d0e0039..b7d94bdf7 100644 --- a/core/util/validation_tree.go +++ b/core/util/validation_tree.go @@ -9,7 +9,7 @@ import ( "math" "sync" - "github.com/zeebo/blake3" + "github.com/minio/sha256-simd" ) const ( @@ -99,7 +99,7 @@ func (v *ValidationTree) calculateRoot() { depth := v.CalculateDepth() nodes := make([][]byte, totalLeaves) copy(nodes, v.leaves) - h := blake3.New() + h := sha256.New() for i := 0; i < depth; i++ { if len(nodes) == 1 { @@ -154,7 +154,7 @@ func NewValidationTree(dataSize int64) *ValidationTree { return &ValidationTree{ dataSize: dataSize, - h: blake3.New(), + h: sha256.New(), leaves: make([][]byte, totalLeaves), } } @@ -223,7 +223,7 @@ If client had required data from 2-9 then blobber would have to provide: func (m *MerklePathForMultiLeafVerification) VerifyMultipleBlocks(data []byte) error { hashes := make([][]byte, 0) - h := blake3.New() + h := sha256.New() // Calculate hashes from the data responded from the blobber. for i := 0; i < len(data); i += MaxMerkleLeavesSize { endIndex := i + MaxMerkleLeavesSize @@ -270,7 +270,7 @@ func (m *MerklePathForMultiLeafVerification) VerifyMultipleBlocks(data []byte) e func (m *MerklePathForMultiLeafVerification) calculateIntermediateHashes(hashes [][]byte) [][]byte { newHashes := make([][]byte, 0) - h := blake3.New() + h := sha256.New() if len(hashes)%2 == 0 { for i := 0; i < len(hashes); i += 2 { h.Reset() diff --git a/core/util/validation_tree_test.go b/core/util/validation_tree_test.go index 9775614dc..149aba444 100644 --- a/core/util/validation_tree_test.go +++ b/core/util/validation_tree_test.go @@ -8,8 +8,8 @@ import ( "math" "testing" + "github.com/minio/sha256-simd" "github.com/stretchr/testify/require" - "github.com/zeebo/blake3" ) const ( @@ -144,7 +144,7 @@ func calculateValidationMerkleRoot(data []byte) []byte { if j > len(data) { j = len(data) } - h := blake3.New() + h := sha256.New() _, _ = h.Write(data[i:j]) hashes = append(hashes, h.Sum(nil)) } @@ -156,19 +156,19 @@ func calculateValidationMerkleRoot(data []byte) []byte { newHashes := make([][]byte, 0) if len(hashes)%2 == 0 { for i := 0; i < len(hashes); i += 2 { - h := blake3.New() + h := sha256.New() _, _ = h.Write(hashes[i]) _, _ = h.Write(hashes[i+1]) newHashes = append(newHashes, h.Sum(nil)) } } else { for i := 0; i < len(hashes)-1; i += 2 { - h := blake3.New() + h := sha256.New() _, _ = h.Write(hashes[i]) _, _ = h.Write(hashes[i+1]) newHashes = append(newHashes, h.Sum(nil)) } - h := blake3.New() + h := sha256.New() _, _ = h.Write(hashes[len(hashes)-1]) newHashes = append(newHashes, h.Sum(nil)) } @@ -191,7 +191,7 @@ func calculateValidationRootAndNodes(b []byte, startInd, endInd int) ( hashes := make([][]byte, 0) nodesData := make([]byte, 0) - h := blake3.New() + h := sha256.New() for i := 0; i < len(b); i += MaxMerkleLeavesSize { j := i + MaxMerkleLeavesSize if j > len(b) { @@ -212,7 +212,7 @@ func calculateValidationRootAndNodes(b []byte, startInd, endInd int) ( newHashes := make([][]byte, 0) if len(hashes)%2 == 0 { for i := 0; i < len(hashes); i += 2 { - h := blake3.New() + h := sha256.New() _, _ = h.Write(hashes[i]) _, _ = h.Write(hashes[i+1]) nodesData = append(nodesData, hashes[i]...) @@ -221,14 +221,14 @@ func calculateValidationRootAndNodes(b []byte, startInd, endInd int) ( } } else { for i := 0; i < len(hashes)-1; i += 2 { - h := blake3.New() + h := sha256.New() _, _ = h.Write(hashes[i]) _, _ = h.Write(hashes[i+1]) nodesData = append(nodesData, hashes[i]...) nodesData = append(nodesData, hashes[i+1]...) newHashes = append(newHashes, h.Sum(nil)) } - h := blake3.New() + h := sha256.New() _, _ = h.Write(hashes[len(hashes)-1]) nodesData = append(nodesData, hashes[len(hashes)-1]...) newHashes = append(newHashes, h.Sum(nil)) diff --git a/go.mod b/go.mod index 604cdf9c5..58ef1951a 100644 --- a/go.mod +++ b/go.mod @@ -45,7 +45,6 @@ require ( require ( github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d github.com/minio/sha256-simd v1.0.1 - github.com/zeebo/blake3 v0.2.3 ) require ( diff --git a/go.sum b/go.sum index 1fe9b61ce..bf726d25b 100644 --- a/go.sum +++ b/go.sum @@ -339,7 +339,6 @@ github.com/klauspost/compress v1.12.3/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8 github.com/klauspost/compress v1.16.0 h1:iULayQNOReoYUe+1qtKOqw9CwJv3aNQu8ivo7lw1HU4= github.com/klauspost/compress v1.16.0/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/cpuid v0.0.0-20170728055534-ae7887de9fa5/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= -github.com/klauspost/cpuid/v2 v2.0.12/go.mod h1:g2LTdtYhdyuGPqyWyv7qRAmj1WBqxuObKfj5c0PQa7c= github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk= github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= github.com/klauspost/crc32 v0.0.0-20161016154125-cb6bfca970f6/go.mod h1:+ZoRqAPRLkC4NPOvfYeR5KNOrY6TD+/sAC3HXPZgDYg= @@ -540,12 +539,6 @@ github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9dec github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yusufpapurcu/wmi v1.2.2 h1:KBNDSne4vP5mbSWnJbO+51IMOXJB67QiYCSBrubbPRg= github.com/yusufpapurcu/wmi v1.2.2/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= -github.com/zeebo/assert v1.1.0 h1:hU1L1vLTHsnO8x8c9KAR5GmM5QscxHg5RNU5z5qbUWY= -github.com/zeebo/assert v1.1.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0= -github.com/zeebo/blake3 v0.2.3 h1:TFoLXsjeXqRNFxSbk35Dk4YtszE/MQQGK10BH4ptoTg= -github.com/zeebo/blake3 v0.2.3/go.mod h1:mjJjZpnsyIVtVgTOSpJ9vmRE4wgDeyt2HU3qXvvKCaQ= -github.com/zeebo/pcg v1.0.1 h1:lyqfGeWiv4ahac6ttHs+I5hwtH/+1mrhlCtVNQM2kHo= -github.com/zeebo/pcg v1.0.1/go.mod h1:09F0S9iiKrwn9rlI5yjLkmrug154/YRW6KnnXVDM/l4= go.dedis.ch/fixbuf v1.0.3 h1:hGcV9Cd/znUxlusJ64eAlExS+5cJDIyTyEG+otu5wQs= go.dedis.ch/fixbuf v1.0.3/go.mod h1:yzJMt34Wa5xD37V5RTdmp38cz3QhMagdGoem9anUalw= go.dedis.ch/kyber/v3 v3.0.4/go.mod h1:OzvaEnPvKlyrWyp3kGXlFdp7ap1VC6RkZDTaPikqhsQ= diff --git a/wasmsdk/blobber.go b/wasmsdk/blobber.go index b79ec55c9..cd9d59338 100644 --- a/wasmsdk/blobber.go +++ b/wasmsdk/blobber.go @@ -624,7 +624,7 @@ func multiUpload(jsonBulkUploadOptions string) (MultiUploadResult, error) { numBlocks = 100 } if allocationObj.DataShards > 7 { - numBlocks = 50 + numBlocks = 75 } options := []sdk.ChunkedUploadOption{ sdk.WithThumbnail(option.ThumbnailBytes.Buffer), diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 93e87320c..06331fb00 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -237,8 +237,8 @@ func GetWritePriceRange() (PriceRange, error) { func SetWasm() { IsWasm = true - BatchSize = 3 - MultiOpBatchSize = 5 + BatchSize = 5 + MultiOpBatchSize = 7 } func getPriceRange(name string) (PriceRange, error) { diff --git a/zboxcore/sdk/chunked_upload_hasher.go b/zboxcore/sdk/chunked_upload_hasher.go index 650958103..93e0de290 100644 --- a/zboxcore/sdk/chunked_upload_hasher.go +++ b/zboxcore/sdk/chunked_upload_hasher.go @@ -1,12 +1,11 @@ package sdk import ( + "crypto/md5" "encoding/hex" "hash" "sync" - "github.com/minio/sha256-simd" - "github.com/0chain/errors" "github.com/0chain/gosdk/constants" "github.com/0chain/gosdk/core/util" @@ -39,7 +38,7 @@ type hasher struct { // CreateHasher creat Hasher instance func CreateHasher(dataSize int64) Hasher { return &hasher{ - File: sha256.New(), + File: md5.New(), FixedMT: util.NewFixedMerkleTree(), ValidationMT: util.NewValidationTree(dataSize), } diff --git a/zboxcore/sdk/chunked_upload_option.go b/zboxcore/sdk/chunked_upload_option.go index 38872052c..5d1809ec3 100644 --- a/zboxcore/sdk/chunked_upload_option.go +++ b/zboxcore/sdk/chunked_upload_option.go @@ -1,6 +1,7 @@ package sdk import ( + "crypto/md5" "encoding/hex" "math" "os" @@ -8,7 +9,6 @@ import ( "github.com/0chain/gosdk/zboxcore/zboxutil" "github.com/klauspost/reedsolomon" - "github.com/minio/sha256-simd" ) // ChunkedUploadOption set stream option @@ -26,7 +26,7 @@ func WithThumbnail(buf []byte) ChunkedUploadOption { su.thumbnailBytes = buf su.fileMeta.ActualThumbnailSize = int64(len(buf)) - thumbnailHasher := sha256.New() + thumbnailHasher := md5.New() thumbnailHasher.Write(buf) su.fileMeta.ActualThumbnailHash = hex.EncodeToString(thumbnailHasher.Sum(nil)) diff --git a/zboxcore/sdk/downloadworker.go b/zboxcore/sdk/downloadworker.go index abc58c18f..eed5b6dbb 100644 --- a/zboxcore/sdk/downloadworker.go +++ b/zboxcore/sdk/downloadworker.go @@ -3,6 +3,7 @@ package sdk import ( "bytes" "context" + "crypto/md5" "encoding/hex" "encoding/json" "fmt" @@ -17,8 +18,6 @@ import ( "sync/atomic" "time" - "github.com/minio/sha256-simd" - "github.com/0chain/errors" "github.com/0chain/gosdk/core/common" "github.com/0chain/gosdk/core/sys" @@ -428,7 +427,7 @@ func (req *DownloadRequest) processDownload(ctx context.Context) { ) if !req.shouldVerify && (startBlock == 0 && endBlock == chunksPerShard) { - actualFileHasher = sha256.New() + actualFileHasher = md5.New() hashDataChan = make(chan []byte, n) hashWg = &sync.WaitGroup{} hashWg.Add(1) diff --git a/zboxcore/zboxutil/transport.go b/zboxcore/zboxutil/transport.go index 0a2bf81be..09bc4337d 100644 --- a/zboxcore/zboxutil/transport.go +++ b/zboxcore/zboxutil/transport.go @@ -21,6 +21,5 @@ var DefaultTransport = &http.Transport{ TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, MaxIdleConnsPerHost: 100, - ReadBufferSize: 34 * 1024 * 1024, - WriteBufferSize: 34 * 1024 * 1024, + WriteBufferSize: 256 * 1024, } From 218d3edd1a43dce1cfd1a700adcb33fb03a883f9 Mon Sep 17 00:00:00 2001 From: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Date: Mon, 4 Dec 2023 02:54:50 +0530 Subject: [PATCH 117/134] Fix iso header (#1314) * add ISO check * remove filename field from authticket * fix typo * log auth token * cleanup --- zboxcore/sdk/allocation.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 06331fb00..10cc23b1b 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -2124,7 +2124,7 @@ func (a *Allocation) downloadFromAuthTicket(fileHandler sys.File, authTicket str if len(a.Blobbers) == 0 { return noBLOBBERS } - + at.FileName = "" downloadReq := &DownloadRequest{Consensus: Consensus{RWMutex: &sync.RWMutex{}}} downloadReq.maskMu = &sync.Mutex{} downloadReq.allocationID = a.ID From 4d5dc8fece074b6de3331102ae8d1b412d3422a3 Mon Sep 17 00:00:00 2001 From: Jayash Satolia <73050737+Jayashsatolia403@users.noreply.github.com> Date: Mon, 4 Dec 2023 03:00:24 +0530 Subject: [PATCH 118/134] Fix zboxcore min submit (#1315) * Fix zboxcore min submit * Fix min submit and min confirmation default configs * Fix unit tests * Fix unit tests --- core/conf/config.go | 4 ++-- core/conf/config_test.go | 4 ++-- wasmsdk/demo/index.html | 4 ++-- zboxcore/blockchain/entity.go | 34 ++++++++++++++++++++++++++++++++-- zboxcore/sdk/sdk.go | 3 ++- zcncore/wallet_base.go | 4 ++-- 6 files changed, 42 insertions(+), 11 deletions(-) diff --git a/core/conf/config.go b/core/conf/config.go index aae29ff2a..5b770768e 100644 --- a/core/conf/config.go +++ b/core/conf/config.go @@ -13,9 +13,9 @@ import ( const ( // DefaultMinSubmit default value for min_submit - DefaultMinSubmit = 50 + DefaultMinSubmit = 10 // DefaultMinConfirmation default value for min_confirmation - DefaultMinConfirmation = 50 + DefaultMinConfirmation = 10 // DefaultMaxTxnQuery default value for max_txn_query DefaultMaxTxnQuery = 5 // DefaultConfirmationChainLength default value for confirmation_chain_length diff --git a/core/conf/config_test.go b/core/conf/config_test.go index a4d07142f..3eae68b8b 100644 --- a/core/conf/config_test.go +++ b/core/conf/config_test.go @@ -75,7 +75,7 @@ func TestLoadConfig(t *testing.T) { return mockDefaultReader() }, run: func(r *require.Assertions, cfg Config) { - r.Equal(50, cfg.MinSubmit) + r.Equal(10, cfg.MinSubmit) }, }, { @@ -109,7 +109,7 @@ func TestLoadConfig(t *testing.T) { return mockDefaultReader() }, run: func(r *require.Assertions, cfg Config) { - r.Equal(50, cfg.MinConfirmation) + r.Equal(10, cfg.MinConfirmation) }, }, { diff --git a/wasmsdk/demo/index.html b/wasmsdk/demo/index.html index c8102b285..d7eee1b5d 100644 --- a/wasmsdk/demo/index.html +++ b/wasmsdk/demo/index.html @@ -202,8 +202,8 @@

please download zcn.wasm from https://github.com/0chain/gosdk/releases/lates const networkConfig = { chainId: '0afc093ffb509f059c55478bc1a60351cef7b4e9c008a53a6cc8241ca8617dfe', signatureScheme: 'bls0chain', - minConfirmation: 50, - minSubmit: 50, + minConfirmation: 10, + minSubmit: 10, confirmationChainLength: 3, } diff --git a/zboxcore/blockchain/entity.go b/zboxcore/blockchain/entity.go index 8929ae858..77f4efe7d 100644 --- a/zboxcore/blockchain/entity.go +++ b/zboxcore/blockchain/entity.go @@ -2,6 +2,9 @@ package blockchain import ( "encoding/json" + "github.com/0chain/gosdk/core/util" + "math" + "sync" "sync/atomic" "github.com/0chain/gosdk/core/common" @@ -9,6 +12,33 @@ import ( "github.com/0chain/gosdk/core/node" ) +var miners []string +var mGuard sync.Mutex + +func getMinMinersSubmit() int { + minMiners := util.MaxInt(calculateMinRequired(float64(chain.MinSubmit), float64(len(chain.Miners))/100), 1) + return minMiners +} + +func calculateMinRequired(minRequired, percent float64) int { + return int(math.Ceil(minRequired * percent)) +} + +func GetStableMiners() []string { + mGuard.Lock() + defer mGuard.Unlock() + if len(miners) == 0 { + miners = util.GetRandom(chain.Miners, getMinMinersSubmit()) + } + + return miners +} +func ResetStableMiners() { + mGuard.Lock() + defer mGuard.Unlock() + miners = util.GetRandom(chain.Miners, getMinMinersSubmit()) +} + type ChainConfig struct { BlockWorker string Sharders []string @@ -82,8 +112,8 @@ func init() { chain = &ChainConfig{ MaxTxnQuery: 5, QuerySleepTime: 5, - MinSubmit: 50, - MinConfirmation: 50, + MinSubmit: 10, + MinConfirmation: 10, } } diff --git a/zboxcore/sdk/sdk.go b/zboxcore/sdk/sdk.go index b78856d9b..96f045275 100644 --- a/zboxcore/sdk/sdk.go +++ b/zboxcore/sdk/sdk.go @@ -1455,10 +1455,11 @@ func smartContractTxnValueFee(sn transaction.SmartContractTxnData, l.Logger.Info(msg) l.Logger.Info("estimated txn fee: ", txn.TransactionFee) - err = transaction.SendTransactionSync(txn, blockchain.GetMiners()) + err = transaction.SendTransactionSync(txn, blockchain.GetStableMiners()) if err != nil { l.Logger.Info("transaction submission failed", zap.Error(err)) node.Cache.Evict(txn.ClientID) + blockchain.ResetStableMiners() return } diff --git a/zcncore/wallet_base.go b/zcncore/wallet_base.go index 98bc9cc4b..afb85aa98 100644 --- a/zcncore/wallet_base.go +++ b/zcncore/wallet_base.go @@ -111,8 +111,8 @@ const ( const consensusThresh = 25 const ( - defaultMinSubmit = int(50) - defaultMinConfirmation = int(50) + defaultMinSubmit = int(10) + defaultMinConfirmation = int(10) defaultConfirmationChainLength = int(3) defaultTxnExpirationSeconds = 60 defaultWaitSeconds = 3 * time.Second From f45ed6ba922b11b94f02a19b334eab7d805b677e Mon Sep 17 00:00:00 2001 From: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Date: Mon, 4 Dec 2023 13:46:43 +0530 Subject: [PATCH 119/134] Revert "Fix iso header (#1314)" (#1317) This reverts commit 218d3edd1a43dce1cfd1a700adcb33fb03a883f9. --- zboxcore/sdk/allocation.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 10cc23b1b..06331fb00 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -2124,7 +2124,7 @@ func (a *Allocation) downloadFromAuthTicket(fileHandler sys.File, authTicket str if len(a.Blobbers) == 0 { return noBLOBBERS } - at.FileName = "" + downloadReq := &DownloadRequest{Consensus: Consensus{RWMutex: &sync.RWMutex{}}} downloadReq.maskMu = &sync.Mutex{} downloadReq.allocationID = a.ID From f2d30c531a18f83b9a81e768548d486ac6387508 Mon Sep 17 00:00:00 2001 From: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Date: Tue, 5 Dec 2023 02:26:40 +0530 Subject: [PATCH 120/134] Add upload for empty file (#1316) * add upload for empty file * fix hash * check ref * fix actual size --- zboxcore/sdk/allocation.go | 12 +++++++++++- zboxcore/sdk/chunked_upload.go | 4 +++- zboxcore/sdk/chunked_upload_option.go | 6 ++++++ zboxcore/sdk/downloadworker.go | 7 +++++++ 4 files changed, 27 insertions(+), 2 deletions(-) diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 06331fb00..9c92bfb3a 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -60,6 +60,10 @@ const ( CanRenameMask = uint16(32) // 0010 0000 ) +const ( + emptyFileDataHash = "d41d8cd98f00b204e9800998ecf8427e" +) + // Expected success rate is calculated (NumDataShards)*100/(NumDataShards+NumParityShards) var GetFileInfo = func(localpath string) (os.FileInfo, error) { @@ -466,7 +470,6 @@ func (a *Allocation) EncryptAndUploadFileWithThumbnail( } func (a *Allocation) StartMultiUpload(workdir string, localPaths []string, fileNames []string, thumbnailPaths []string, encrypts []bool, chunkNumbers []int, remotePaths []string, isUpdate []bool, isWebstreaming []bool, status StatusCallback) error { - l.Logger.Debug("Initialize batch: ", BatchSize, MultiOpBatchSize) if len(localPaths) != len(thumbnailPaths) { return errors.New("invalid_value", "length of localpaths and thumbnailpaths must be equal") } @@ -556,6 +559,13 @@ func (a *Allocation) StartMultiUpload(workdir string, localPaths []string, fileN Workdir: workdir, RemotePath: fileMeta.RemotePath, } + if fileMeta.ActualSize == 0 { + byteReader := bytes.NewReader([]byte( + emptyFileDataHash)) + operationRequests[idx].FileReader = byteReader + operationRequests[idx].Opts = append(operationRequests[idx].Opts, WithActualHash(emptyFileDataHash)) + operationRequests[idx].FileMeta.ActualSize = int64(len(emptyFileDataHash)) + } if isUpdate[idx] { operationRequests[idx].OperationType = constants.FileOperationUpdate } diff --git a/zboxcore/sdk/chunked_upload.go b/zboxcore/sdk/chunked_upload.go index 826125714..e6846cc75 100644 --- a/zboxcore/sdk/chunked_upload.go +++ b/zboxcore/sdk/chunked_upload.go @@ -409,7 +409,9 @@ func (su *ChunkedUpload) process() error { su.progress.UploadLength += chunks.totalReadSize if chunks.isFinal { - su.fileMeta.ActualHash, err = su.chunkReader.GetFileHash() + if su.fileMeta.ActualHash == "" { + su.fileMeta.ActualHash, err = su.chunkReader.GetFileHash() + } if err != nil { if su.statusCallback != nil { su.statusCallback.Error(su.allocationObj.ID, su.fileMeta.RemotePath, su.opCode, err) diff --git a/zboxcore/sdk/chunked_upload_option.go b/zboxcore/sdk/chunked_upload_option.go index 5d1809ec3..a3fc3d850 100644 --- a/zboxcore/sdk/chunked_upload_option.go +++ b/zboxcore/sdk/chunked_upload_option.go @@ -97,3 +97,9 @@ func WithEncryptedPoint(point string) ChunkedUploadOption { su.encryptedKeyPoint = point } } + +func WithActualHash(hash string) ChunkedUploadOption { + return func(su *ChunkedUpload) { + su.fileMeta.ActualHash = hash + } +} diff --git a/zboxcore/sdk/downloadworker.go b/zboxcore/sdk/downloadworker.go index eed5b6dbb..d1788c706 100644 --- a/zboxcore/sdk/downloadworker.go +++ b/zboxcore/sdk/downloadworker.go @@ -368,6 +368,13 @@ func (req *DownloadRequest) processDownload(ctx context.Context) { op = opThumbnailDownload } fRef := req.fRef + if fRef != nil && fRef.ActualFileHash == emptyFileDataHash { + if req.statusCallback != nil { + req.statusCallback.Completed( + req.allocationID, remotePathCB, fRef.Name, "", len(emptyFileDataHash), op) + } + return + } size, chunksPerShard, blocksPerShard := req.size, req.chunksPerShard, req.blocksPerShard logger.Logger.Info( From 2a794a0835ed64214b233570a43666f32b470598 Mon Sep 17 00:00:00 2001 From: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Date: Tue, 5 Dec 2023 13:27:20 +0530 Subject: [PATCH 121/134] fix empty upload (#1320) --- zboxcore/sdk/allocation.go | 8 +------- zboxcore/sdk/upload_worker.go | 8 ++++++++ 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 9c92bfb3a..922350615 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -559,13 +559,7 @@ func (a *Allocation) StartMultiUpload(workdir string, localPaths []string, fileN Workdir: workdir, RemotePath: fileMeta.RemotePath, } - if fileMeta.ActualSize == 0 { - byteReader := bytes.NewReader([]byte( - emptyFileDataHash)) - operationRequests[idx].FileReader = byteReader - operationRequests[idx].Opts = append(operationRequests[idx].Opts, WithActualHash(emptyFileDataHash)) - operationRequests[idx].FileMeta.ActualSize = int64(len(emptyFileDataHash)) - } + if isUpdate[idx] { operationRequests[idx].OperationType = constants.FileOperationUpdate } diff --git a/zboxcore/sdk/upload_worker.go b/zboxcore/sdk/upload_worker.go index 08986eda5..b14552361 100644 --- a/zboxcore/sdk/upload_worker.go +++ b/zboxcore/sdk/upload_worker.go @@ -1,6 +1,7 @@ package sdk import ( + "bytes" "io" thrown "github.com/0chain/errors" @@ -118,6 +119,13 @@ func (uo *UploadOperation) Error(allocObj *Allocation, consensus int, err error) func NewUploadOperation(workdir string, allocObj *Allocation, connectionID string, fileMeta FileMeta, fileReader io.Reader, isUpdate, isWebstreaming bool, opts ...ChunkedUploadOption) (*UploadOperation, string, error) { uo := &UploadOperation{} + if fileMeta.ActualSize == 0 { + byteReader := bytes.NewReader([]byte( + emptyFileDataHash)) + fileReader = byteReader + opts = append(opts, WithActualHash(emptyFileDataHash)) + fileMeta.ActualSize = int64(len(emptyFileDataHash)) + } cu, err := CreateChunkedUpload(workdir, allocObj, fileMeta, fileReader, isUpdate, false, isWebstreaming, connectionID, opts...) if err != nil { return nil, "", err From 223ba2ce5f3a41c38254fb317b8f510dd0f46a71 Mon Sep 17 00:00:00 2001 From: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Date: Wed, 6 Dec 2023 03:30:03 +0530 Subject: [PATCH 122/134] fix read auth ticket (#1319) --- zboxcore/sdk/download_reqeust_header.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/zboxcore/sdk/download_reqeust_header.go b/zboxcore/sdk/download_reqeust_header.go index cd0e24e52..3606e4618 100644 --- a/zboxcore/sdk/download_reqeust_header.go +++ b/zboxcore/sdk/download_reqeust_header.go @@ -1,6 +1,7 @@ package sdk import ( + "encoding/base64" "fmt" "net/http" "strconv" @@ -38,7 +39,8 @@ func (h *DownloadRequestHeader) ToHeader(req *http.Request) { } if h.AuthToken != nil { - req.Header.Set("X-Auth-Token", string(h.AuthToken)) + token := base64.StdEncoding.EncodeToString(h.AuthToken) + req.Header.Set("X-Auth-Token", token) } if h.DownloadMode != "" { From 60d8a76df1e6168ee62806310fb4aa916d294d1c Mon Sep 17 00:00:00 2001 From: Manohar Reddy Date: Wed, 6 Dec 2023 17:51:09 +0000 Subject: [PATCH 123/134] allocation validation for data parity shards (#1321) --- zboxcore/sdk/sdk.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/zboxcore/sdk/sdk.go b/zboxcore/sdk/sdk.go index 96f045275..fffe270f7 100644 --- a/zboxcore/sdk/sdk.go +++ b/zboxcore/sdk/sdk.go @@ -1000,6 +1000,10 @@ func CreateAllocationForOwner( return "", 0, nil, errors.New("invalid_lock", "int64 overflow on lock value") } + if datashards < 1 || parityshards < 1 { + return "", 0, nil, errors.New("allocation_validation_failed", "atleast 1 data and 1 parity shards are required") + } + allocationRequest, err := getNewAllocationBlobbers( datashards, parityshards, size, readPrice, writePrice, preferredBlobberIds) if err != nil { From c26e5713eb46f940ee605251e8e32f34875ed617 Mon Sep 17 00:00:00 2001 From: Manohar Reddy Date: Sun, 10 Dec 2023 14:51:20 +0000 Subject: [PATCH 124/134] fix git action to raise PRs to update gosdk (#1313) * test gosdk update * test-gosdk-update * use binary operators instead of terinary * use github.ref * use github ref * add branch name * use quotes * prepare for PR * test work flow dispatch * test extract branch * print env * prepare for PR --- .github/workflows/sdk-release.yml | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/.github/workflows/sdk-release.yml b/.github/workflows/sdk-release.yml index c76ed6926..32e66f37b 100644 --- a/.github/workflows/sdk-release.yml +++ b/.github/workflows/sdk-release.yml @@ -6,14 +6,16 @@ concurrency: on: push: - branches: [ master, staging, qa, sprint-* ] - tags: - - 'v*.*.*' + branches: [ master, staging, qa, sprint-*] workflow_dispatch: inputs: version: description: '0Chain SDK version' required: true + base: + description: the target branch to which PRs should be raised + default: sprint-1.11 + required: true env: ACTIONS_ALLOW_UNSECURE_COMMANDS: true @@ -34,19 +36,29 @@ jobs: fail-fast: false max-parallel: 1 matrix: - repo: [0nft, 0box, 0dns, zwalletcli, zboxcli, blobber, zs3server, s3-migration, token_bridge_authserver ] + repo: [0box, 0dns, zwalletcli, zboxcli, blobber, zs3server, s3-migration, token_bridge_authserver ] needs: [ release ] runs-on: [self-hosted, build] steps: + - name: Extract branch or version name + shell: bash + run: | + GITHUB_REF=$(echo $GITHUB_REF | sed -e "s#refs/heads/##g") + echo $GITHUB_REF + echo ${{ github.event_name }} + echo "branch=${{ github.event_name == 'workflow_dispatch' && github.event.inputs.version || '$GITHUB_REF' }}" >> $GITHUB_ENV + echo "base=${{ github.event_name == 'workflow_dispatch' && github.event.inputs.base || '$GITHUB_REF' }}" >> $GITHUB_ENV + id: extract_branch + - name: Create PR on ${{ matrix.repo }} - uses: convictional/trigger-workflow-and-wait@v1.3.0 + uses: convictional/trigger-workflow-and-wait@v1.6.1 with: owner: 0chain repo: ${{ matrix.repo }} - ref: ${{ github.head_ref || github.ref_name }} + ref: staging github_token: ${{ secrets.GOSDK }} workflow_file_name: gosdk.yml - inputs: ${{ needs.build.outputs.SDK }} + client_payload: '{"gosdk": "${{ env.branch }}", "base": "${{ env.base }}"}' propagate_failure: true trigger_workflow: true wait_workflow: true From 9b9b8e0d5c896fabbefb7d243ffb304e443a89a1 Mon Sep 17 00:00:00 2001 From: Yaroslav Svitlytskyi <53532703+YarikRevich@users.noreply.github.com> Date: Sun, 10 Dec 2023 17:49:18 +0100 Subject: [PATCH 125/134] feature: added custom block number during Tenderly fork creation (#1323) --- .github/workflows/tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index deb91074b..1245bfa55 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -119,7 +119,7 @@ jobs: echo "TENDERLY_CREATION_INFO=$(curl -X POST \ -H "x-access-key: ${{ secrets.TENDERLY_SECRET }}" \ -H "Content-Type: application/json" \ - -d '{"alias":"mainnet-dev-${{ env.RUNNER_NUMBER }}-${{ github.run_id }}", "description":"", "network_id":"1"}' \ + -d '{"alias":"mainnet-dev-${{ env.RUNNER_NUMBER }}-${{ github.run_id }}${{ github.run_attempt }}", "description":"", "block_number": 18539779, "network_id":"1"}' \ https://api.tenderly.co/api/v1/account/zus_network/project/project/fork)" >> $GITHUB_ENV - name: "Parse Tenderly fork creation transaction result" From aa9db0adc2992c0c370d5a14e4b9b677fa97ad82 Mon Sep 17 00:00:00 2001 From: Yury Date: Mon, 11 Dec 2023 17:10:15 +0200 Subject: [PATCH 126/134] Fix/retry tx on nonce error (#1322) * Revert "experiment" This reverts commit 050270f52815dcd930f760f20a4c7e3e669d73fb. * Revert "experiment" This reverts commit d4821f8e28c4efce59775129b4f25eaa1df2905d. * Revert "experiment" This reverts commit 9f65b2eef30528662b59482a6c59d6a633f1ff77. * Revert "experiment" This reverts commit 6313cb8a49d211ab8a6c476ca839922be7c31288. * Revert "experiment" This reverts commit b6be0b51767f39cb53a9439c3a34fe2f828b2dfc. * Revert "experiment" This reverts commit 68d41905a3aaf1c094d50f7b418349d7c78663cc. * Revert "experiment" This reverts commit 3a23f3f33b9446cf5711f950b0cd80a40993e429. * Revert "experiment" This reverts commit 6b6578bb857c9e4351db941fc84e65fac0994c15. * Revert "experiment" This reverts commit 65a0152adc10754977a479e09cdb8d577ca8aefb. * Revert "experiment" This reverts commit 6834b058a99bba80621c756292f7f4205b24e936. * Revert "experiment" This reverts commit 8446894c579f5acd14db1b09b5966f92ca1588be. * Revert "hotfix" This reverts commit 48cf793a70f754f44c662d839bdde4e191ec2748. * Revert "hotfix" This reverts commit 895c7f0012837d2f9a0cbfdcddf47f8dbe0d13b7. * Revert "added logging" This reverts commit fafce3c9b90c0863e574a2609a202f962ecb90ac. * Revert "added logging" This reverts commit 10b6a4afbdecc1e8a201d5ac80c4d12f0b97c411. * retry failed transaction in zbox with nonce error --- core/transaction/entity.go | 25 +++++++++++++++++++++---- zboxcore/sdk/sdk.go | 25 ++++++++++++++++++------- 2 files changed, 39 insertions(+), 11 deletions(-) diff --git a/core/transaction/entity.go b/core/transaction/entity.go index 3f2a2879e..358450c0c 100644 --- a/core/transaction/entity.go +++ b/core/transaction/entity.go @@ -259,22 +259,39 @@ func (t *Transaction) VerifyTransaction(verifyHandler VerifyFunc) (bool, error) func SendTransactionSync(txn *Transaction, miners []string) error { wg := sync.WaitGroup{} wg.Add(len(miners)) - - failureCount := 0 + fails := make(chan error, len(miners)) for _, miner := range miners { url := fmt.Sprintf("%v/%v", miner, TXN_SUBMIT_URL) go func() { _, err := sendTransactionToURL(url, txn, &wg) if err != nil { - failureCount++ + fails <- err } }() //nolint } wg.Wait() + close(fails) + + failureCount := 0 + messages := make(map[string]int) + for e := range fails { + if e != nil { + failureCount++ + messages[e.Error()] += 1 + } + } + + max := 0 + dominant := "" + for m, s := range messages { + if s > max { + dominant = m + } + } if failureCount == len(miners) { - return errors.New("transaction_send_error", "failed to send transaction to all miners") + return errors.New("transaction_send_error", dominant) } return nil diff --git a/zboxcore/sdk/sdk.go b/zboxcore/sdk/sdk.go index fffe270f7..db0cd60f9 100644 --- a/zboxcore/sdk/sdk.go +++ b/zboxcore/sdk/sdk.go @@ -9,6 +9,7 @@ import ( "math" "net/http" "strconv" + "strings" "time" "github.com/0chain/common/core/currency" @@ -223,7 +224,7 @@ func ReadPoolLock(tokens, fee uint64) (hash string, nonce int64, err error) { Name: transaction.STORAGESC_READ_POOL_LOCK, InputArgs: nil, } - hash, _, nonce, _, err = smartContractTxnValueFee(sn, tokens, fee) + hash, _, nonce, _, err = smartContractTxnValueFeeWithRetry(sn, tokens, fee) return } @@ -237,7 +238,7 @@ func ReadPoolUnlock(fee uint64) (hash string, nonce int64, err error) { Name: transaction.STORAGESC_READ_POOL_UNLOCK, InputArgs: nil, } - hash, _, nonce, _, err = smartContractTxnValueFee(sn, 0, fee) + hash, _, nonce, _, err = smartContractTxnValueFeeWithRetry(sn, 0, fee) return } @@ -379,7 +380,7 @@ func StakePoolLock(providerType ProviderType, providerID string, value, fee uint Name: transaction.STORAGESC_STAKE_POOL_LOCK, InputArgs: &spr, } - hash, _, nonce, _, err = smartContractTxnValueFee(sn, value, fee) + hash, _, nonce, _, err = smartContractTxnValueFeeWithRetry(sn, value, fee) return } @@ -422,7 +423,7 @@ func StakePoolUnlock(providerType ProviderType, providerID string, fee uint64) ( } var out string - if _, out, nonce, _, err = smartContractTxnValueFee(sn, 0, fee); err != nil { + if _, out, nonce, _, err = smartContractTxnValueFeeWithRetry(sn, 0, fee); err != nil { return // an error } @@ -455,7 +456,7 @@ func WritePoolLock(allocID string, tokens, fee uint64) (hash string, nonce int64 Name: transaction.STORAGESC_WRITE_POOL_LOCK, InputArgs: &req, } - hash, _, nonce, _, err = smartContractTxnValueFee(sn, tokens, fee) + hash, _, nonce, _, err = smartContractTxnValueFeeWithRetry(sn, tokens, fee) return } @@ -476,7 +477,7 @@ func WritePoolUnlock(allocID string, fee uint64) (hash string, nonce int64, err Name: transaction.STORAGESC_WRITE_POOL_UNLOCK, InputArgs: &req, } - hash, _, nonce, _, err = smartContractTxnValueFee(sn, 0, fee) + hash, _, nonce, _, err = smartContractTxnValueFeeWithRetry(sn, 0, fee) return } @@ -1415,7 +1416,17 @@ func smartContractTxnValue(sn transaction.SmartContractTxnData, value uint64) ( hash, out string, nonce int64, txn *transaction.Transaction, err error) { // Fee is set during sdk initialization. - return smartContractTxnValueFee(sn, value, client.TxnFee()) + return smartContractTxnValueFeeWithRetry(sn, value, client.TxnFee()) +} + +func smartContractTxnValueFeeWithRetry(sn transaction.SmartContractTxnData, + value, fee uint64) (hash, out string, nonce int64, t *transaction.Transaction, err error) { + hash, out, nonce, t, err = smartContractTxnValueFee(sn, value, fee) + + if err != nil && strings.Contains(err.Error(), "invalid transaction nonce") { + return smartContractTxnValueFee(sn, value, fee) + } + return } func smartContractTxnValueFee(sn transaction.SmartContractTxnData, From e3b28c1c3a782951a412a7eb35578ac549323037 Mon Sep 17 00:00:00 2001 From: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Date: Wed, 13 Dec 2023 01:00:39 +0530 Subject: [PATCH 127/134] Fix wm rollback (#1324) * fix wm rollback * fix rb check * version logs * fix prev version * cleanup --- zboxcore/sdk/rollback.go | 11 ++++++++--- zboxcore/sdk/writemarker_mutex.go | 5 +++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/zboxcore/sdk/rollback.go b/zboxcore/sdk/rollback.go index 1b50772a3..dd5151655 100644 --- a/zboxcore/sdk/rollback.go +++ b/zboxcore/sdk/rollback.go @@ -116,7 +116,11 @@ func (rb *RollbackBlobber) processRollback(ctx context.Context, tx string) error wm.AllocationRoot = rb.lpm.PrevWM.AllocationRoot wm.PreviousAllocationRoot = rb.lpm.PrevWM.AllocationRoot wm.FileMetaRoot = rb.lpm.PrevWM.FileMetaRoot + if wm.AllocationRoot == rb.lpm.LatestWM.AllocationRoot { + return nil + } } + err := wm.Sign() if err != nil { l.Logger.Error("Signing writemarker failed: ", err) @@ -265,7 +269,7 @@ func (a *Allocation) CheckAllocStatus() (AllocStatus, error) { latestVersion = version } - if prevVersion == "" { + if prevVersion == "" && version != latestVersion { prevVersion = version } @@ -276,7 +280,6 @@ func (a *Allocation) CheckAllocStatus() (AllocStatus, error) { versionMap[version] = append(versionMap[version], rb) } - l.Logger.Info("versionMap", zap.Any("versionMap", versionMap)) if len(versionMap) < 2 { return Commit, nil } @@ -290,13 +293,15 @@ func (a *Allocation) CheckAllocStatus() (AllocStatus, error) { if len(versionMap[latestVersion]) >= req || len(versionMap[prevVersion]) >= req || len(versionMap) > 2 { // TODO: Return Repair after refactoring the repair function return Repair, nil + } else { + l.Logger.Info("versionMapLen", zap.Int("versionMapLen", len(versionMap)), zap.Int("latestLen", len(versionMap[latestVersion])), zap.Int("prevLen", len(versionMap[prevVersion]))) } // rollback to previous version l.Logger.Info("Rolling back to previous version") fullConsensus := len(versionMap[latestVersion]) - (req - len(versionMap[prevVersion])) errCnt = 0 - + l.Logger.Info("fullConsensus", zap.Int32("fullConsensus", int32(fullConsensus)), zap.Int("latestLen", len(versionMap[latestVersion])), zap.Int("prevLen", len(versionMap[prevVersion]))) for _, rb := range versionMap[latestVersion] { wg.Add(1) diff --git a/zboxcore/sdk/writemarker_mutex.go b/zboxcore/sdk/writemarker_mutex.go index f761ab389..bbf4046be 100644 --- a/zboxcore/sdk/writemarker_mutex.go +++ b/zboxcore/sdk/writemarker_mutex.go @@ -290,6 +290,11 @@ func (wmMu *WriteMarkerMutex) lockBlobber( var resp *http.Response var shouldContinue bool for retry := 0; retry < 3; retry++ { + select { + case <-ctx.Done(): + return + default: + } err, shouldContinue = func() (err error, shouldContinue bool) { reqCtx, ctxCncl := context.WithTimeout(ctx, timeOut) defer ctxCncl() From d74e39c5cb83b94d9698e6429402b099b63957bc Mon Sep 17 00:00:00 2001 From: Jayash Satolia <73050737+Jayashsatolia403@users.noreply.github.com> Date: Wed, 13 Dec 2023 11:29:41 +0530 Subject: [PATCH 128/134] Cleanup free storage update allocation (#1325) --- core/transaction/entity.go | 1 - zboxcore/sdk/sdk.go | 18 ------------------ 2 files changed, 19 deletions(-) diff --git a/core/transaction/entity.go b/core/transaction/entity.go index 358450c0c..6c06356b0 100644 --- a/core/transaction/entity.go +++ b/core/transaction/entity.go @@ -110,7 +110,6 @@ const ( NEW_ALLOCATION_REQUEST = "new_allocation_request" NEW_FREE_ALLOCATION = "free_allocation_request" UPDATE_ALLOCATION_REQUEST = "update_allocation_request" - FREE_UPDATE_ALLOCATION = "free_update_allocation" LOCK_TOKEN = "lock" UNLOCK_TOKEN = "unlock" diff --git a/zboxcore/sdk/sdk.go b/zboxcore/sdk/sdk.go index db0cd60f9..532fe845c 100644 --- a/zboxcore/sdk/sdk.go +++ b/zboxcore/sdk/sdk.go @@ -1231,24 +1231,6 @@ func UpdateAllocation( return } -func CreateFreeUpdateAllocation(marker, allocationId string, value uint64) (string, int64, error) { - if !sdkInitialized { - return "", 0, sdkNotInitialized - } - - var input = map[string]interface{}{ - "allocation_id": allocationId, - "marker": marker, - } - - var sn = transaction.SmartContractTxnData{ - Name: transaction.FREE_UPDATE_ALLOCATION, - InputArgs: input, - } - hash, _, n, _, err := smartContractTxnValue(sn, value) - return hash, n, err -} - func FinalizeAllocation(allocID string) (hash string, nonce int64, err error) { if !sdkInitialized { return "", 0, sdkNotInitialized From 310edbb4d669566acc8cfc6e2940170d2da813fa Mon Sep 17 00:00:00 2001 From: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Date: Thu, 14 Dec 2023 03:28:08 +0530 Subject: [PATCH 129/134] remove batch size (#1327) --- zboxcore/sdk/allocation.go | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 922350615..e979c56a7 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -39,10 +39,9 @@ import ( ) var ( - noBLOBBERS = errors.New("", "No Blobbers set in this allocation") - notInitialized = errors.New("sdk_not_initialized", "Please call InitStorageSDK Init and use GetAllocation to get the allocation object") - IsWasm = false - MultiOpBatchSize = 10 + noBLOBBERS = errors.New("", "No Blobbers set in this allocation") + notInitialized = errors.New("sdk_not_initialized", "Please call InitStorageSDK Init and use GetAllocation to get the allocation object") + IsWasm = false ) const ( @@ -242,7 +241,6 @@ func GetWritePriceRange() (PriceRange, error) { func SetWasm() { IsWasm = true BatchSize = 5 - MultiOpBatchSize = 7 } func getPriceRange(name string) (PriceRange, error) { @@ -841,11 +839,6 @@ func (a *Allocation) DoMultiOperation(operations []OperationRequest) error { } for ; i < len(operations); i++ { - if len(mo.operations) >= MultiOpBatchSize { - // max batch size reached, commit - connectionID = zboxutil.NewConnectionId() - break - } op := operations[i] remotePath := op.RemotePath parentPaths := GenerateParentPaths(remotePath) From 61e65f232bc0843d55d6eb2664cfbc7b21d1a567 Mon Sep 17 00:00:00 2001 From: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Date: Sat, 16 Dec 2023 01:40:30 +0530 Subject: [PATCH 130/134] fix retry op callback (#1329) --- zboxcore/sdk/multi_operation_worker.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/zboxcore/sdk/multi_operation_worker.go b/zboxcore/sdk/multi_operation_worker.go index 5ab77bc6f..89597bf01 100644 --- a/zboxcore/sdk/multi_operation_worker.go +++ b/zboxcore/sdk/multi_operation_worker.go @@ -248,6 +248,9 @@ func (mo *MultiOperation) Process() error { } defer writeMarkerMutex.Unlock(mo.ctx, mo.operationMask, mo.allocationObj.Blobbers, time.Minute, mo.connectionID) //nolint: errcheck if status != Commit { + for _, op := range mo.operations { + op.Error(mo.allocationObj, 0, ErrRetryOperation) + } return ErrRetryOperation } logger.Logger.Info("[checkAllocStatus]", time.Since(start).Milliseconds()) From 58e0df0198178f1277ba9e1cd51bc539ece10d6c Mon Sep 17 00:00:00 2001 From: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Date: Sat, 16 Dec 2023 02:03:28 +0530 Subject: [PATCH 131/134] Revert "remove batch size (#1327)" (#1328) This reverts commit 310edbb4d669566acc8cfc6e2940170d2da813fa. --- zboxcore/sdk/allocation.go | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index e979c56a7..922350615 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -39,9 +39,10 @@ import ( ) var ( - noBLOBBERS = errors.New("", "No Blobbers set in this allocation") - notInitialized = errors.New("sdk_not_initialized", "Please call InitStorageSDK Init and use GetAllocation to get the allocation object") - IsWasm = false + noBLOBBERS = errors.New("", "No Blobbers set in this allocation") + notInitialized = errors.New("sdk_not_initialized", "Please call InitStorageSDK Init and use GetAllocation to get the allocation object") + IsWasm = false + MultiOpBatchSize = 10 ) const ( @@ -241,6 +242,7 @@ func GetWritePriceRange() (PriceRange, error) { func SetWasm() { IsWasm = true BatchSize = 5 + MultiOpBatchSize = 7 } func getPriceRange(name string) (PriceRange, error) { @@ -839,6 +841,11 @@ func (a *Allocation) DoMultiOperation(operations []OperationRequest) error { } for ; i < len(operations); i++ { + if len(mo.operations) >= MultiOpBatchSize { + // max batch size reached, commit + connectionID = zboxutil.NewConnectionId() + break + } op := operations[i] remotePath := op.RemotePath parentPaths := GenerateParentPaths(remotePath) From bee24b781cef2511cd92609d97744cf0190198e0 Mon Sep 17 00:00:00 2001 From: peterlimg <54137706+peterlimg@users.noreply.github.com> Date: Sun, 17 Dec 2023 06:29:19 +1100 Subject: [PATCH 132/134] Add `force` param for getAllocationBlobbers wasm (#1330) --- wasmsdk/allocation.go | 4 ++-- zboxcore/sdk/sdk.go | 4 ++++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/wasmsdk/allocation.go b/wasmsdk/allocation.go index 2190afc8d..3812cf199 100644 --- a/wasmsdk/allocation.go +++ b/wasmsdk/allocation.go @@ -45,7 +45,7 @@ func createfreeallocation(freeStorageMarker string) (string, error) { func getAllocationBlobbers(preferredBlobberURLs []string, dataShards, parityShards int, size int64, - minReadPrice, maxReadPrice, minWritePrice, maxWritePrice int64) ([]string, error) { + minReadPrice, maxReadPrice, minWritePrice, maxWritePrice int64, force bool) ([]string, error) { if len(preferredBlobberURLs) > 0 { return sdk.GetBlobberIds(preferredBlobberURLs) @@ -57,7 +57,7 @@ func getAllocationBlobbers(preferredBlobberURLs []string, }, sdk.PriceRange{ Min: uint64(minWritePrice), Max: uint64(maxWritePrice), - }) + }, force) } func createAllocation(datashards, parityshards int, size int64, diff --git a/zboxcore/sdk/sdk.go b/zboxcore/sdk/sdk.go index 532fe845c..04601f146 100644 --- a/zboxcore/sdk/sdk.go +++ b/zboxcore/sdk/sdk.go @@ -1032,6 +1032,7 @@ func GetAllocationBlobbers( datashards, parityshards int, size int64, readPrice, writePrice PriceRange, + force ...bool, ) ([]string, error) { var allocationRequest = map[string]interface{}{ "data_shards": datashards, @@ -1045,6 +1046,9 @@ func GetAllocationBlobbers( params := make(map[string]string) params["allocation_data"] = string(allocationData) + if len(force) > 0 && force[0] { + params["force"] = strconv.FormatBool(force[0]) + } allocBlobber, err := zboxutil.MakeSCRestAPICall(STORAGE_SCADDRESS, "/alloc_blobbers", params, nil) if err != nil { From 3d993d049d4a5c5a6c5bf8e6bc7020fa47429beb Mon Sep 17 00:00:00 2001 From: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Date: Sun, 17 Dec 2023 15:12:30 +0530 Subject: [PATCH 133/134] fix retry callback (#1331) --- zboxcore/sdk/multi_operation_worker.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/zboxcore/sdk/multi_operation_worker.go b/zboxcore/sdk/multi_operation_worker.go index 89597bf01..b24f25992 100644 --- a/zboxcore/sdk/multi_operation_worker.go +++ b/zboxcore/sdk/multi_operation_worker.go @@ -231,6 +231,9 @@ func (mo *MultiOperation) Process() error { writeMarkerMutex.Unlock(mo.ctx, mo.operationMask, mo.allocationObj.Blobbers, time.Minute, mo.connectionID) //nolint: errcheck statusBar := NewRepairBar(mo.allocationObj.ID) if statusBar == nil { + for _, op := range mo.operations { + op.Error(mo.allocationObj, 0, ErrRetryOperation) + } return ErrRetryOperation } statusBar.wg.Add(1) @@ -244,6 +247,9 @@ func (mo *MultiOperation) Process() error { } else { l.Logger.Error("Repair failed") } + for _, op := range mo.operations { + op.Error(mo.allocationObj, 0, ErrRetryOperation) + } return ErrRetryOperation } defer writeMarkerMutex.Unlock(mo.ctx, mo.operationMask, mo.allocationObj.Blobbers, time.Minute, mo.connectionID) //nolint: errcheck From b7a1596694eb0005455f90fc8c19b2a7a10d7962 Mon Sep 17 00:00:00 2001 From: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Date: Tue, 19 Dec 2023 01:23:00 +0530 Subject: [PATCH 134/134] Fix fill panic (#1334) * fix fill shards panic * add log for fill err --- zboxcore/sdk/downloadworker.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/zboxcore/sdk/downloadworker.go b/zboxcore/sdk/downloadworker.go index d1788c706..3281a83e8 100644 --- a/zboxcore/sdk/downloadworker.go +++ b/zboxcore/sdk/downloadworker.go @@ -284,6 +284,10 @@ func (req *DownloadRequest) fillShards(shards [][][]byte, result *downloadBlock) } else { data = result.BlockChunks[i] } + if i >= len(shards) || len(shards[i]) <= result.idx { + l.Logger.Error("Invalid shard index", result.idx, len(shards), len(shards[i])) + return errors.New("invalid_shard_index", fmt.Sprintf("Invalid shard index %d shard len: %d shard block len: %d", result.idx, len(shards), i)) + } shards[i][result.idx] = data } return