diff --git a/go.mod b/go.mod index be2ada2fdd..d231bf3e62 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,7 @@ module github.com/BitBoxSwiss/bitbox-wallet-app go 1.22 +toolchain go1.23.6 require ( github.com/BitBoxSwiss/bitbox02-api-go v0.0.0-20250212204931-2b90fadfc774 @@ -9,7 +10,7 @@ require ( github.com/btcsuite/btcd/btcec/v2 v2.3.4 github.com/btcsuite/btcd/btcutil v1.1.6 github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0 - github.com/ethereum/go-ethereum v1.14.13 + github.com/ethereum/go-ethereum v1.15.4 github.com/flynn/noise v1.1.0 github.com/gorilla/mux v1.8.1 github.com/gorilla/websocket v1.5.3 @@ -27,37 +28,37 @@ require ( require ( github.com/Microsoft/go-winio v0.6.2 // indirect github.com/aead/siphash v1.0.1 // indirect - github.com/bits-and-blooms/bitset v1.13.0 // indirect + github.com/bits-and-blooms/bitset v1.17.0 // indirect github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f // indirect github.com/cespare/cp v1.1.1 // indirect - github.com/consensys/bavard v0.1.13 // indirect - github.com/consensys/gnark-crypto v0.13.0 // indirect - github.com/crate-crypto/go-ipa v0.0.0-20240223125850-b1e8a79f509c // indirect + github.com/consensys/bavard v0.1.22 // indirect + github.com/consensys/gnark-crypto v0.14.0 // indirect + github.com/crate-crypto/go-ipa v0.0.0-20240724233137-53bbb0ceb27a // indirect github.com/crate-crypto/go-kzg-4844 v1.1.0 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/deckarep/golang-set/v2 v2.6.0 // indirect github.com/decred/dcrd/crypto/blake256 v1.0.1 // indirect github.com/decred/dcrd/dcrec/secp256k1/v4 v4.3.0 // indirect github.com/ethereum/c-kzg-4844 v1.0.3 // indirect - github.com/ethereum/go-verkle v0.1.1-0.20240829091221-dffa7562dbe9 // indirect + github.com/ethereum/go-verkle v0.2.2 // indirect github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/go-ole/go-ole v1.3.0 // indirect github.com/google/uuid v1.6.0 // indirect - github.com/holiman/uint256 v1.3.1 // indirect + github.com/holiman/uint256 v1.3.2 // indirect github.com/kkdai/bstream v1.0.0 // indirect github.com/mmcloughlin/addchain v0.4.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/shirou/gopsutil v3.21.11+incompatible // indirect github.com/stretchr/objx v0.5.2 // indirect - github.com/supranational/blst v0.3.13 // indirect + github.com/supranational/blst v0.3.14 // indirect github.com/tklauser/go-sysconf v0.3.14 // indirect github.com/tklauser/numcpus v0.8.0 // indirect github.com/yusufpapurcu/wmi v1.2.4 // indirect golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 // indirect - golang.org/x/mod v0.19.0 // indirect - golang.org/x/sync v0.7.0 // indirect + golang.org/x/mod v0.22.0 // indirect + golang.org/x/sync v0.10.0 // indirect golang.org/x/sys v0.29.0 // indirect - golang.org/x/tools v0.23.0 // indirect + golang.org/x/tools v0.29.0 // indirect google.golang.org/protobuf v1.34.2 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect rsc.io/tmplfunc v0.0.3 // indirect diff --git a/go.sum b/go.sum index 44d4c0769a..3b73e5d207 100644 --- a/go.sum +++ b/go.sum @@ -12,8 +12,8 @@ github.com/aead/siphash v1.0.1 h1:FwHfE/T45KPKYuuSAKyyvE+oPWcaQ+CUmFW0bPlM+kg= github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII= 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/bits-and-blooms/bitset v1.13.0 h1:bAQ9OPNFYbGHV6Nez0tmNI0RiEu7/hxlYJRUA0wFAVE= -github.com/bits-and-blooms/bitset v1.13.0/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8= +github.com/bits-and-blooms/bitset v1.17.0 h1:1X2TS7aHz1ELcC0yU1y2stUs/0ig5oMU6STFZGrhvHI= +github.com/bits-and-blooms/bitset v1.17.0/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8= github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ= github.com/btcsuite/btcd v0.22.0-beta.0.20220111032746-97732e52810c/go.mod h1:tjmYdS6MLJ5/s0Fj4DbLgSbDHbEqLJrtnHecBFkdz5M= github.com/btcsuite/btcd v0.23.5-0.20231215221805-96c9fd8078fd/go.mod h1:nm3Bko6zh6bWP60UxwoT5LzdGJsQJaPo6HjduXq9p6A= @@ -58,14 +58,14 @@ github.com/cockroachdb/redact v1.1.5 h1:u1PMllDkdFfPWaNGMyLD1+so+aq3uUItthCFqzwP github.com/cockroachdb/redact v1.1.5/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 h1:zuQyyAKVxetITBuuhv3BI9cMrmStnpT18zmgmTxunpo= github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06/go.mod h1:7nc4anLGjupUW/PeY5qiNYsdNXj7zopG+eqsS7To5IQ= -github.com/consensys/bavard v0.1.13 h1:oLhMLOFGTLdlda/kma4VOJazblc7IM5y5QPd2A/YjhQ= -github.com/consensys/bavard v0.1.13/go.mod h1:9ItSMtA/dXMAiL7BG6bqW2m3NdSEObYWoH223nGHukI= -github.com/consensys/gnark-crypto v0.13.0 h1:VPULb/v6bbYELAPTDFINEVaMTTybV5GLxDdcjnS+4oc= -github.com/consensys/gnark-crypto v0.13.0/go.mod h1:wKqwsieaKPThcFkHe0d0zMsbHEUWFmZcG7KBCse210o= -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/crate-crypto/go-ipa v0.0.0-20240223125850-b1e8a79f509c h1:uQYC5Z1mdLRPrZhHjHxufI8+2UG/i25QG92j0Er9p6I= -github.com/crate-crypto/go-ipa v0.0.0-20240223125850-b1e8a79f509c/go.mod h1:geZJZH3SzKCqnz5VT0q/DyIG/tvu/dZk+VIfXicupJs= +github.com/consensys/bavard v0.1.22 h1:Uw2CGvbXSZWhqK59X0VG/zOjpTFuOMcPLStrp1ihI0A= +github.com/consensys/bavard v0.1.22/go.mod h1:k/zVjHHC4B+PQy1Pg7fgvG3ALicQw540Crag8qx+dZs= +github.com/consensys/gnark-crypto v0.14.0 h1:DDBdl4HaBtdQsq/wfMwJvZNE80sHidrK3Nfrefatm0E= +github.com/consensys/gnark-crypto v0.14.0/go.mod h1:CU4UijNPsHawiVGNxe9co07FkzCeWHHrb1li/n1XoU0= +github.com/cpuguy83/go-md2man/v2 v2.0.5 h1:ZtcqGrnekaHpVLArFSe4HK5DoKx1T0rq2DwVB0alcyc= +github.com/cpuguy83/go-md2man/v2 v2.0.5/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/crate-crypto/go-ipa v0.0.0-20240724233137-53bbb0ceb27a h1:W8mUrRp6NOVl3J+MYp5kPMoUZPp7aOYHtaua31lwRHg= +github.com/crate-crypto/go-ipa v0.0.0-20240724233137-53bbb0ceb27a/go.mod h1:sTwzHBvIzm2RfVCGNEBZgRyjwK40bVoun3ZnGOCafNM= github.com/crate-crypto/go-kzg-4844 v1.1.0 h1:EN/u9k2TF6OWSHrCCDBBU6GLNMq88OspHHlMnHfoyU4= github.com/crate-crypto/go-kzg-4844 v1.1.0/go.mod h1:JolLjpSff1tCCJKaJx4psrlEdlXuJEC996PL3tTAFks= github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -83,10 +83,10 @@ github.com/decred/dcrd/dcrec/secp256k1/v4 v4.3.0/go.mod h1:v57UDF4pDQJcEfFUCRop3 github.com/decred/dcrd/lru v1.0.0/go.mod h1:mxKOwFd7lFjN2GZYsiz/ecgqR6kkYAl+0pz0tEMk218= github.com/ethereum/c-kzg-4844 v1.0.3 h1:IEnbOHwjixW2cTvKRUlAAUOeleV7nNM/umJR+qy4WDs= github.com/ethereum/c-kzg-4844 v1.0.3/go.mod h1:VewdlzQmpT5QSrVhbBuGoCdFJkpaJlO1aQputP83wc0= -github.com/ethereum/go-ethereum v1.14.13 h1:L81Wmv0OUP6cf4CW6wtXsr23RUrDhKs2+Y9Qto+OgHU= -github.com/ethereum/go-ethereum v1.14.13/go.mod h1:RAC2gVMWJ6FkxSPESfbshrcKpIokgQKsVKmAuqdekDY= -github.com/ethereum/go-verkle v0.1.1-0.20240829091221-dffa7562dbe9 h1:8NfxH2iXvJ60YRB8ChToFTUzl8awsc3cJ8CbLjGIl/A= -github.com/ethereum/go-verkle v0.1.1-0.20240829091221-dffa7562dbe9/go.mod h1:M3b90YRnzqKyyzBEWJGqj8Qff4IDeXnzFw0P9bFw3uk= +github.com/ethereum/go-ethereum v1.15.4 h1:a0P+AalZaosp97rfKoYXHYWzyK3+jXWZrciM9S7XFrI= +github.com/ethereum/go-ethereum v1.15.4/go.mod h1:1LG2LnMOx2yPRHR/S+xuipXH29vPr6BIH6GElD8N/fo= +github.com/ethereum/go-verkle v0.2.2 h1:I2W0WjnrFUIzzVPwm8ykY+7pL2d4VhlsePn4j7cnFk8= +github.com/ethereum/go-verkle v0.2.2/go.mod h1:M3b90YRnzqKyyzBEWJGqj8Qff4IDeXnzFw0P9bFw3uk= github.com/flynn/noise v1.1.0 h1:KjPQoQCEFdZDiP03phOvGi11+SVVhBG2wOWAorLsstg= github.com/flynn/noise v1.1.0/go.mod h1:xbMo+0i6+IGbYdJhF31t2eR1BIU0CYc12+BNAKwUTag= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= @@ -137,8 +137,8 @@ github.com/holiman/billy v0.0.0-20240216141850-2abb0c79d3c4 h1:X4egAf/gcS1zATw6w github.com/holiman/billy v0.0.0-20240216141850-2abb0c79d3c4/go.mod h1:5GuXa7vkL8u9FkFuWdVvfR5ix8hRB7DbOAaYULamFpc= 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.3.1 h1:JfTzmih28bittyHM8z360dCjIA9dbPIBlcTI6lmctQs= -github.com/holiman/uint256 v1.3.1/go.mod h1:EOMSn4q6Nyt9P6efbI3bueV4e1b3dGlUCXeiRV4ng7E= +github.com/holiman/uint256 v1.3.2 h1:a9EgMPSC1AAaj1SZL5zIQD3WbwTuHrMGOerLjGmM/TA= +github.com/holiman/uint256 v1.3.2/go.mod h1:EOMSn4q6Nyt9P6efbI3bueV4e1b3dGlUCXeiRV4ng7E= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/huin/goupnp v1.3.0 h1:UvLUlWDNpoUdYzb2TCn+MuTWtcjXKSza2n6CBdQ0xXc= github.com/huin/goupnp v1.3.0/go.mod h1:gnGPsThkYa7bFi/KWmEysQRf48l2dvR5bxr2OFckNX8= @@ -163,8 +163,8 @@ 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/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= -github.com/leanovate/gopter v0.2.9 h1:fQjYxZaynp97ozCzfOyOuAGOU4aU/z37zf/tOujFk7c= -github.com/leanovate/gopter v0.2.9/go.mod h1:U2L/78B+KVFIx2VmW6onHJQzXtFb+p5y3y2Sh+Jxxv8= +github.com/leanovate/gopter v0.2.11 h1:vRjThO1EKPb/1NsDXuDrzldR28RLkBflWYcU9CvzWu4= +github.com/leanovate/gopter v0.2.11/go.mod h1:aK3tzZP/C+p1m3SPRE4SYZFGP7jjkuSI4f7Xvpt0S9c= 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.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= @@ -191,6 +191,16 @@ github.com/onsi/gomega v1.4.1/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5 github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +github.com/pion/dtls/v2 v2.2.7 h1:cSUBsETxepsCSFSxC3mc/aDo14qQLMSL+O6IjG28yV8= +github.com/pion/dtls/v2 v2.2.7/go.mod h1:8WiMkebSHFD0T+dIU+UeBaoV7kDhOW5oDCzZ7WZ/F9s= +github.com/pion/logging v0.2.2 h1:M9+AIj/+pxNsDfAT64+MAVgJO0rsyLnoJKCqf//DoeY= +github.com/pion/logging v0.2.2/go.mod h1:k0/tDVsRCX2Mb2ZEmTqNa7CWsQPc+YYCB7Q+5pahoms= +github.com/pion/stun/v2 v2.0.0 h1:A5+wXKLAypxQri59+tmQKVs7+l6mMM+3d+eER9ifRU0= +github.com/pion/stun/v2 v2.0.0/go.mod h1:22qRSh08fSEttYUmJZGlriq9+03jtVmXNODgLccj8GQ= +github.com/pion/transport/v2 v2.2.1 h1:7qYnCBlpgSJNYMbLCKuSY9KbQdBFoETvPNETv0y4N7c= +github.com/pion/transport/v2 v2.2.1/go.mod h1:cXXWavvCnFF6McHTft3DWS9iic2Mftcz1Aq29pGcU5g= +github.com/pion/transport/v3 v3.0.1 h1:gDTlPJwROfSfz6QfSi0ZmeCSkFcnWWiiR9ES0ouANiM= +github.com/pion/transport/v3 v3.0.1/go.mod h1:UY7kiITrlMv7/IKgd5eTUcaahZx5oUN3l9SzK5f5xE0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= @@ -228,18 +238,18 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -github.com/supranational/blst v0.3.13 h1:AYeSxdOMacwu7FBmpfloBz5pbFXDmJL33RuwnKtmTjk= -github.com/supranational/blst v0.3.13/go.mod h1:jZJtfjgudtNl4en1tzwPIV3KjUnQUvG3/j+w+fVonLw= +github.com/supranational/blst v0.3.14 h1:xNMoHRJOTwMn63ip6qoWJ2Ymgvj7E2b9jY2FAwY+qRo= +github.com/supranational/blst v0.3.14/go.mod h1:jZJtfjgudtNl4en1tzwPIV3KjUnQUvG3/j+w+fVonLw= github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 h1:epCh84lMvA70Z7CTTCmYQn2CKbY8j86K7/FAIr141uY= github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7/go.mod h1:q4W45IWZaF22tdD+VEXcAWRA037jwmWEB5VWYORlTpc= github.com/tklauser/go-sysconf v0.3.14 h1:g5vzr9iPFFz24v2KZXs/pvpvh8/V9Fw6vQK5ZZb78yU= github.com/tklauser/go-sysconf v0.3.14/go.mod h1:1ym4lWMLUOhuBOPGtRcJm7tEGX4SCYNEEEtghGG/8uY= github.com/tklauser/numcpus v0.8.0 h1:Mx4Wwe/FjZLeQsK/6kt2EOepwwSl7SmJrK5bV/dXYgY= github.com/tklauser/numcpus v0.8.0/go.mod h1:ZJZlAY+dmR4eut8epnzf0u/VwodKmryxR8txiloSqBE= -github.com/urfave/cli/v2 v2.25.7 h1:VAzn5oq403l5pHjc4OhD54+XGO9cdKVL/7lDjF+iKUs= -github.com/urfave/cli/v2 v2.25.7/go.mod h1:8qnjx1vcq5s2/wpsqoZFndg2CE5tNFyrTvS6SinrnYQ= -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/urfave/cli/v2 v2.27.5 h1:WoHEJLdsXr6dDWoJgMq/CboDmyY/8HMMH1fTECbih+w= +github.com/urfave/cli/v2 v2.27.5/go.mod h1:3Sevf16NykTbInEnD0yKkjDAeZDS0A6bzhBH5hrMvTQ= +github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 h1:gEOO8jv9F4OT7lGCjxCBTO/36wtF6j2nSip77qHd4x4= +github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1/go.mod h1:Ohn+xnUBiLI6FVj/9LpzZWtj1/D6lUovWYBkxHVV3aM= github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0= github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= go.etcd.io/bbolt v1.3.11 h1:yGEzV1wPz2yVCLsD8ZAiGHhHVlczyC9d1rP43/VCRJ0= @@ -254,8 +264,8 @@ golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 h1:2dVuKD2vS7b0QIHQbpyTISPd0 golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56/go.mod h1:M4RDyNAINzryxdtnbRXRL/OHtkFuWGRjvuhBJpk2IlY= golang.org/x/mobile v0.0.0-20240716161057-1ad2df20a8b6 h1:/VlmIrkuLf2wzPjkZ8imSpckHoW7Y71h66dxbLHSpi8= golang.org/x/mobile v0.0.0-20240716161057-1ad2df20a8b6/go.mod h1:TCsc78+c4cqb8IKEosz2LwJ6YRNkIjMuAYeHYjchGDE= -golang.org/x/mod v0.19.0 h1:fEdghXQSo20giMthA7cd28ZC+jts4amQ3YMXiP5oMQ8= -golang.org/x/mod v0.19.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/mod v0.22.0 h1:D4nJWe9zXqHOmWqj4VMOJhvzj7bEZg4wEYa759z1pH4= +golang.org/x/mod v0.22.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/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-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= @@ -265,8 +275,8 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.34.0 h1:Mb7Mrk043xzHgnRM88suvJFwzVrRfHEHJEl5/71CKw0= golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M= -golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ= +golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/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-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -288,11 +298,11 @@ 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.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= -golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk= -golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= +golang.org/x/time v0.9.0 h1:EsRrnYcQiGH+5FfbgvV4AP7qEZstoyrHB0DzarOQ4ZY= +golang.org/x/time v0.9.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.23.0 h1:SGsXPZ+2l4JsgaCKkx+FQ9YZ5XEtA1GZYuoDjenLjvg= -golang.org/x/tools v0.23.0/go.mod h1:pnu6ufv6vQkll6szChhK3C3L/ruaIv5eBeztNG8wtsI= +golang.org/x/tools v0.29.0 h1:Xx0h3TtM9rzQpQuR4dKLrdglAmCEN5Oi+P74JdhdzXE= +golang.org/x/tools v0.29.0/go.mod h1:KMQVMRsVxU6nHCFXrBPhDB8XncLNLM0lIy/F14RP588= 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= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= diff --git a/vendor/github.com/bits-and-blooms/bitset/README.md b/vendor/github.com/bits-and-blooms/bitset/README.md index fe7bca65eb..f48d52a1df 100644 --- a/vendor/github.com/bits-and-blooms/bitset/README.md +++ b/vendor/github.com/bits-and-blooms/bitset/README.md @@ -134,6 +134,16 @@ The `roaring` library allows you to go back and forth between compressed Roaring ``` +### Goroutine safety + +In general, it not safe to access +the same BitSet using different goroutines--they are +unsynchronized for performance. Should you want to access +a BitSet from more than one goroutine, you should +provide synchronization. Typically this is done by using channels to pass +the *BitSet around (in Go style; so there is only ever one owner), +or by using `sync.Mutex` to serialize operations on BitSets. + ## Implementation Note Go 1.9 introduced a native `math/bits` library. We provide backward compatibility to Go 1.7, which might be removed. diff --git a/vendor/github.com/bits-and-blooms/bitset/bitset.go b/vendor/github.com/bits-and-blooms/bitset/bitset.go index 9f38ed3a9d..334367dd90 100644 --- a/vendor/github.com/bits-and-blooms/bitset/bitset.go +++ b/vendor/github.com/bits-and-blooms/bitset/bitset.go @@ -68,9 +68,16 @@ var base64Encoding = base64.URLEncoding // Base64StdEncoding Marshal/Unmarshal BitSet with base64.StdEncoding(Default: base64.URLEncoding) func Base64StdEncoding() { base64Encoding = base64.StdEncoding } -// LittleEndian Marshal/Unmarshal Binary as Little Endian(Default: binary.BigEndian) +// LittleEndian sets Marshal/Unmarshal Binary as Little Endian (Default: binary.BigEndian) func LittleEndian() { binaryOrder = binary.LittleEndian } +// BigEndian sets Marshal/Unmarshal Binary as Big Endian (Default: binary.BigEndian) +func BigEndian() { binaryOrder = binary.BigEndian } + +// BinaryOrder returns the current binary order, see also LittleEndian() +// and BigEndian() to change the order. +func BinaryOrder() binary.ByteOrder { return binaryOrder } + // A BitSet is a set of bits. The zero value of a BitSet is an empty set of length 0. type BitSet struct { length uint @@ -99,12 +106,22 @@ func From(buf []uint64) *BitSet { return FromWithLength(uint(len(buf))*64, buf) } -// FromWithLength constructs from an array of words and length. -func FromWithLength(len uint, set []uint64) *BitSet { - return &BitSet{len, set} +// FromWithLength constructs from an array of words and length in bits. +// This function is for advanced users, most users should prefer +// the From function. +// As a user of FromWithLength, you are responsible for ensuring +// that the length is correct: your slice should have length at +// least (length+63)/64 in 64-bit words. +func FromWithLength(length uint, set []uint64) *BitSet { + if len(set) < wordsNeeded(length) { + panic("BitSet.FromWithLength: slice is too short") + } + return &BitSet{length, set} } -// Bytes returns the bitset as array of words +// Bytes returns the bitset as array of 64-bit words, giving direct access to the internal representation. +// It is not a copy, so changes to the returned slice will affect the bitset. +// It is meant for advanced users. func (b *BitSet) Bytes() []uint64 { return b.set } @@ -118,7 +135,7 @@ func wordsNeeded(i uint) int { } // wordsNeededUnbound calculates the number of words needed for i bits, possibly exceeding the capacity. -// This function is useful if you know that the capacity cannot be exceeded (e.g., you have an existing bitmap). +// This function is useful if you know that the capacity cannot be exceeded (e.g., you have an existing BitSet). func wordsNeededUnbound(i uint) int { return int((i + (wordSize - 1)) >> log2WordSize) } @@ -128,7 +145,10 @@ func wordsIndex(i uint) uint { return i & (wordSize - 1) } -// New creates a new BitSet with a hint that length bits will be required +// New creates a new BitSet with a hint that length bits will be required. +// The memory usage is at least length/8 bytes. +// In case of allocation failure, the function will return a BitSet with zero +// capacity. func New(length uint) (bset *BitSet) { defer func() { if r := recover(); r != nil { @@ -147,13 +167,30 @@ func New(length uint) (bset *BitSet) { return bset } +// MustNew creates a new BitSet with the given length bits. +// It panics if length exceeds the possible capacity or by a lack of memory. +func MustNew(length uint) (bset *BitSet) { + if length >= Cap() { + panic("You are exceeding the capacity") + } + + return &BitSet{ + length, + make([]uint64, wordsNeeded(length)), // may panic on lack of memory + } +} + // Cap returns the total possible capacity, or number of bits +// that can be stored in the BitSet theoretically. Under 32-bit system, +// it is 4294967295 and under 64-bit system, it is 18446744073709551615. +// Note that this is further limited by the maximum allocation size in Go, +// and your available memory, as any Go data structure. func Cap() uint { return ^uint(0) } // Len returns the number of bits in the BitSet. -// Note the difference to method Count, see example. +// Note that it differ from Count function. func (b *BitSet) Len() uint { return b.length } @@ -184,12 +221,32 @@ func (b *BitSet) Test(i uint) bool { return b.set[i>>log2WordSize]&(1<> log2WordSize) + subWordIndex := wordsIndex(i) + + // The word that the index falls within, shifted so the index is at bit 0 + var firstWord, secondWord uint64 + if firstWordIndex < len(b.set) { + firstWord = b.set[firstWordIndex] >> subWordIndex + } + + // The next word, masked to only include the necessary bits and shifted to cover the + // top of the word + if (firstWordIndex + 1) < len(b.set) { + secondWord = b.set[firstWordIndex+1] << uint64(wordSize-subWordIndex) + } + + return firstWord | secondWord +} + // Set bit i to 1, the capacity of the bitset is automatically // increased accordingly. -// If i>= Cap(), this function will panic. // Warning: using a very large value for 'i' // may lead to a memory shortage and a panic: the caller is responsible // for providing sensible parameters in line with their memory capacity. +// The memory usage is at least slightly over i/8 bytes. func (b *BitSet) Set(i uint) *BitSet { if i >= b.length { // if we need more bits, make 'em b.extendSet(i) @@ -198,7 +255,7 @@ func (b *BitSet) Set(i uint) *BitSet { return b } -// Clear bit i to 0 +// Clear bit i to 0. This never cause a memory allocation. It is always safe. func (b *BitSet) Clear(i uint) *BitSet { if i >= b.length { return b @@ -208,7 +265,6 @@ func (b *BitSet) Clear(i uint) *BitSet { } // SetTo sets bit i to value. -// If i>= Cap(), this function will panic. // Warning: using a very large value for 'i' // may lead to a memory shortage and a panic: the caller is responsible // for providing sensible parameters in line with their memory capacity. @@ -220,7 +276,6 @@ func (b *BitSet) SetTo(i uint, value bool) *BitSet { } // Flip bit at i. -// If i>= Cap(), this function will panic. // Warning: using a very large value for 'i' // may lead to a memory shortage and a panic: the caller is responsible // for providing sensible parameters in line with their memory capacity. @@ -233,7 +288,6 @@ func (b *BitSet) Flip(i uint) *BitSet { } // FlipRange bit in [start, end). -// If end>= Cap(), this function will panic. // Warning: using a very large value for 'end' // may lead to a memory shortage and a panic: the caller is responsible // for providing sensible parameters in line with their memory capacity. @@ -275,6 +329,7 @@ func (b *BitSet) FlipRange(start, end uint) *BitSet { // memory usage until the GC runs. Normally this should not be a problem, but if you // have an extremely large BitSet its important to understand that the old BitSet will // remain in memory until the GC frees it. +// If you are memory constrained, this function may cause a panic. func (b *BitSet) Shrink(lastbitindex uint) *BitSet { length := lastbitindex + 1 idx := wordsNeeded(length) @@ -294,6 +349,11 @@ func (b *BitSet) Shrink(lastbitindex uint) *BitSet { // Compact shrinks BitSet to so that we preserve all set bits, while minimizing // memory usage. Compact calls Shrink. +// A new slice is allocated to store the new bits, so you may see an increase in +// memory usage until the GC runs. Normally this should not be a problem, but if you +// have an extremely large BitSet its important to understand that the old BitSet will +// remain in memory until the GC frees it. +// If you are memory constrained, this function may cause a panic. func (b *BitSet) Compact() *BitSet { idx := len(b.set) - 1 for ; idx >= 0 && b.set[idx] == 0; idx-- { @@ -353,7 +413,8 @@ func (b *BitSet) InsertAt(idx uint) *BitSet { return b } -// String creates a string representation of the Bitmap +// String creates a string representation of the BitSet. It is only intended for +// human-readable output and not for serialization. func (b *BitSet) String() string { // follows code from https://github.com/RoaringBitmap/roaring var buffer bytes.Buffer @@ -541,7 +602,58 @@ func (b *BitSet) NextClear(i uint) (uint, bool) { return 0, false } -// ClearAll clears the entire BitSet +// PreviousSet returns the previous set bit from the specified index, +// including possibly the current index +// along with an error code (true = valid, false = no bit found i.e. all bits are clear) +func (b *BitSet) PreviousSet(i uint) (uint, bool) { + x := int(i >> log2WordSize) + if x >= len(b.set) { + return 0, false + } + w := b.set[x] + // Clear the bits above the index + w = w & ((1 << (wordsIndex(i) + 1)) - 1) + if w != 0 { + return uint(x<= 0; x-- { + w = b.set[x] + if w != 0 { + return uint(x<> log2WordSize) + if x >= len(b.set) { + return 0, false + } + w := b.set[x] + // Flip all bits and find the highest one bit + w = ^w + // Clear the bits above the index + w = w & ((1 << (wordsIndex(i) + 1)) - 1) + if w != 0 { + return uint(x<= 0; x-- { + w = b.set[x] + w = ^w + if w != 0 { + return uint(x<= 0 && b.set[idx] == 0; idx-- { + } + + // no set bits + if idx < 0 { + return 0, false + } + + return uint(idx)*wordSize + len64(b.set[idx]) - 1, true +} + +// ShiftLeft shifts the bitset like << operation would do. +// +// Left shift may require bitset size extension. We try to avoid the +// unnecessary memory operations by detecting the leftmost set bit. +// The function will panic if shift causes excess of capacity. +func (b *BitSet) ShiftLeft(bits uint) { + panicIfNull(b) + + if bits == 0 { + return + } + + top, ok := b.top() + if !ok { + return + } + + // capacity check + if top+bits < bits { + panic("You are exceeding the capacity") + } + + // destination set + dst := b.set + + // not using extendSet() to avoid unneeded data copying + nsize := wordsNeeded(top + bits) + if len(b.set) < nsize { + dst = make([]uint64, nsize) + } + if top+bits >= b.length { + b.length = top + bits + 1 + } + + pad, idx := top%wordSize, top>>log2WordSize + shift, pages := bits%wordSize, bits>>log2WordSize + if bits%wordSize == 0 { // happy case: just add pages + copy(dst[pages:nsize], b.set) + } else { + if pad+shift >= wordSize { + dst[idx+pages+1] = b.set[idx] >> (wordSize - shift) + } + + for i := int(idx); i >= 0; i-- { + if i > 0 { + dst[i+int(pages)] = (b.set[i] << shift) | (b.set[i-1] >> (wordSize - shift)) + } else { + dst[i+int(pages)] = b.set[i] << shift + } + } + } + + // zeroing extra pages + for i := 0; i < int(pages); i++ { + dst[i] = 0 + } + + b.set = dst +} + +// ShiftRight shifts the bitset like >> operation would do. +func (b *BitSet) ShiftRight(bits uint) { + panicIfNull(b) + + if bits == 0 { + return + } + + top, ok := b.top() + if !ok { + return + } + + if bits >= top { + b.set = make([]uint64, wordsNeeded(b.length)) + return + } + + pad, idx := top%wordSize, top>>log2WordSize + shift, pages := bits%wordSize, bits>>log2WordSize + if bits%wordSize == 0 { // happy case: just clear pages + b.set = b.set[pages:] + b.length -= pages * wordSize + } else { + for i := 0; i <= int(idx-pages); i++ { + if i < int(idx-pages) { + b.set[i] = (b.set[i+int(pages)] >> shift) | (b.set[i+int(pages)+1] << (wordSize - shift)) + } else { + b.set[i] = b.set[i+int(pages)] >> shift + } + } + + if pad < shift { + b.set[int(idx-pages)] = 0 + } + } + + for i := int(idx-pages) + 1; i <= int(idx); i++ { + b.set[i] = 0 + } +} diff --git a/vendor/github.com/bits-and-blooms/bitset/leading_zeros_18.go b/vendor/github.com/bits-and-blooms/bitset/leading_zeros_18.go new file mode 100644 index 0000000000..72af1d6fc5 --- /dev/null +++ b/vendor/github.com/bits-and-blooms/bitset/leading_zeros_18.go @@ -0,0 +1,43 @@ +//go:build !go1.9 +// +build !go1.9 + +package bitset + +var len8tab = "" + + "\x00\x01\x02\x02\x03\x03\x03\x03\x04\x04\x04\x04\x04\x04\x04\x04" + + "\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05" + + "\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06" + + "\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06" + + "\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07" + + "\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07" + + "\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07" + + "\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07" + + "\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08" + + "\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08" + + "\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08" + + "\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08" + + "\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08" + + "\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08" + + "\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08" + + "\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08" + +// len64 returns the minimum number of bits required to represent x; the result is 0 for x == 0. +func len64(x uint64) (n uint) { + if x >= 1<<32 { + x >>= 32 + n = 32 + } + if x >= 1<<16 { + x >>= 16 + n += 16 + } + if x >= 1<<8 { + x >>= 8 + n += 8 + } + return n + uint(len8tab[x]) +} + +func leadingZeroes64(v uint64) uint { + return 64 - len64(v) +} diff --git a/vendor/github.com/bits-and-blooms/bitset/leading_zeros_19.go b/vendor/github.com/bits-and-blooms/bitset/leading_zeros_19.go new file mode 100644 index 0000000000..74a7942414 --- /dev/null +++ b/vendor/github.com/bits-and-blooms/bitset/leading_zeros_19.go @@ -0,0 +1,14 @@ +//go:build go1.9 +// +build go1.9 + +package bitset + +import "math/bits" + +func len64(v uint64) uint { + return uint(bits.Len64(v)) +} + +func leadingZeroes64(v uint64) uint { + return uint(bits.LeadingZeros64(v)) +} diff --git a/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/g1.go b/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/g1.go index 909ff12f16..50ab4713e3 100644 --- a/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/g1.go +++ b/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/g1.go @@ -25,38 +25,40 @@ import ( "runtime" ) -// G1Affine point in affine coordinates +// G1Affine is a point in affine coordinates (x,y) type G1Affine struct { X, Y fp.Element } -// G1Jac is a point with fp.Element coordinates +// G1Jac is a point in Jacobian coordinates (x=X/Z², y=Y/Z³) type G1Jac struct { X, Y, Z fp.Element } -// g1JacExtended parameterized Jacobian coordinates (x=X/ZZ, y=Y/ZZZ, ZZ³=ZZZ²) +// g1JacExtended is a point in extended Jacobian coordinates (x=X/ZZ, y=Y/ZZZ, ZZ³=ZZZ²) type g1JacExtended struct { X, Y, ZZ, ZZZ fp.Element } // ------------------------------------------------------------------------------------------------- -// Affine +// Affine coordinates -// Set sets p to the provided point +// Set sets p to a in affine coordinates. func (p *G1Affine) Set(a *G1Affine) *G1Affine { p.X, p.Y = a.X, a.Y return p } -// setInfinity sets p to O +// setInfinity sets p to the infinity point, which is encoded as (0,0). +// N.B.: (0,0) is never on the curve for j=0 curves (Y²=X³+B). func (p *G1Affine) setInfinity() *G1Affine { p.X.SetZero() p.Y.SetZero() return p } -// ScalarMultiplication computes and returns p = a ⋅ s +// ScalarMultiplication computes and returns p = [s]a +// where p and a are affine points. func (p *G1Affine) ScalarMultiplication(a *G1Affine, s *big.Int) *G1Affine { var _p G1Jac _p.FromAffine(a) @@ -65,7 +67,8 @@ func (p *G1Affine) ScalarMultiplication(a *G1Affine, s *big.Int) *G1Affine { return p } -// ScalarMultiplicationBase computes and returns p = g ⋅ s where g is the prime subgroup generator +// ScalarMultiplicationBase computes and returns p = [s]g +// where g is the affine point generating the prime subgroup. func (p *G1Affine) ScalarMultiplicationBase(s *big.Int) *G1Affine { var _p G1Jac _p.mulGLV(&g1Gen, s) @@ -73,8 +76,9 @@ func (p *G1Affine) ScalarMultiplicationBase(s *big.Int) *G1Affine { return p } -// Add adds two point in affine coordinates. -// Jacobian addition with Z1=Z2=1 +// Add adds two points in affine coordinates. +// It uses the Jacobian addition with a.Z=b.Z=1 and converts the result to affine coordinates. +// // https://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-mmadd-2007-bl func (p *G1Affine) Add(a, b *G1Affine) *G1Affine { var q G1Jac @@ -120,6 +124,10 @@ func (p *G1Affine) Add(a, b *G1Affine) *G1Affine { } // Double doubles a point in affine coordinates. +// It converts the point to Jacobian coordinates, doubles it using Jacobian +// addition with a.Z=1, and converts it back to affine coordinates. +// +// http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-mdbl-2007-bl func (p *G1Affine) Double(a *G1Affine) *G1Affine { var q G1Jac q.FromAffine(a) @@ -128,7 +136,8 @@ func (p *G1Affine) Double(a *G1Affine) *G1Affine { return p } -// Sub subs two point in affine coordinates. +// Sub subtracts two points in affine coordinates. +// It uses a similar approach to Add, but negates the second point before adding. func (p *G1Affine) Sub(a, b *G1Affine) *G1Affine { var bneg G1Affine bneg.Neg(b) @@ -136,19 +145,19 @@ func (p *G1Affine) Sub(a, b *G1Affine) *G1Affine { return p } -// Equal tests if two points (in Affine coordinates) are equal +// Equal tests if two points in affine coordinates are equal. func (p *G1Affine) Equal(a *G1Affine) bool { return p.X.Equal(&a.X) && p.Y.Equal(&a.Y) } -// Neg computes -G +// Neg sets p to the affine negative point -a = (a.X, -a.Y). func (p *G1Affine) Neg(a *G1Affine) *G1Affine { p.X = a.X p.Y.Neg(&a.Y) return p } -// FromJacobian rescales a point in Jacobian coord in z=1 plane +// FromJacobian converts a point p1 from Jacobian to affine coordinates. func (p *G1Affine) FromJacobian(p1 *G1Jac) *G1Affine { var a, b fp.Element @@ -167,7 +176,7 @@ func (p *G1Affine) FromJacobian(p1 *G1Jac) *G1Affine { return p } -// String returns the string representation of the point or "O" if it is infinity +// String returns the string representation E(x,y) of the affine point p or "O" if it is infinity. func (p *G1Affine) String() string { if p.IsInfinity() { return "O" @@ -175,21 +184,20 @@ func (p *G1Affine) String() string { return "E([" + p.X.String() + "," + p.Y.String() + "])" } -// IsInfinity checks if the point is infinity -// in affine, it's encoded as (0,0) -// (0,0) is never on the curve for j=0 curves +// IsInfinity checks if the affine point p is infinity, which is encoded as (0,0). +// N.B.: (0,0) is never on the curve for j=0 curves (Y²=X³+B). func (p *G1Affine) IsInfinity() bool { return p.X.IsZero() && p.Y.IsZero() } -// IsOnCurve returns true if p in on the curve +// IsOnCurve returns true if the affine point p in on the curve. func (p *G1Affine) IsOnCurve() bool { var point G1Jac point.FromAffine(p) return point.IsOnCurve() // call this function to handle infinity point } -// IsInSubGroup returns true if p is in the correct subgroup, false otherwise +// IsInSubGroup returns true if the affine point p is in the correct subgroup, false otherwise. func (p *G1Affine) IsInSubGroup() bool { var _p G1Jac _p.FromAffine(p) @@ -197,84 +205,76 @@ func (p *G1Affine) IsInSubGroup() bool { } // ------------------------------------------------------------------------------------------------- -// Jacobian +// Jacobian coordinates -// Set sets p to the provided point -func (p *G1Jac) Set(a *G1Jac) *G1Jac { - p.X, p.Y, p.Z = a.X, a.Y, a.Z +// Set sets p to a in Jacobian coordinates. +func (p *G1Jac) Set(q *G1Jac) *G1Jac { + p.X, p.Y, p.Z = q.X, q.Y, q.Z return p } -// Equal tests if two points (in Jacobian coordinates) are equal -func (p *G1Jac) Equal(a *G1Jac) bool { +// Equal tests if two points in Jacobian coordinates are equal. +func (p *G1Jac) Equal(q *G1Jac) bool { // If one point is infinity, the other must also be infinity. if p.Z.IsZero() { - return a.Z.IsZero() + return q.Z.IsZero() } // If the other point is infinity, return false since we can't // the following checks would be incorrect. - if a.Z.IsZero() { + if q.Z.IsZero() { return false } var pZSquare, aZSquare fp.Element pZSquare.Square(&p.Z) - aZSquare.Square(&a.Z) + aZSquare.Square(&q.Z) var lhs, rhs fp.Element lhs.Mul(&p.X, &aZSquare) - rhs.Mul(&a.X, &pZSquare) + rhs.Mul(&q.X, &pZSquare) if !lhs.Equal(&rhs) { return false } - lhs.Mul(&p.Y, &aZSquare).Mul(&lhs, &a.Z) - rhs.Mul(&a.Y, &pZSquare).Mul(&rhs, &p.Z) + lhs.Mul(&p.Y, &aZSquare).Mul(&lhs, &q.Z) + rhs.Mul(&q.Y, &pZSquare).Mul(&rhs, &p.Z) return lhs.Equal(&rhs) } -// Neg computes -G -func (p *G1Jac) Neg(a *G1Jac) *G1Jac { - *p = *a - p.Y.Neg(&a.Y) - return p -} - -// SubAssign subtracts two points on the curve -func (p *G1Jac) SubAssign(a *G1Jac) *G1Jac { - var tmp G1Jac - tmp.Set(a) - tmp.Y.Neg(&tmp.Y) - p.AddAssign(&tmp) +// Neg sets p to the Jacobian negative point -q = (q.X, -q.Y, q.Z). +func (p *G1Jac) Neg(q *G1Jac) *G1Jac { + *p = *q + p.Y.Neg(&q.Y) return p } -// AddAssign point addition in montgomery form +// AddAssign sets p to p+a in Jacobian coordinates. +// // https://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#addition-add-2007-bl -func (p *G1Jac) AddAssign(a *G1Jac) *G1Jac { +func (p *G1Jac) AddAssign(q *G1Jac) *G1Jac { - // p is infinity, return a + // p is infinity, return q if p.Z.IsZero() { - p.Set(a) + p.Set(q) return p } - // a is infinity, return p - if a.Z.IsZero() { + // q is infinity, return p + if q.Z.IsZero() { return p } var Z1Z1, Z2Z2, U1, U2, S1, S2, H, I, J, r, V fp.Element - Z1Z1.Square(&a.Z) + Z1Z1.Square(&q.Z) Z2Z2.Square(&p.Z) - U1.Mul(&a.X, &Z2Z2) + U1.Mul(&q.X, &Z2Z2) U2.Mul(&p.X, &Z1Z1) - S1.Mul(&a.Y, &p.Z). + S1.Mul(&q.Y, &p.Z). Mul(&S1, &Z2Z2) - S2.Mul(&p.Y, &a.Z). + S2.Mul(&p.Y, &q.Z). Mul(&S2, &Z1Z1) - // if p == a, we double instead + // if p == q, we double instead if U1.Equal(&U2) && S1.Equal(&S2) { return p.DoubleAssign() } @@ -293,7 +293,7 @@ func (p *G1Jac) AddAssign(a *G1Jac) *G1Jac { Mul(&p.Y, &r) S1.Mul(&S1, &J).Double(&S1) p.Y.Sub(&p.Y, &S1) - p.Z.Add(&p.Z, &a.Z) + p.Z.Add(&p.Z, &q.Z) p.Z.Square(&p.Z). Sub(&p.Z, &Z1Z1). Sub(&p.Z, &Z2Z2). @@ -302,8 +302,19 @@ func (p *G1Jac) AddAssign(a *G1Jac) *G1Jac { return p } -// DoubleMixed point addition -// http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-mdbl-2007-bl +// SubAssign sets p to p-a in Jacobian coordinates. +// It uses a similar approach to AddAssign, but negates the point a before adding. +func (p *G1Jac) SubAssign(q *G1Jac) *G1Jac { + var tmp G1Jac + tmp.Set(q) + tmp.Y.Neg(&tmp.Y) + p.AddAssign(&tmp) + return p +} + +// Double sets p to [2]q in Jacobian coordinates. +// +// https://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2007-bl func (p *G1Jac) DoubleMixed(a *G1Affine) *G1Jac { var XX, YY, YYYY, S, M, T fp.Element XX.Square(&a.X) @@ -315,7 +326,7 @@ func (p *G1Jac) DoubleMixed(a *G1Affine) *G1Jac { Sub(&S, &YYYY). Double(&S) M.Double(&XX). - Add(&M, &XX) // -> + a, but a=0 here + Add(&M, &XX) // -> + A, but A=0 here T.Square(&M). Sub(&T, &S). Sub(&T, &S) @@ -331,7 +342,8 @@ func (p *G1Jac) DoubleMixed(a *G1Affine) *G1Jac { return p } -// AddMixed point addition +// AddMixed sets p to p+a in Jacobian coordinates, where a.Z = 1. +// // http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-madd-2007-bl func (p *G1Jac) AddMixed(a *G1Affine) *G1Jac { @@ -380,7 +392,8 @@ func (p *G1Jac) AddMixed(a *G1Affine) *G1Jac { return p } -// Double doubles a point in Jacobian coordinates +// Double sets p to [2]q in Jacobian coordinates. +// // https://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2007-bl func (p *G1Jac) Double(q *G1Jac) *G1Jac { p.Set(q) @@ -388,7 +401,8 @@ func (p *G1Jac) Double(q *G1Jac) *G1Jac { return p } -// DoubleAssign doubles a point in Jacobian coordinates +// DoubleAssign doubles p in Jacobian coordinates. +// // https://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2007-bl func (p *G1Jac) DoubleAssign() *G1Jac { @@ -420,39 +434,43 @@ func (p *G1Jac) DoubleAssign() *G1Jac { return p } -// ScalarMultiplication computes and returns p = a ⋅ s +// ScalarMultiplication computes and returns p = [s]a +// where p and a are Jacobian points. +// using the GLV technique. // see https://www.iacr.org/archive/crypto2001/21390189.pdf -func (p *G1Jac) ScalarMultiplication(a *G1Jac, s *big.Int) *G1Jac { - return p.mulGLV(a, s) +func (p *G1Jac) ScalarMultiplication(q *G1Jac, s *big.Int) *G1Jac { + return p.mulGLV(q, s) } -// ScalarMultiplicationBase computes and returns p = g ⋅ s where g is the prime subgroup generator +// ScalarMultiplicationBase computes and returns p = [s]g +// where g is the prime subgroup generator. func (p *G1Jac) ScalarMultiplicationBase(s *big.Int) *G1Jac { return p.mulGLV(&g1Gen, s) + } -// String returns canonical representation of the point in affine coordinates +// String converts p to affine coordinates and returns its string representation E(x,y) or "O" if it is infinity. func (p *G1Jac) String() string { _p := G1Affine{} _p.FromJacobian(p) return _p.String() } -// FromAffine sets p = Q, p in Jacobian, Q in affine -func (p *G1Jac) FromAffine(Q *G1Affine) *G1Jac { - if Q.IsInfinity() { +// FromAffine converts a point a from affine to Jacobian coordinates. +func (p *G1Jac) FromAffine(a *G1Affine) *G1Jac { + if a.IsInfinity() { p.Z.SetZero() p.X.SetOne() p.Y.SetOne() return p } p.Z.SetOne() - p.X.Set(&Q.X) - p.Y.Set(&Q.Y) + p.X.Set(&a.X) + p.Y.Set(&a.Y) return p } -// IsOnCurve returns true if p in on the curve +// IsOnCurve returns true if the Jacobian point p in on the curve. func (p *G1Jac) IsOnCurve() bool { var left, right, tmp, ZZ fp.Element left.Square(&p.Y) @@ -484,13 +502,14 @@ func (p *G1Jac) IsInSubGroup() bool { } -// mulWindowed computes a 2-bits windowed scalar multiplication -func (p *G1Jac) mulWindowed(a *G1Jac, s *big.Int) *G1Jac { +// mulWindowed computes the 2-bits windowed double-and-add scalar +// multiplication p=[s]q in Jacobian coordinates. +func (p *G1Jac) mulWindowed(q *G1Jac, s *big.Int) *G1Jac { var res G1Jac var ops [3]G1Jac - ops[0].Set(a) + ops[0].Set(q) if s.Sign() == -1 { ops[0].Neg(&ops[0]) } @@ -517,17 +536,18 @@ func (p *G1Jac) mulWindowed(a *G1Jac, s *big.Int) *G1Jac { } -// ϕ assigns p to ϕ(a) where ϕ: (x,y) → (w x,y), and returns p -// where w is a third root of unity in 𝔽p -func (p *G1Jac) phi(a *G1Jac) *G1Jac { - p.Set(a) +// phi sets p to ϕ(a) where ϕ: (x,y) → (w x,y), +// where w is a third root of unity. +func (p *G1Jac) phi(q *G1Jac) *G1Jac { + p.Set(q) p.X.Mul(&p.X, &thirdRootOneG1) return p } // mulGLV computes the scalar multiplication using a windowed-GLV method +// // see https://www.iacr.org/archive/crypto2001/21390189.pdf -func (p *G1Jac) mulGLV(a *G1Jac, s *big.Int) *G1Jac { +func (p *G1Jac) mulGLV(q *G1Jac, s *big.Int) *G1Jac { var table [15]G1Jac var res G1Jac @@ -535,11 +555,11 @@ func (p *G1Jac) mulGLV(a *G1Jac, s *big.Int) *G1Jac { res.Set(&g1Infinity) - // table[b3b2b1b0-1] = b3b2 ⋅ ϕ(a) + b1b0*a - table[0].Set(a) - table[3].phi(a) + // table[b3b2b1b0-1] = b3b2 ⋅ ϕ(q) + b1b0*q + table[0].Set(q) + table[3].phi(q) - // split the scalar, modifies ±a, ϕ(a) accordingly + // split the scalar, modifies ±q, ϕ(q) accordingly k := ecc.SplitScalar(s, &glvBasis) if k[0].Sign() == -1 { @@ -552,7 +572,7 @@ func (p *G1Jac) mulGLV(a *G1Jac, s *big.Int) *G1Jac { } // precompute table (2 bits sliding window) - // table[b3b2b1b0-1] = b3b2 ⋅ ϕ(a) + b1b0 ⋅ a if b3b2b1b0 != 0 + // table[b3b2b1b0-1] = b3b2 ⋅ ϕ(q) + b1b0 ⋅ q if b3b2b1b0 != 0 table[1].Double(&table[0]) table[2].Set(&table[1]).AddAssign(&table[0]) table[4].Set(&table[3]).AddAssign(&table[0]) @@ -608,16 +628,17 @@ func (p *G1Affine) ClearCofactor(a *G1Affine) *G1Affine { } // ClearCofactor maps a point in E(Fp) to E(Fp)[r] -func (p *G1Jac) ClearCofactor(a *G1Jac) *G1Jac { +func (p *G1Jac) ClearCofactor(q *G1Jac) *G1Jac { // cf https://eprint.iacr.org/2019/403.pdf, 5 var res G1Jac - res.ScalarMultiplication(a, &xGen).AddAssign(a) + res.ScalarMultiplication(q, &xGen).AddAssign(q) p.Set(&res) return p } -// JointScalarMultiplication computes [s1]a1+[s2]a2 using Straus-Shamir technique +// JointScalarMultiplication computes [s1]a1+[s2]a2 using Strauss-Shamir technique +// where a1 and a2 are affine points. func (p *G1Jac) JointScalarMultiplication(a1, a2 *G1Affine, s1, s2 *big.Int) *G1Jac { var res, p1, p2 G1Jac @@ -688,21 +709,22 @@ func (p *G1Jac) JointScalarMultiplication(a1, a2 *G1Affine, s1, s2 *big.Int) *G1 } // JointScalarMultiplicationBase computes [s1]g+[s2]a using Straus-Shamir technique -// where g is the prime subgroup generator +// where g is the prime subgroup generator. func (p *G1Jac) JointScalarMultiplicationBase(a *G1Affine, s1, s2 *big.Int) *G1Jac { return p.JointScalarMultiplication(&g1GenAff, a, s1, s2) + } // ------------------------------------------------------------------------------------------------- -// Jacobian extended +// extended Jacobian coordinates -// Set sets p to the provided point -func (p *g1JacExtended) Set(a *g1JacExtended) *g1JacExtended { - p.X, p.Y, p.ZZ, p.ZZZ = a.X, a.Y, a.ZZ, a.ZZZ +// Set sets p to a in extended Jacobian coordinates. +func (p *g1JacExtended) Set(q *g1JacExtended) *g1JacExtended { + p.X, p.Y, p.ZZ, p.ZZZ = q.X, q.Y, q.ZZ, q.ZZZ return p } -// setInfinity sets p to O +// setInfinity sets p to the infinity point (1,1,0,0). func (p *g1JacExtended) setInfinity() *g1JacExtended { p.X.SetOne() p.Y.SetOne() @@ -711,43 +733,45 @@ func (p *g1JacExtended) setInfinity() *g1JacExtended { return p } -func (p *g1JacExtended) IsZero() bool { +// IsInfinity checks if the p is infinity, i.e. p.ZZ=0. +func (p *g1JacExtended) IsInfinity() bool { return p.ZZ.IsZero() } -// fromJacExtended sets Q in affine coordinates -func (p *G1Affine) fromJacExtended(Q *g1JacExtended) *G1Affine { - if Q.ZZ.IsZero() { +// fromJacExtended converts an extended Jacobian point to an affine point. +func (p *G1Affine) fromJacExtended(q *g1JacExtended) *G1Affine { + if q.ZZ.IsZero() { p.X = fp.Element{} p.Y = fp.Element{} return p } - p.X.Inverse(&Q.ZZ).Mul(&p.X, &Q.X) - p.Y.Inverse(&Q.ZZZ).Mul(&p.Y, &Q.Y) + p.X.Inverse(&q.ZZ).Mul(&p.X, &q.X) + p.Y.Inverse(&q.ZZZ).Mul(&p.Y, &q.Y) return p } -// fromJacExtended sets Q in Jacobian coordinates -func (p *G1Jac) fromJacExtended(Q *g1JacExtended) *G1Jac { - if Q.ZZ.IsZero() { +// fromJacExtended converts an extended Jacobian point to a Jacobian point. +func (p *G1Jac) fromJacExtended(q *g1JacExtended) *G1Jac { + if q.ZZ.IsZero() { p.Set(&g1Infinity) return p } - p.X.Mul(&Q.ZZ, &Q.X).Mul(&p.X, &Q.ZZ) - p.Y.Mul(&Q.ZZZ, &Q.Y).Mul(&p.Y, &Q.ZZZ) - p.Z.Set(&Q.ZZZ) + p.X.Mul(&q.ZZ, &q.X).Mul(&p.X, &q.ZZ) + p.Y.Mul(&q.ZZZ, &q.Y).Mul(&p.Y, &q.ZZZ) + p.Z.Set(&q.ZZZ) return p } -// unsafeFromJacExtended sets p in Jacobian coordinates, but don't check for infinity -func (p *G1Jac) unsafeFromJacExtended(Q *g1JacExtended) *G1Jac { - p.X.Square(&Q.ZZ).Mul(&p.X, &Q.X) - p.Y.Square(&Q.ZZZ).Mul(&p.Y, &Q.Y) - p.Z = Q.ZZZ +// unsafeFromJacExtended converts an extended Jacobian point, distinct from Infinity, to a Jacobian point. +func (p *G1Jac) unsafeFromJacExtended(q *g1JacExtended) *G1Jac { + p.X.Square(&q.ZZ).Mul(&p.X, &q.X) + p.Y.Square(&q.ZZZ).Mul(&p.Y, &q.Y) + p.Z = q.ZZZ return p } -// add point in Jacobian extended coordinates +// add sets p to p+q in extended Jacobian coordinates. +// // https://www.hyperelliptic.org/EFD/g1p/auto-shortw-xyzz.html#addition-add-2008-s func (p *g1JacExtended) add(q *g1JacExtended) *g1JacExtended { //if q is infinity return p @@ -803,10 +827,11 @@ func (p *g1JacExtended) add(q *g1JacExtended) *g1JacExtended { return p } -// double point in Jacobian extended coordinates +// double sets p to [2]q in Jacobian extended coordinates. +// // http://www.hyperelliptic.org/EFD/g1p/auto-shortw-xyzz.html#doubling-dbl-2008-s-1 -// since we consider any point on Z=0 as the point at infinity -// this doubling formula works for infinity points as well +// N.B.: since we consider any point on Z=0 as the point at infinity +// this doubling formula works for infinity points as well. func (p *g1JacExtended) double(q *g1JacExtended) *g1JacExtended { var U, V, W, S, XX, M fp.Element @@ -816,7 +841,7 @@ func (p *g1JacExtended) double(q *g1JacExtended) *g1JacExtended { S.Mul(&q.X, &V) XX.Square(&q.X) M.Double(&XX). - Add(&M, &XX) // -> + a, but a=0 here + Add(&M, &XX) // -> + A, but A=0 here U.Mul(&W, &q.Y) p.X.Square(&M). @@ -831,9 +856,10 @@ func (p *g1JacExtended) double(q *g1JacExtended) *g1JacExtended { return p } -// subMixed same as addMixed, but will negate a.Y +// addMixed sets p to p+q in extended Jacobian coordinates, where a.ZZ=1. +// // http://www.hyperelliptic.org/EFD/g1p/auto-shortw-xyzz.html#addition-madd-2008-s -func (p *g1JacExtended) subMixed(a *G1Affine) *g1JacExtended { +func (p *g1JacExtended) addMixed(a *G1Affine) *g1JacExtended { //if a is infinity return p if a.IsInfinity() { @@ -842,7 +868,7 @@ func (p *g1JacExtended) subMixed(a *G1Affine) *g1JacExtended { // p is infinity, return a if p.ZZ.IsZero() { p.X = a.X - p.Y.Neg(&a.Y) + p.Y = a.Y p.ZZ.SetOne() p.ZZZ.SetOne() return p @@ -855,12 +881,11 @@ func (p *g1JacExtended) subMixed(a *G1Affine) *g1JacExtended { P.Sub(&P, &p.X) R.Mul(&a.Y, &p.ZZZ) - R.Neg(&R) R.Sub(&R, &p.Y) if P.IsZero() { if R.IsZero() { - return p.doubleNegMixed(a) + return p.doubleMixed(a) } p.ZZ = fp.Element{} @@ -887,9 +912,10 @@ func (p *g1JacExtended) subMixed(a *G1Affine) *g1JacExtended { } -// addMixed +// subMixed works the same as addMixed, but negates a.Y. +// // http://www.hyperelliptic.org/EFD/g1p/auto-shortw-xyzz.html#addition-madd-2008-s -func (p *g1JacExtended) addMixed(a *G1Affine) *g1JacExtended { +func (p *g1JacExtended) subMixed(a *G1Affine) *g1JacExtended { //if a is infinity return p if a.IsInfinity() { @@ -898,7 +924,7 @@ func (p *g1JacExtended) addMixed(a *G1Affine) *g1JacExtended { // p is infinity, return a if p.ZZ.IsZero() { p.X = a.X - p.Y = a.Y + p.Y.Neg(&a.Y) p.ZZ.SetOne() p.ZZZ.SetOne() return p @@ -911,11 +937,12 @@ func (p *g1JacExtended) addMixed(a *G1Affine) *g1JacExtended { P.Sub(&P, &p.X) R.Mul(&a.Y, &p.ZZZ) + R.Neg(&R) R.Sub(&R, &p.Y) if P.IsZero() { if R.IsZero() { - return p.doubleMixed(a) + return p.doubleNegMixed(a) } p.ZZ = fp.Element{} @@ -942,21 +969,21 @@ func (p *g1JacExtended) addMixed(a *G1Affine) *g1JacExtended { } -// doubleNegMixed same as double, but will negate q.Y -func (p *g1JacExtended) doubleNegMixed(q *G1Affine) *g1JacExtended { +// doubleNegMixed works the same as double, but negates q.Y. +func (p *g1JacExtended) doubleNegMixed(a *G1Affine) *g1JacExtended { var U, V, W, S, XX, M, S2, L fp.Element - U.Double(&q.Y) + U.Double(&a.Y) U.Neg(&U) V.Square(&U) W.Mul(&U, &V) - S.Mul(&q.X, &V) - XX.Square(&q.X) + S.Mul(&a.X, &V) + XX.Square(&a.X) M.Double(&XX). - Add(&M, &XX) // -> + a, but a=0 here + Add(&M, &XX) // -> + A, but A=0 here S2.Double(&S) - L.Mul(&W, &q.Y) + L.Mul(&W, &a.Y) p.X.Square(&M). Sub(&p.X, &S2) @@ -969,21 +996,22 @@ func (p *g1JacExtended) doubleNegMixed(q *G1Affine) *g1JacExtended { return p } -// doubleMixed point in Jacobian extended coordinates +// doubleMixed sets p to [2]a in Jacobian extended coordinates, where a.ZZ=1. +// // http://www.hyperelliptic.org/EFD/g1p/auto-shortw-xyzz.html#doubling-dbl-2008-s-1 -func (p *g1JacExtended) doubleMixed(q *G1Affine) *g1JacExtended { +func (p *g1JacExtended) doubleMixed(a *G1Affine) *g1JacExtended { var U, V, W, S, XX, M, S2, L fp.Element - U.Double(&q.Y) + U.Double(&a.Y) V.Square(&U) W.Mul(&U, &V) - S.Mul(&q.X, &V) - XX.Square(&q.X) + S.Mul(&a.X, &V) + XX.Square(&a.X) M.Double(&XX). - Add(&M, &XX) // -> + a, but a=0 here + Add(&M, &XX) // -> + A, but A=0 here S2.Double(&S) - L.Mul(&W, &q.Y) + L.Mul(&W, &a.Y) p.X.Square(&M). Sub(&p.X, &S2) @@ -997,7 +1025,7 @@ func (p *g1JacExtended) doubleMixed(q *G1Affine) *g1JacExtended { } // BatchJacobianToAffineG1 converts points in Jacobian coordinates to Affine coordinates -// performing a single field inversion (Montgomery batch inversion trick). +// performing a single field inversion using the Montgomery batch inversion trick. func BatchJacobianToAffineG1(points []G1Jac) []G1Affine { result := make([]G1Affine, len(points)) zeroes := make([]bool, len(points)) @@ -1047,7 +1075,7 @@ func BatchJacobianToAffineG1(points []G1Jac) []G1Affine { // BatchScalarMultiplicationG1 multiplies the same base by all scalars // and return resulting points in affine coordinates -// uses a simple windowed-NAF like exponentiation algorithm +// uses a simple windowed-NAF-like multiplication algorithm. func BatchScalarMultiplicationG1(base *G1Affine, scalars []fr.Element) []G1Affine { // approximate cost in group ops is // cost = 2^{c-1} + n(scalar.nbBits+nbChunks) @@ -1129,9 +1157,8 @@ func BatchScalarMultiplicationG1(base *G1Affine, scalars []fr.Element) []G1Affin return toReturnAff } -// batch add affine coordinates -// using batch inversion -// special cases (doubling, infinity) must be filtered out before this call +// batchAddG1Affine adds affine points using the Montgomery batch inversion trick. +// Special cases (doubling, infinity) must be filtered out before this call. func batchAddG1Affine[TP pG1Affine, TPP ppG1Affine, TC cG1Affine](R *TPP, P *TP, batchSize int) { var lambda, lambdain TC diff --git a/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/g2.go b/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/g2.go index 5d49b49366..424d939d5e 100644 --- a/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/g2.go +++ b/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/g2.go @@ -17,6 +17,7 @@ package bls12381 import ( + "crypto/rand" "github.com/consensys/gnark-crypto/ecc" "github.com/consensys/gnark-crypto/ecc/bls12-381/fr" "github.com/consensys/gnark-crypto/ecc/bls12-381/internal/fptower" @@ -25,17 +26,17 @@ import ( "runtime" ) -// G2Affine point in affine coordinates +// G2Affine is a point in affine coordinates (x,y) type G2Affine struct { X, Y fptower.E2 } -// G2Jac is a point with fptower.E2 coordinates +// G2Jac is a point in Jacobian coordinates (x=X/Z², y=Y/Z³) type G2Jac struct { X, Y, Z fptower.E2 } -// g2JacExtended parameterized Jacobian coordinates (x=X/ZZ, y=Y/ZZZ, ZZ³=ZZZ²) +// g2JacExtended is a point in extended Jacobian coordinates (x=X/ZZ, y=Y/ZZZ, ZZ³=ZZZ²) type g2JacExtended struct { X, Y, ZZ, ZZZ fptower.E2 } @@ -46,22 +47,24 @@ type g2Proj struct { } // ------------------------------------------------------------------------------------------------- -// Affine +// Affine coordinates -// Set sets p to the provided point +// Set sets p to a in affine coordinates. func (p *G2Affine) Set(a *G2Affine) *G2Affine { p.X, p.Y = a.X, a.Y return p } -// setInfinity sets p to O +// setInfinity sets p to the infinity point, which is encoded as (0,0). +// N.B.: (0,0) is never on the curve for j=0 curves (Y²=X³+B). func (p *G2Affine) setInfinity() *G2Affine { p.X.SetZero() p.Y.SetZero() return p } -// ScalarMultiplication computes and returns p = a ⋅ s +// ScalarMultiplication computes and returns p = [s]a +// where p and a are affine points. func (p *G2Affine) ScalarMultiplication(a *G2Affine, s *big.Int) *G2Affine { var _p G2Jac _p.FromAffine(a) @@ -70,7 +73,8 @@ func (p *G2Affine) ScalarMultiplication(a *G2Affine, s *big.Int) *G2Affine { return p } -// ScalarMultiplicationBase computes and returns p = g ⋅ s where g is the prime subgroup generator +// ScalarMultiplicationBase computes and returns p = [s]g +// where g is the affine point generating the prime subgroup. func (p *G2Affine) ScalarMultiplicationBase(s *big.Int) *G2Affine { var _p G2Jac _p.mulGLV(&g2Gen, s) @@ -78,8 +82,9 @@ func (p *G2Affine) ScalarMultiplicationBase(s *big.Int) *G2Affine { return p } -// Add adds two point in affine coordinates. -// Jacobian addition with Z1=Z2=1 +// Add adds two points in affine coordinates. +// It uses the Jacobian addition with a.Z=b.Z=1 and converts the result to affine coordinates. +// // https://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-mmadd-2007-bl func (p *G2Affine) Add(a, b *G2Affine) *G2Affine { var q G2Jac @@ -125,6 +130,10 @@ func (p *G2Affine) Add(a, b *G2Affine) *G2Affine { } // Double doubles a point in affine coordinates. +// It converts the point to Jacobian coordinates, doubles it using Jacobian +// addition with a.Z=1, and converts it back to affine coordinates. +// +// http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-mdbl-2007-bl func (p *G2Affine) Double(a *G2Affine) *G2Affine { var q G2Jac q.FromAffine(a) @@ -133,7 +142,8 @@ func (p *G2Affine) Double(a *G2Affine) *G2Affine { return p } -// Sub subs two point in affine coordinates. +// Sub subtracts two points in affine coordinates. +// It uses a similar approach to Add, but negates the second point before adding. func (p *G2Affine) Sub(a, b *G2Affine) *G2Affine { var bneg G2Affine bneg.Neg(b) @@ -141,19 +151,19 @@ func (p *G2Affine) Sub(a, b *G2Affine) *G2Affine { return p } -// Equal tests if two points (in Affine coordinates) are equal +// Equal tests if two points in affine coordinates are equal. func (p *G2Affine) Equal(a *G2Affine) bool { return p.X.Equal(&a.X) && p.Y.Equal(&a.Y) } -// Neg computes -G +// Neg sets p to the affine negative point -a = (a.X, -a.Y). func (p *G2Affine) Neg(a *G2Affine) *G2Affine { p.X = a.X p.Y.Neg(&a.Y) return p } -// FromJacobian rescales a point in Jacobian coord in z=1 plane +// FromJacobian converts a point p1 from Jacobian to affine coordinates. func (p *G2Affine) FromJacobian(p1 *G2Jac) *G2Affine { var a, b fptower.E2 @@ -172,7 +182,7 @@ func (p *G2Affine) FromJacobian(p1 *G2Jac) *G2Affine { return p } -// String returns the string representation of the point or "O" if it is infinity +// String returns the string representation E(x,y) of the affine point p or "O" if it is infinity. func (p *G2Affine) String() string { if p.IsInfinity() { return "O" @@ -180,21 +190,20 @@ func (p *G2Affine) String() string { return "E([" + p.X.String() + "," + p.Y.String() + "])" } -// IsInfinity checks if the point is infinity -// in affine, it's encoded as (0,0) -// (0,0) is never on the curve for j=0 curves +// IsInfinity checks if the affine point p is infinity, which is encoded as (0,0). +// N.B.: (0,0) is never on the curve for j=0 curves (Y²=X³+B). func (p *G2Affine) IsInfinity() bool { return p.X.IsZero() && p.Y.IsZero() } -// IsOnCurve returns true if p in on the curve +// IsOnCurve returns true if the affine point p in on the curve. func (p *G2Affine) IsOnCurve() bool { var point G2Jac point.FromAffine(p) return point.IsOnCurve() // call this function to handle infinity point } -// IsInSubGroup returns true if p is in the correct subgroup, false otherwise +// IsInSubGroup returns true if the affine point p is in the correct subgroup, false otherwise. func (p *G2Affine) IsInSubGroup() bool { var _p G2Jac _p.FromAffine(p) @@ -202,84 +211,76 @@ func (p *G2Affine) IsInSubGroup() bool { } // ------------------------------------------------------------------------------------------------- -// Jacobian +// Jacobian coordinates -// Set sets p to the provided point -func (p *G2Jac) Set(a *G2Jac) *G2Jac { - p.X, p.Y, p.Z = a.X, a.Y, a.Z +// Set sets p to a in Jacobian coordinates. +func (p *G2Jac) Set(q *G2Jac) *G2Jac { + p.X, p.Y, p.Z = q.X, q.Y, q.Z return p } -// Equal tests if two points (in Jacobian coordinates) are equal -func (p *G2Jac) Equal(a *G2Jac) bool { +// Equal tests if two points in Jacobian coordinates are equal. +func (p *G2Jac) Equal(q *G2Jac) bool { // If one point is infinity, the other must also be infinity. if p.Z.IsZero() { - return a.Z.IsZero() + return q.Z.IsZero() } // If the other point is infinity, return false since we can't // the following checks would be incorrect. - if a.Z.IsZero() { + if q.Z.IsZero() { return false } var pZSquare, aZSquare fptower.E2 pZSquare.Square(&p.Z) - aZSquare.Square(&a.Z) + aZSquare.Square(&q.Z) var lhs, rhs fptower.E2 lhs.Mul(&p.X, &aZSquare) - rhs.Mul(&a.X, &pZSquare) + rhs.Mul(&q.X, &pZSquare) if !lhs.Equal(&rhs) { return false } - lhs.Mul(&p.Y, &aZSquare).Mul(&lhs, &a.Z) - rhs.Mul(&a.Y, &pZSquare).Mul(&rhs, &p.Z) + lhs.Mul(&p.Y, &aZSquare).Mul(&lhs, &q.Z) + rhs.Mul(&q.Y, &pZSquare).Mul(&rhs, &p.Z) return lhs.Equal(&rhs) } -// Neg computes -G -func (p *G2Jac) Neg(a *G2Jac) *G2Jac { - *p = *a - p.Y.Neg(&a.Y) +// Neg sets p to the Jacobian negative point -q = (q.X, -q.Y, q.Z). +func (p *G2Jac) Neg(q *G2Jac) *G2Jac { + *p = *q + p.Y.Neg(&q.Y) return p } -// SubAssign subtracts two points on the curve -func (p *G2Jac) SubAssign(a *G2Jac) *G2Jac { - var tmp G2Jac - tmp.Set(a) - tmp.Y.Neg(&tmp.Y) - p.AddAssign(&tmp) - return p -} - -// AddAssign point addition in montgomery form +// AddAssign sets p to p+a in Jacobian coordinates. +// // https://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#addition-add-2007-bl -func (p *G2Jac) AddAssign(a *G2Jac) *G2Jac { +func (p *G2Jac) AddAssign(q *G2Jac) *G2Jac { - // p is infinity, return a + // p is infinity, return q if p.Z.IsZero() { - p.Set(a) + p.Set(q) return p } - // a is infinity, return p - if a.Z.IsZero() { + // q is infinity, return p + if q.Z.IsZero() { return p } var Z1Z1, Z2Z2, U1, U2, S1, S2, H, I, J, r, V fptower.E2 - Z1Z1.Square(&a.Z) + Z1Z1.Square(&q.Z) Z2Z2.Square(&p.Z) - U1.Mul(&a.X, &Z2Z2) + U1.Mul(&q.X, &Z2Z2) U2.Mul(&p.X, &Z1Z1) - S1.Mul(&a.Y, &p.Z). + S1.Mul(&q.Y, &p.Z). Mul(&S1, &Z2Z2) - S2.Mul(&p.Y, &a.Z). + S2.Mul(&p.Y, &q.Z). Mul(&S2, &Z1Z1) - // if p == a, we double instead + // if p == q, we double instead if U1.Equal(&U2) && S1.Equal(&S2) { return p.DoubleAssign() } @@ -298,7 +299,7 @@ func (p *G2Jac) AddAssign(a *G2Jac) *G2Jac { Mul(&p.Y, &r) S1.Mul(&S1, &J).Double(&S1) p.Y.Sub(&p.Y, &S1) - p.Z.Add(&p.Z, &a.Z) + p.Z.Add(&p.Z, &q.Z) p.Z.Square(&p.Z). Sub(&p.Z, &Z1Z1). Sub(&p.Z, &Z2Z2). @@ -307,8 +308,19 @@ func (p *G2Jac) AddAssign(a *G2Jac) *G2Jac { return p } -// DoubleMixed point addition -// http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-mdbl-2007-bl +// SubAssign sets p to p-a in Jacobian coordinates. +// It uses a similar approach to AddAssign, but negates the point a before adding. +func (p *G2Jac) SubAssign(q *G2Jac) *G2Jac { + var tmp G2Jac + tmp.Set(q) + tmp.Y.Neg(&tmp.Y) + p.AddAssign(&tmp) + return p +} + +// Double sets p to [2]q in Jacobian coordinates. +// +// https://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2007-bl func (p *G2Jac) DoubleMixed(a *G2Affine) *G2Jac { var XX, YY, YYYY, S, M, T fptower.E2 XX.Square(&a.X) @@ -320,7 +332,7 @@ func (p *G2Jac) DoubleMixed(a *G2Affine) *G2Jac { Sub(&S, &YYYY). Double(&S) M.Double(&XX). - Add(&M, &XX) // -> + a, but a=0 here + Add(&M, &XX) // -> + A, but A=0 here T.Square(&M). Sub(&T, &S). Sub(&T, &S) @@ -336,7 +348,8 @@ func (p *G2Jac) DoubleMixed(a *G2Affine) *G2Jac { return p } -// AddMixed point addition +// AddMixed sets p to p+a in Jacobian coordinates, where a.Z = 1. +// // http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-madd-2007-bl func (p *G2Jac) AddMixed(a *G2Affine) *G2Jac { @@ -385,7 +398,8 @@ func (p *G2Jac) AddMixed(a *G2Affine) *G2Jac { return p } -// Double doubles a point in Jacobian coordinates +// Double sets p to [2]q in Jacobian coordinates. +// // https://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2007-bl func (p *G2Jac) Double(q *G2Jac) *G2Jac { p.Set(q) @@ -393,7 +407,8 @@ func (p *G2Jac) Double(q *G2Jac) *G2Jac { return p } -// DoubleAssign doubles a point in Jacobian coordinates +// DoubleAssign doubles p in Jacobian coordinates. +// // https://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2007-bl func (p *G2Jac) DoubleAssign() *G2Jac { @@ -425,39 +440,43 @@ func (p *G2Jac) DoubleAssign() *G2Jac { return p } -// ScalarMultiplication computes and returns p = a ⋅ s +// ScalarMultiplication computes and returns p = [s]a +// where p and a are Jacobian points. +// using the GLV technique. // see https://www.iacr.org/archive/crypto2001/21390189.pdf -func (p *G2Jac) ScalarMultiplication(a *G2Jac, s *big.Int) *G2Jac { - return p.mulGLV(a, s) +func (p *G2Jac) ScalarMultiplication(q *G2Jac, s *big.Int) *G2Jac { + return p.mulGLV(q, s) } -// ScalarMultiplicationBase computes and returns p = g ⋅ s where g is the prime subgroup generator +// ScalarMultiplicationBase computes and returns p = [s]g +// where g is the prime subgroup generator. func (p *G2Jac) ScalarMultiplicationBase(s *big.Int) *G2Jac { return p.mulGLV(&g2Gen, s) + } -// String returns canonical representation of the point in affine coordinates +// String converts p to affine coordinates and returns its string representation E(x,y) or "O" if it is infinity. func (p *G2Jac) String() string { _p := G2Affine{} _p.FromJacobian(p) return _p.String() } -// FromAffine sets p = Q, p in Jacobian, Q in affine -func (p *G2Jac) FromAffine(Q *G2Affine) *G2Jac { - if Q.IsInfinity() { +// FromAffine converts a point a from affine to Jacobian coordinates. +func (p *G2Jac) FromAffine(a *G2Affine) *G2Jac { + if a.IsInfinity() { p.Z.SetZero() p.X.SetOne() p.Y.SetOne() return p } p.Z.SetOne() - p.X.Set(&Q.X) - p.Y.Set(&Q.Y) + p.X.Set(&a.X) + p.Y.Set(&a.Y) return p } -// IsOnCurve returns true if p in on the curve +// IsOnCurve returns true if the Jacobian point p in on the curve. func (p *G2Jac) IsOnCurve() bool { var left, right, tmp, ZZ fptower.E2 left.Square(&p.Y) @@ -482,13 +501,14 @@ func (p *G2Jac) IsInSubGroup() bool { return res.IsOnCurve() && res.Z.IsZero() } -// mulWindowed computes a 2-bits windowed scalar multiplication -func (p *G2Jac) mulWindowed(a *G2Jac, s *big.Int) *G2Jac { +// mulWindowed computes the 2-bits windowed double-and-add scalar +// multiplication p=[s]q in Jacobian coordinates. +func (p *G2Jac) mulWindowed(q *G2Jac, s *big.Int) *G2Jac { var res G2Jac var ops [3]G2Jac - ops[0].Set(a) + ops[0].Set(q) if s.Sign() == -1 { ops[0].Neg(&ops[0]) } @@ -515,26 +535,27 @@ func (p *G2Jac) mulWindowed(a *G2Jac, s *big.Int) *G2Jac { } -// ψ(p) = u o π o u⁻¹ where u:E'→E iso from the twist to E -func (p *G2Jac) psi(a *G2Jac) *G2Jac { - p.Set(a) +// psi sets p to ψ(q) = u o π o u⁻¹ where u:E'→E is the isomorphism from the twist to the curve E and π is the Frobenius map. +func (p *G2Jac) psi(q *G2Jac) *G2Jac { + p.Set(q) p.X.Conjugate(&p.X).Mul(&p.X, &endo.u) p.Y.Conjugate(&p.Y).Mul(&p.Y, &endo.v) p.Z.Conjugate(&p.Z) return p } -// ϕ assigns p to ϕ(a) where ϕ: (x,y) → (w x,y), and returns p -// where w is a third root of unity in 𝔽p -func (p *G2Jac) phi(a *G2Jac) *G2Jac { - p.Set(a) +// phi sets p to ϕ(a) where ϕ: (x,y) → (w x,y), +// where w is a third root of unity. +func (p *G2Jac) phi(q *G2Jac) *G2Jac { + p.Set(q) p.X.MulByElement(&p.X, &thirdRootOneG2) return p } // mulGLV computes the scalar multiplication using a windowed-GLV method +// // see https://www.iacr.org/archive/crypto2001/21390189.pdf -func (p *G2Jac) mulGLV(a *G2Jac, s *big.Int) *G2Jac { +func (p *G2Jac) mulGLV(q *G2Jac, s *big.Int) *G2Jac { var table [15]G2Jac var res G2Jac @@ -542,11 +563,11 @@ func (p *G2Jac) mulGLV(a *G2Jac, s *big.Int) *G2Jac { res.Set(&g2Infinity) - // table[b3b2b1b0-1] = b3b2 ⋅ ϕ(a) + b1b0*a - table[0].Set(a) - table[3].phi(a) + // table[b3b2b1b0-1] = b3b2 ⋅ ϕ(q) + b1b0*q + table[0].Set(q) + table[3].phi(q) - // split the scalar, modifies ±a, ϕ(a) accordingly + // split the scalar, modifies ±q, ϕ(q) accordingly k := ecc.SplitScalar(s, &glvBasis) if k[0].Sign() == -1 { @@ -559,7 +580,7 @@ func (p *G2Jac) mulGLV(a *G2Jac, s *big.Int) *G2Jac { } // precompute table (2 bits sliding window) - // table[b3b2b1b0-1] = b3b2 ⋅ ϕ(a) + b1b0 ⋅ a if b3b2b1b0 != 0 + // table[b3b2b1b0-1] = b3b2 ⋅ ϕ(q) + b1b0 ⋅ q if b3b2b1b0 != 0 table[1].Double(&table[0]) table[2].Set(&table[1]).AddAssign(&table[0]) table[4].Set(&table[3]).AddAssign(&table[0]) @@ -615,23 +636,23 @@ func (p *G2Affine) ClearCofactor(a *G2Affine) *G2Affine { } // ClearCofactor maps a point in curve to r-torsion -func (p *G2Jac) ClearCofactor(a *G2Jac) *G2Jac { +func (p *G2Jac) ClearCofactor(q *G2Jac) *G2Jac { // https://eprint.iacr.org/2017/419.pdf, 4.1 var xg, xxg, res, t G2Jac - xg.ScalarMultiplication(a, &xGen).Neg(&xg) + xg.ScalarMultiplication(q, &xGen).Neg(&xg) xxg.ScalarMultiplication(&xg, &xGen).Neg(&xxg) res.Set(&xxg). SubAssign(&xg). - SubAssign(a) + SubAssign(q) t.Set(&xg). - SubAssign(a). + SubAssign(q). psi(&t) res.AddAssign(&t) - t.Double(a) + t.Double(q) t.X.MulByElement(&t.X, &thirdRootOneG1) res.SubAssign(&t) @@ -643,15 +664,15 @@ func (p *G2Jac) ClearCofactor(a *G2Jac) *G2Jac { } // ------------------------------------------------------------------------------------------------- -// Jacobian extended +// extended Jacobian coordinates -// Set sets p to the provided point -func (p *g2JacExtended) Set(a *g2JacExtended) *g2JacExtended { - p.X, p.Y, p.ZZ, p.ZZZ = a.X, a.Y, a.ZZ, a.ZZZ +// Set sets p to a in extended Jacobian coordinates. +func (p *g2JacExtended) Set(q *g2JacExtended) *g2JacExtended { + p.X, p.Y, p.ZZ, p.ZZZ = q.X, q.Y, q.ZZ, q.ZZZ return p } -// setInfinity sets p to O +// setInfinity sets p to the infinity point (1,1,0,0). func (p *g2JacExtended) setInfinity() *g2JacExtended { p.X.SetOne() p.Y.SetOne() @@ -660,43 +681,45 @@ func (p *g2JacExtended) setInfinity() *g2JacExtended { return p } -func (p *g2JacExtended) IsZero() bool { +// IsInfinity checks if the p is infinity, i.e. p.ZZ=0. +func (p *g2JacExtended) IsInfinity() bool { return p.ZZ.IsZero() } -// fromJacExtended sets Q in affine coordinates -func (p *G2Affine) fromJacExtended(Q *g2JacExtended) *G2Affine { - if Q.ZZ.IsZero() { +// fromJacExtended converts an extended Jacobian point to an affine point. +func (p *G2Affine) fromJacExtended(q *g2JacExtended) *G2Affine { + if q.ZZ.IsZero() { p.X = fptower.E2{} p.Y = fptower.E2{} return p } - p.X.Inverse(&Q.ZZ).Mul(&p.X, &Q.X) - p.Y.Inverse(&Q.ZZZ).Mul(&p.Y, &Q.Y) + p.X.Inverse(&q.ZZ).Mul(&p.X, &q.X) + p.Y.Inverse(&q.ZZZ).Mul(&p.Y, &q.Y) return p } -// fromJacExtended sets Q in Jacobian coordinates -func (p *G2Jac) fromJacExtended(Q *g2JacExtended) *G2Jac { - if Q.ZZ.IsZero() { +// fromJacExtended converts an extended Jacobian point to a Jacobian point. +func (p *G2Jac) fromJacExtended(q *g2JacExtended) *G2Jac { + if q.ZZ.IsZero() { p.Set(&g2Infinity) return p } - p.X.Mul(&Q.ZZ, &Q.X).Mul(&p.X, &Q.ZZ) - p.Y.Mul(&Q.ZZZ, &Q.Y).Mul(&p.Y, &Q.ZZZ) - p.Z.Set(&Q.ZZZ) + p.X.Mul(&q.ZZ, &q.X).Mul(&p.X, &q.ZZ) + p.Y.Mul(&q.ZZZ, &q.Y).Mul(&p.Y, &q.ZZZ) + p.Z.Set(&q.ZZZ) return p } -// unsafeFromJacExtended sets p in Jacobian coordinates, but don't check for infinity -func (p *G2Jac) unsafeFromJacExtended(Q *g2JacExtended) *G2Jac { - p.X.Square(&Q.ZZ).Mul(&p.X, &Q.X) - p.Y.Square(&Q.ZZZ).Mul(&p.Y, &Q.Y) - p.Z = Q.ZZZ +// unsafeFromJacExtended converts an extended Jacobian point, distinct from Infinity, to a Jacobian point. +func (p *G2Jac) unsafeFromJacExtended(q *g2JacExtended) *G2Jac { + p.X.Square(&q.ZZ).Mul(&p.X, &q.X) + p.Y.Square(&q.ZZZ).Mul(&p.Y, &q.Y) + p.Z = q.ZZZ return p } -// add point in Jacobian extended coordinates +// add sets p to p+q in extended Jacobian coordinates. +// // https://www.hyperelliptic.org/EFD/g1p/auto-shortw-xyzz.html#addition-add-2008-s func (p *g2JacExtended) add(q *g2JacExtended) *g2JacExtended { //if q is infinity return p @@ -752,10 +775,11 @@ func (p *g2JacExtended) add(q *g2JacExtended) *g2JacExtended { return p } -// double point in Jacobian extended coordinates +// double sets p to [2]q in Jacobian extended coordinates. +// // http://www.hyperelliptic.org/EFD/g1p/auto-shortw-xyzz.html#doubling-dbl-2008-s-1 -// since we consider any point on Z=0 as the point at infinity -// this doubling formula works for infinity points as well +// N.B.: since we consider any point on Z=0 as the point at infinity +// this doubling formula works for infinity points as well. func (p *g2JacExtended) double(q *g2JacExtended) *g2JacExtended { var U, V, W, S, XX, M fptower.E2 @@ -765,7 +789,7 @@ func (p *g2JacExtended) double(q *g2JacExtended) *g2JacExtended { S.Mul(&q.X, &V) XX.Square(&q.X) M.Double(&XX). - Add(&M, &XX) // -> + a, but a=0 here + Add(&M, &XX) // -> + A, but A=0 here U.Mul(&W, &q.Y) p.X.Square(&M). @@ -780,9 +804,10 @@ func (p *g2JacExtended) double(q *g2JacExtended) *g2JacExtended { return p } -// subMixed same as addMixed, but will negate a.Y +// addMixed sets p to p+q in extended Jacobian coordinates, where a.ZZ=1. +// // http://www.hyperelliptic.org/EFD/g1p/auto-shortw-xyzz.html#addition-madd-2008-s -func (p *g2JacExtended) subMixed(a *G2Affine) *g2JacExtended { +func (p *g2JacExtended) addMixed(a *G2Affine) *g2JacExtended { //if a is infinity return p if a.IsInfinity() { @@ -791,7 +816,7 @@ func (p *g2JacExtended) subMixed(a *G2Affine) *g2JacExtended { // p is infinity, return a if p.ZZ.IsZero() { p.X = a.X - p.Y.Neg(&a.Y) + p.Y = a.Y p.ZZ.SetOne() p.ZZZ.SetOne() return p @@ -804,12 +829,11 @@ func (p *g2JacExtended) subMixed(a *G2Affine) *g2JacExtended { P.Sub(&P, &p.X) R.Mul(&a.Y, &p.ZZZ) - R.Neg(&R) R.Sub(&R, &p.Y) if P.IsZero() { if R.IsZero() { - return p.doubleNegMixed(a) + return p.doubleMixed(a) } p.ZZ = fptower.E2{} @@ -836,9 +860,10 @@ func (p *g2JacExtended) subMixed(a *G2Affine) *g2JacExtended { } -// addMixed +// subMixed works the same as addMixed, but negates a.Y. +// // http://www.hyperelliptic.org/EFD/g1p/auto-shortw-xyzz.html#addition-madd-2008-s -func (p *g2JacExtended) addMixed(a *G2Affine) *g2JacExtended { +func (p *g2JacExtended) subMixed(a *G2Affine) *g2JacExtended { //if a is infinity return p if a.IsInfinity() { @@ -847,7 +872,7 @@ func (p *g2JacExtended) addMixed(a *G2Affine) *g2JacExtended { // p is infinity, return a if p.ZZ.IsZero() { p.X = a.X - p.Y = a.Y + p.Y.Neg(&a.Y) p.ZZ.SetOne() p.ZZZ.SetOne() return p @@ -860,11 +885,12 @@ func (p *g2JacExtended) addMixed(a *G2Affine) *g2JacExtended { P.Sub(&P, &p.X) R.Mul(&a.Y, &p.ZZZ) + R.Neg(&R) R.Sub(&R, &p.Y) if P.IsZero() { if R.IsZero() { - return p.doubleMixed(a) + return p.doubleNegMixed(a) } p.ZZ = fptower.E2{} @@ -891,21 +917,21 @@ func (p *g2JacExtended) addMixed(a *G2Affine) *g2JacExtended { } -// doubleNegMixed same as double, but will negate q.Y -func (p *g2JacExtended) doubleNegMixed(q *G2Affine) *g2JacExtended { +// doubleNegMixed works the same as double, but negates q.Y. +func (p *g2JacExtended) doubleNegMixed(a *G2Affine) *g2JacExtended { var U, V, W, S, XX, M, S2, L fptower.E2 - U.Double(&q.Y) + U.Double(&a.Y) U.Neg(&U) V.Square(&U) W.Mul(&U, &V) - S.Mul(&q.X, &V) - XX.Square(&q.X) + S.Mul(&a.X, &V) + XX.Square(&a.X) M.Double(&XX). - Add(&M, &XX) // -> + a, but a=0 here + Add(&M, &XX) // -> + A, but A=0 here S2.Double(&S) - L.Mul(&W, &q.Y) + L.Mul(&W, &a.Y) p.X.Square(&M). Sub(&p.X, &S2) @@ -918,21 +944,22 @@ func (p *g2JacExtended) doubleNegMixed(q *G2Affine) *g2JacExtended { return p } -// doubleMixed point in Jacobian extended coordinates +// doubleMixed sets p to [2]a in Jacobian extended coordinates, where a.ZZ=1. +// // http://www.hyperelliptic.org/EFD/g1p/auto-shortw-xyzz.html#doubling-dbl-2008-s-1 -func (p *g2JacExtended) doubleMixed(q *G2Affine) *g2JacExtended { +func (p *g2JacExtended) doubleMixed(a *G2Affine) *g2JacExtended { var U, V, W, S, XX, M, S2, L fptower.E2 - U.Double(&q.Y) + U.Double(&a.Y) V.Square(&U) W.Mul(&U, &V) - S.Mul(&q.X, &V) - XX.Square(&q.X) + S.Mul(&a.X, &V) + XX.Square(&a.X) M.Double(&XX). - Add(&M, &XX) // -> + a, but a=0 here + Add(&M, &XX) // -> + A, but A=0 here S2.Double(&S) - L.Mul(&W, &q.Y) + L.Mul(&W, &a.Y) p.X.Square(&M). Sub(&p.X, &S2) @@ -946,38 +973,38 @@ func (p *g2JacExtended) doubleMixed(q *G2Affine) *g2JacExtended { } // ------------------------------------------------------------------------------------------------- -// Homogenous projective +// Homogenous projective coordinates -// Set sets p to the provided point -func (p *g2Proj) Set(a *g2Proj) *g2Proj { - p.x, p.y, p.z = a.x, a.y, a.z +// Set sets p to a in projective coordinates. +func (p *g2Proj) Set(q *g2Proj) *g2Proj { + p.x, p.y, p.z = q.x, q.y, q.z return p } -// Neg computes -G -func (p *g2Proj) Neg(a *g2Proj) *g2Proj { - *p = *a - p.y.Neg(&a.y) +// Neg sets p to the projective negative point -q = (q.X, -q.Y). +func (p *g2Proj) Neg(q *g2Proj) *g2Proj { + *p = *q + p.y.Neg(&q.y) return p } -// FromAffine sets p = Q, p in homogenous projective, Q in affine -func (p *g2Proj) FromAffine(Q *G2Affine) *g2Proj { - if Q.X.IsZero() && Q.Y.IsZero() { +// FromAffine converts q in affine to p in projective coordinates. +func (p *g2Proj) FromAffine(a *G2Affine) *g2Proj { + if a.X.IsZero() && a.Y.IsZero() { p.z.SetZero() p.x.SetOne() p.y.SetOne() return p } p.z.SetOne() - p.x.Set(&Q.X) - p.y.Set(&Q.Y) + p.x.Set(&a.X) + p.y.Set(&a.Y) return p } // BatchScalarMultiplicationG2 multiplies the same base by all scalars // and return resulting points in affine coordinates -// uses a simple windowed-NAF like exponentiation algorithm +// uses a simple windowed-NAF-like multiplication algorithm. func BatchScalarMultiplicationG2(base *G2Affine, scalars []fr.Element) []G2Affine { // approximate cost in group ops is // cost = 2^{c-1} + n(scalar.nbBits+nbChunks) @@ -1056,9 +1083,8 @@ func BatchScalarMultiplicationG2(base *G2Affine, scalars []fr.Element) []G2Affin return toReturn } -// batch add affine coordinates -// using batch inversion -// special cases (doubling, infinity) must be filtered out before this call +// batchAddG2Affine adds affine points using the Montgomery batch inversion trick. +// Special cases (doubling, infinity) must be filtered out before this call. func batchAddG2Affine[TP pG2Affine, TPP ppG2Affine, TC cG2Affine](R *TPP, P *TP, batchSize int) { var lambda, lambdain TC @@ -1106,3 +1132,20 @@ func batchAddG2Affine[TP pG2Affine, TPP ppG2Affine, TC cG2Affine](R *TPP, P *TP, (*R)[j].Set(&rr) } } + +// RandomOnG2 produces a random point in G2 +// using standard map-to-curve methods, which means the relative discrete log +// of the generated point with respect to the canonical generator is not known. +func RandomOnG2() (G2Affine, error) { + if gBytes, err := randomFrSizedBytes(); err != nil { + return G2Affine{}, err + } else { + return HashToG2(gBytes, []byte("random on g2")) + } +} + +func randomFrSizedBytes() ([]byte, error) { + res := make([]byte, fr.Bytes) + _, err := rand.Read(res) + return res, err +} diff --git a/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/internal/fptower/e12.go b/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/internal/fptower/e12.go index 095a79a4c0..65945c3d9d 100644 --- a/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/internal/fptower/e12.go +++ b/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/internal/fptower/e12.go @@ -67,14 +67,14 @@ func (z *E12) SetOne() *E12 { return z } -// Add set z=x+y in E12 and return z +// Add sets z=x+y in E12 and returns z func (z *E12) Add(x, y *E12) *E12 { z.C0.Add(&x.C0, &y.C0) z.C1.Add(&x.C1, &y.C1) return z } -// Sub sets z to x sub y and return z +// Sub sets z to x-y and returns z func (z *E12) Sub(x, y *E12) *E12 { z.C0.Sub(&x.C0, &y.C0) z.C1.Sub(&x.C1, &y.C1) @@ -99,16 +99,17 @@ func (z *E12) SetRandom() (*E12, error) { return z, nil } -// IsZero returns true if the two elements are equal, false otherwise +// IsZero returns true if z is zero, false otherwise func (z *E12) IsZero() bool { return z.C0.IsZero() && z.C1.IsZero() } +// IsOne returns true if z is one, false otherwise func (z *E12) IsOne() bool { return z.C0.IsOne() && z.C1.IsZero() } -// Mul set z=x*y in E12 and return z +// Mul sets z=x*y in E12 and returns z func (z *E12) Mul(x, y *E12) *E12 { var a, b, c E6 a.Add(&x.C0, &x.C1) @@ -121,7 +122,7 @@ func (z *E12) Mul(x, y *E12) *E12 { return z } -// Square set z=x*x in E12 and return z +// Square sets z=x*x in E12 and returns z func (z *E12) Square(x *E12) *E12 { //Algorithm 22 from https://eprint.iacr.org/2010/354.pdf @@ -406,7 +407,7 @@ func (z *E12) CyclotomicSquare(x *E12) *E12 { return z } -// Inverse set z to the inverse of x in E12 and return z +// Inverse sets z to the inverse of x in E12 and returns z // // if x == 0, sets and returns z = x func (z *E12) Inverse(x *E12) *E12 { @@ -424,8 +425,8 @@ func (z *E12) Inverse(x *E12) *E12 { return z } -// BatchInvertE12 returns a new slice with every element inverted. -// Uses Montgomery batch inversion trick +// BatchInvertE12 returns a new slice with every element in a inverted. +// It uses Montgomery batch inversion trick. // // if a[i] == 0, returns result[i] = a[i] func BatchInvertE12(a []E12) []E12 { @@ -635,12 +636,12 @@ func (z *E12) ExpGLV(x E12, k *big.Int) *E12 { return z } -// InverseUnitary inverse a unitary element +// InverseUnitary inverses a unitary element func (z *E12) InverseUnitary(x *E12) *E12 { return z.Conjugate(x) } -// Conjugate set z to x conjugated and return z +// Conjugate sets z to x conjugated and returns z func (z *E12) Conjugate(x *E12) *E12 { *z = *x z.C1.Neg(&z.C1) @@ -846,6 +847,8 @@ func BatchDecompressTorus(x []E6) ([]E12, error) { return res, nil } +// Select is conditional move. +// If cond = 0, it sets z to caseZ and returns it. otherwise caseNz. func (z *E12) Select(cond int, caseZ *E12, caseNz *E12) *E12 { //Might be able to save a nanosecond or two by an aggregate implementation @@ -855,6 +858,7 @@ func (z *E12) Select(cond int, caseZ *E12, caseNz *E12) *E12 { return z } +// Div divides an element in E12 by an element in E12 func (z *E12) Div(x *E12, y *E12) *E12 { var r E12 r.Inverse(y).Mul(x, &r) diff --git a/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/internal/fptower/e2.go b/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/internal/fptower/e2.go index 0390e7e4b3..75fd711c78 100644 --- a/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/internal/fptower/e2.go +++ b/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/internal/fptower/e2.go @@ -101,11 +101,12 @@ func (z *E2) SetRandom() (*E2, error) { return z, nil } -// IsZero returns true if the two elements are equal, false otherwise +// IsZero returns true if z is zero, false otherwise func (z *E2) IsZero() bool { return z.A0.IsZero() && z.A1.IsZero() } +// IsOne returns true if z is one, false otherwise func (z *E2) IsOne() bool { return z.A0.IsOne() && z.A1.IsZero() } @@ -116,7 +117,7 @@ func (z *E2) Add(x, y *E2) *E2 { return z } -// Sub two elements of E2 +// Sub subtracts two elements of E2 func (z *E2) Sub(x, y *E2) *E2 { subE2(z, x, y) return z @@ -155,7 +156,7 @@ func (z *E2) Conjugate(x *E2) *E2 { return z } -// Halve sets z = z / 2 +// Halve sets z to z / 2 func (z *E2) Halve() { z.A0.Halve() z.A1.Halve() @@ -213,7 +214,7 @@ func init() { var sqrtExp1, sqrtExp2 big.Int -// Sqrt sets z to the square root of and returns z +// Sqrt sets z to the square root of x and returns z // The function does not test whether the square root // exists or not, it's up to the caller to call // Legendre beforehand. @@ -243,8 +244,8 @@ func (z *E2) Sqrt(x *E2) *E2 { return z } -// BatchInvertE2 returns a new slice with every element inverted. -// Uses Montgomery batch inversion trick +// BatchInvertE2 returns a new slice with every element in a inverted. +// It uses Montgomery batch inversion trick. // // if a[i] == 0, returns result[i] = a[i] func BatchInvertE2(a []E2) []E2 { @@ -279,6 +280,8 @@ func BatchInvertE2(a []E2) []E2 { return res } +// Select is conditional move. +// If cond = 0, it sets z to caseZ and returns it. otherwise caseNz. func (z *E2) Select(cond int, caseZ *E2, caseNz *E2) *E2 { //Might be able to save a nanosecond or two by an aggregate implementation @@ -288,6 +291,7 @@ func (z *E2) Select(cond int, caseZ *E2, caseNz *E2) *E2 { return z } +// Div divides an element in E2 by an element in E2 func (z *E2) Div(x *E2, y *E2) *E2 { var r E2 r.Inverse(y).Mul(x, &r) diff --git a/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/internal/fptower/e6.go b/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/internal/fptower/e6.go index 128007df27..1867470a88 100644 --- a/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/internal/fptower/e6.go +++ b/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/internal/fptower/e6.go @@ -63,11 +63,12 @@ func (z *E6) SetRandom() (*E6, error) { return z, nil } -// IsZero returns true if the two elements are equal, false otherwise +// IsZero returns true if z is zero, false otherwise func (z *E6) IsZero() bool { return z.B0.IsZero() && z.B1.IsZero() && z.B2.IsZero() } +// IsOne returns true if z is one, false otherwise func (z *E6) IsOne() bool { return z.B0.IsOne() && z.B1.IsZero() && z.B2.IsZero() } @@ -88,7 +89,7 @@ func (z *E6) Neg(x *E6) *E6 { return z } -// Sub two elements of E6 +// Sub subtracts two elements of E6 func (z *E6) Sub(x, y *E6) *E6 { z.B0.Sub(&x.B0, &y.B0) z.B1.Sub(&x.B1, &y.B1) @@ -286,8 +287,8 @@ func (z *E6) Inverse(x *E6) *E6 { return z } -// BatchInvertE6 returns a new slice with every element inverted. -// Uses Montgomery batch inversion trick +// BatchInvertE6 returns a new slice with every element in a inverted. +// It uses Montgomery batch inversion trick. // // if a[i] == 0, returns result[i] = a[i] func BatchInvertE6(a []E6) []E6 { @@ -322,6 +323,8 @@ func BatchInvertE6(a []E6) []E6 { return res } +// Select is conditional move. +// If cond = 0, it sets z to caseZ and returns it. otherwise caseNz. func (z *E6) Select(cond int, caseZ *E6, caseNz *E6) *E6 { //Might be able to save a nanosecond or two by an aggregate implementation @@ -332,6 +335,7 @@ func (z *E6) Select(cond int, caseZ *E6, caseNz *E6) *E6 { return z } +// Div divides an element in E6 by an element in E6 func (z *E6) Div(x *E6, y *E6) *E6 { var r E6 r.Inverse(y).Mul(x, &r) diff --git a/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/multiexp.go b/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/multiexp.go index 19350818ff..bfea254036 100644 --- a/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/multiexp.go +++ b/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/multiexp.go @@ -323,6 +323,31 @@ func msmReduceChunkG1Affine(p *G1Jac, c int, chChunks []chan g1JacExtended) *G1J return p.unsafeFromJacExtended(&_p) } +// Fold computes the multi-exponentiation \sum_{i=0}^{len(points)-1} points[i] * +// combinationCoeff^i and stores the result in p. It returns error in case +// configuration is invalid. +func (p *G1Affine) Fold(points []G1Affine, combinationCoeff fr.Element, config ecc.MultiExpConfig) (*G1Affine, error) { + var _p G1Jac + if _, err := _p.Fold(points, combinationCoeff, config); err != nil { + return nil, err + } + p.FromJacobian(&_p) + return p, nil +} + +// Fold computes the multi-exponentiation \sum_{i=0}^{len(points)-1} points[i] * +// combinationCoeff^i and stores the result in p. It returns error in case +// configuration is invalid. +func (p *G1Jac) Fold(points []G1Affine, combinationCoeff fr.Element, config ecc.MultiExpConfig) (*G1Jac, error) { + scalars := make([]fr.Element, len(points)) + scalar := fr.NewElement(1) + for i := 0; i < len(points); i++ { + scalars[i].Set(&scalar) + scalar.Mul(&scalar, &combinationCoeff) + } + return p.MultiExp(points, scalars, config) +} + // MultiExp implements section 4 of https://eprint.iacr.org/2012/549.pdf // // This call return an error if len(scalars) != len(points) or if provided config is invalid. @@ -621,6 +646,31 @@ func msmReduceChunkG2Affine(p *G2Jac, c int, chChunks []chan g2JacExtended) *G2J return p.unsafeFromJacExtended(&_p) } +// Fold computes the multi-exponentiation \sum_{i=0}^{len(points)-1} points[i] * +// combinationCoeff^i and stores the result in p. It returns error in case +// configuration is invalid. +func (p *G2Affine) Fold(points []G2Affine, combinationCoeff fr.Element, config ecc.MultiExpConfig) (*G2Affine, error) { + var _p G2Jac + if _, err := _p.Fold(points, combinationCoeff, config); err != nil { + return nil, err + } + p.FromJacobian(&_p) + return p, nil +} + +// Fold computes the multi-exponentiation \sum_{i=0}^{len(points)-1} points[i] * +// combinationCoeff^i and stores the result in p. It returns error in case +// configuration is invalid. +func (p *G2Jac) Fold(points []G2Affine, combinationCoeff fr.Element, config ecc.MultiExpConfig) (*G2Jac, error) { + scalars := make([]fr.Element, len(points)) + scalar := fr.NewElement(1) + for i := 0; i < len(points); i++ { + scalars[i].Set(&scalar) + scalar.Mul(&scalar, &combinationCoeff) + } + return p.MultiExp(points, scalars, config) +} + // selector stores the index, mask and shifts needed to select bits from a scalar // it is used during the multiExp algorithm or the batch scalar multiplication type selector struct { diff --git a/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/multiexp_affine.go b/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/multiexp_affine.go index 937a43c9d1..1b71b7ab45 100644 --- a/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/multiexp_affine.go +++ b/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/multiexp_affine.go @@ -60,10 +60,9 @@ func processChunkG1BatchAffine[BJE ibg1JacExtended, B ibG1Affine, BS bitSet, TP // note that we have 2 sets of buckets // 1 in G1Affine used with the batch affine additions // 1 in g1JacExtended used in case the queue of conflicting points - var buckets B + var buckets B // in G1Affine coordinates, infinity point is represented as (0,0), no need to init var bucketsJE BJE for i := 0; i < len(buckets); i++ { - buckets[i].setInfinity() bucketsJE[i].setInfinity() } @@ -226,7 +225,7 @@ func processChunkG1BatchAffine[BJE ibg1JacExtended, B ibG1Affine, BS bitSet, TP total.setInfinity() for k := len(buckets) - 1; k >= 0; k-- { runningSum.addMixed(&buckets[k]) - if !bucketsJE[k].IsZero() { + if !bucketsJE[k].IsInfinity() { runningSum.add(&bucketsJE[k]) } total.add(&runningSum) @@ -388,10 +387,9 @@ func processChunkG2BatchAffine[BJE ibg2JacExtended, B ibG2Affine, BS bitSet, TP // note that we have 2 sets of buckets // 1 in G2Affine used with the batch affine additions // 1 in g2JacExtended used in case the queue of conflicting points - var buckets B + var buckets B // in G2Affine coordinates, infinity point is represented as (0,0), no need to init var bucketsJE BJE for i := 0; i < len(buckets); i++ { - buckets[i].setInfinity() bucketsJE[i].setInfinity() } @@ -554,7 +552,7 @@ func processChunkG2BatchAffine[BJE ibg2JacExtended, B ibG2Affine, BS bitSet, TP total.setInfinity() for k := len(buckets) - 1; k >= 0; k-- { runningSum.addMixed(&buckets[k]) - if !bucketsJE[k].IsZero() { + if !bucketsJE[k].IsInfinity() { runningSum.add(&bucketsJE[k]) } total.add(&runningSum) diff --git a/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/multiexp_jacobian.go b/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/multiexp_jacobian.go index 1b8c0e79aa..80b042d8d3 100644 --- a/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/multiexp_jacobian.go +++ b/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/multiexp_jacobian.go @@ -56,7 +56,7 @@ func processChunkG1Jacobian[B ibg1JacExtended](chunk uint64, runningSum.setInfinity() total.setInfinity() for k := len(buckets) - 1; k >= 0; k-- { - if !buckets[k].IsZero() { + if !buckets[k].IsInfinity() { runningSum.add(&buckets[k]) } total.add(&runningSum) @@ -145,7 +145,7 @@ func processChunkG2Jacobian[B ibg2JacExtended](chunk uint64, runningSum.setInfinity() total.setInfinity() for k := len(buckets) - 1; k >= 0; k-- { - if !buckets[k].IsZero() { + if !buckets[k].IsInfinity() { runningSum.add(&buckets[k]) } total.add(&runningSum) diff --git a/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/pairing.go b/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/pairing.go index b7c1bf66b2..be2e8bc74e 100644 --- a/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/pairing.go +++ b/vendor/github.com/consensys/gnark-crypto/ecc/bls12-381/pairing.go @@ -386,14 +386,15 @@ func PairingCheckFixedQ(P []G1Affine, lines [][2][len(LoopCounter) - 1]LineEvalu func PrecomputeLines(Q G2Affine) (PrecomputedLines [2][len(LoopCounter) - 1]LineEvaluationAff) { var accQ G2Affine accQ.Set(&Q) - n := len(LoopCounter) - for i := n - 2; i >= 0; i-- { - accQ.doubleStep(&PrecomputedLines[0][i]) + // i = n - 2 + accQ.doubleStep(&PrecomputedLines[0][n-2]) + accQ.addStep(&PrecomputedLines[1][n-2], &Q) + for i := n - 3; i >= 0; i-- { if LoopCounter[i] == 0 { - continue + accQ.doubleStep(&PrecomputedLines[0][i]) } else { - accQ.addStep(&PrecomputedLines[1][i], &Q) + accQ.doubleAndAddStep(&PrecomputedLines[0][i], &PrecomputedLines[1][i], &Q) } } return PrecomputedLines @@ -541,3 +542,49 @@ func (p *G2Affine) addStep(evaluations *LineEvaluationAff, a *G2Affine) { p.X.Set(&xr) p.Y.Set(&yr) } + +func (p *G2Affine) doubleAndAddStep(evaluations1, evaluations2 *LineEvaluationAff, a *G2Affine) { + var n, d, l1, x3, l2, x4, y4 fptower.E2 + + // compute λ1 = (y2-y1)/(x2-x1) + n.Sub(&p.Y, &a.Y) + d.Sub(&p.X, &a.X) + l1.Div(&n, &d) + + // compute x3 =λ1²-x1-x2 + x3.Square(&l1) + x3.Sub(&x3, &p.X) + x3.Sub(&x3, &a.X) + + // omit y3 computation + + // compute line1 + evaluations1.R0.Set(&l1) + evaluations1.R1.Mul(&l1, &p.X) + evaluations1.R1.Sub(&evaluations1.R1, &p.Y) + + // compute λ2 = -λ1-2y1/(x3-x1) + n.Double(&p.Y) + d.Sub(&x3, &p.X) + l2.Div(&n, &d) + l2.Add(&l2, &l1) + l2.Neg(&l2) + + // compute x4 = λ2²-x1-x3 + x4.Square(&l2) + x4.Sub(&x4, &p.X) + x4.Sub(&x4, &x3) + + // compute y4 = λ2(x1 - x4)-y1 + y4.Sub(&p.X, &x4) + y4.Mul(&l2, &y4) + y4.Sub(&y4, &p.Y) + + // compute line2 + evaluations2.R0.Set(&l2) + evaluations2.R1.Mul(&l2, &p.X) + evaluations2.R1.Sub(&evaluations2.R1, &p.Y) + + p.X.Set(&x4) + p.Y.Set(&y4) +} diff --git a/vendor/github.com/ethereum/go-ethereum/.gitignore b/vendor/github.com/ethereum/go-ethereum/.gitignore index ac0f4efdfb..7000fedd25 100644 --- a/vendor/github.com/ethereum/go-ethereum/.gitignore +++ b/vendor/github.com/ethereum/go-ethereum/.gitignore @@ -37,6 +37,7 @@ profile.cov # IdeaIDE .idea +*.iml # VS Code .vscode diff --git a/vendor/github.com/ethereum/go-ethereum/.golangci.yml b/vendor/github.com/ethereum/go-ethereum/.golangci.yml index e355e6f9d1..a702da524b 100644 --- a/vendor/github.com/ethereum/go-ethereum/.golangci.yml +++ b/vendor/github.com/ethereum/go-ethereum/.golangci.yml @@ -3,9 +3,6 @@ run: timeout: 20m tests: true - # default is true. Enables skipping of directories: - # vendor$, third_party$, testdata$, examples$, Godeps$, builtin$ - skip-dirs-use-default: true linters: disable-all: true @@ -28,7 +25,7 @@ linters: - gocheckcompilerdirectives - reassign - mirror - - tenv + - usetesting ### linters we tried and will not be using: ### # - structcheck # lots of false positives @@ -54,6 +51,9 @@ linters-settings: exclude: [""] issues: + # default is true. Enables skipping of directories: + # vendor$, third_party$, testdata$, examples$, Godeps$, builtin$ + exclude-dirs-use-default: true exclude-files: - core/genesis_alloc.go exclude-rules: diff --git a/vendor/github.com/ethereum/go-ethereum/.mailmap b/vendor/github.com/ethereum/go-ethereum/.mailmap index 312e51d854..92a9e07748 100644 --- a/vendor/github.com/ethereum/go-ethereum/.mailmap +++ b/vendor/github.com/ethereum/go-ethereum/.mailmap @@ -5,6 +5,9 @@ Aaron Kumavis Abel Nieto Abel Nieto +Adrian Sutton +Adrian Sutton + Afri Schoedon <58883403+q9f@users.noreply.github.com> Afri Schoedon <5chdn@users.noreply.github.com> <58883403+q9f@users.noreply.github.com> @@ -22,6 +25,9 @@ Alexey Akhunov Alon Muroch +Andrei Silviu Dragnea +Andrei Silviu Dragnea + Andrey Petrov Andrey Petrov @@ -51,11 +57,17 @@ Chris Ziogas Christoph Jentzsch +Daniel Liu +Daniel Liu <139250065@qq.com> + Diederik Loerakker Dimitry Khokhlov +Ha ĐANG + Domino Valdano +Domino Valdano Edgar Aroutiounian @@ -82,6 +94,9 @@ Gavin Wood Gregg Dourgarian +guangwu +guangwu + Guillaume Ballet Guillaume Ballet <3272758+gballet@users.noreply.github.com> @@ -95,13 +110,21 @@ Heiko Hees Henning Diedrich Henning Diedrich Drake Burroughs +henridf +henridf + Hwanjo Heo <34005989+hwanjo@users.noreply.github.com> +Ikko Eltociear Ashimine + Iskander (Alex) Sharipov Iskander (Alex) Sharipov Jae Kwon +James Prestwich +James Prestwich <10149425+prestwich@users.noreply.github.com> + Janoš Guljaš Janoš Guljaš Janos Guljas @@ -120,23 +143,38 @@ Jeffrey Wilcke Jens Agerberg +Jeremy Schlatter +Jeremy Schlatter + +John Chase <68833933+joohhnnn@users.noreply.github.com> + Joseph Chow Joseph Chow ethers - Joseph Goulden Justin Drake +Karl Bartel +Karl Bartel + Kenso Trabing Kenso Trabing +Liyi Guo <102356659+colinlyguo@users.noreply.github.com> + +lmittmann <3458786+lmittmann@users.noreply.github.com> +lmittmann <3458786+lmittmann@users.noreply.github.com> + Liang Ma Liang Ma Louis Holbrook Louis Holbrook +makcandrov +makcandrov <108467407+makcandrov@users.noreply.github.com> + Maran Hidskes Marian Oancea @@ -144,17 +182,33 @@ Marian Oancea Martin Becze Martin Becze +Martin Holst Swende + Martin Lundfall -Matt Garnett <14004106+lightclient@users.noreply.github.com> +Marius van der Wijden +Marius van der Wijden <115323661+vdwijden@users.noreply.github.com> + +Matt Garnett +Matt Garnett <14004106+lightclient@users.noreply.github.com> Matthew Halpern Matthew Halpern +meowsbits +meowsbits <45600330+meowsbits@users.noreply.github.com> + Michael Riabzev +Michael de Hoog +Michael de Hoog + Nchinda Nchinda +Nebojsa Urosevic + +nedifi <103940716+nedifi@users.noreply.github.com> + Nick Dodson Nick Johnson @@ -169,6 +223,9 @@ Olivier Hervieu Pascal Dierich Pascal Dierich +Paweł Bylica +Paweł Bylica + RJ Catalano RJ Catalano @@ -179,8 +236,22 @@ Rene Lubov <41963722+renaynay@users.noreply.github.com> Robert Zaremba Robert Zaremba +Roberto Bayardo +Roberto Bayardo + Roman Mandeleil +Sebastian Stammler +Sebastian Stammler + +Seungbae Yu +Seungbae Yu <72970043+dbadoy@users.noreply.github.com> + +Sina Mahmoodi <1591639+s1na@users.noreply.github.com> + +Steve Milk +Steve Milk <915337710@qq.com> + Sorin Neacsu Sorin Neacsu @@ -191,8 +262,14 @@ Taylor Gerring Thomas Bocek +tianyeyouyou +tianyeyouyou <150894831+tianyeyouyou@users.noreply.github.com> + Tim Cooijmans +ucwong +ucwong + Valentin Wüstholz Valentin Wüstholz @@ -221,6 +298,9 @@ Xudong Liu <33193253+r1cs@users.noreply.github.com> Yohann Léon +yzb <335357057@qq.com> +yzb <335357057@qq.com> + Zachinquarantine Zachinquarantine @@ -228,9 +308,4 @@ Ziyuan Zhong Zsolt Felföldi -meowsbits -meowsbits <45600330+meowsbits@users.noreply.github.com> - -nedifi <103940716+nedifi@users.noreply.github.com> - Максим Чусовлянов diff --git a/vendor/github.com/ethereum/go-ethereum/.travis.yml b/vendor/github.com/ethereum/go-ethereum/.travis.yml index 2ba3af9419..5e8a493d03 100644 --- a/vendor/github.com/ethereum/go-ethereum/.travis.yml +++ b/vendor/github.com/ethereum/go-ethereum/.travis.yml @@ -15,7 +15,7 @@ jobs: os: linux arch: amd64 dist: focal - go: 1.23.x + go: 1.24.x env: - docker services: @@ -25,7 +25,7 @@ jobs: before_install: - export DOCKER_CLI_EXPERIMENTAL=enabled script: - - go run build/ci.go dockerx -platform "linux/amd64,linux/arm64,linux/riscv64" -upload ethereum/client-go + - go run build/ci.go dockerx -platform "linux/amd64,linux/arm64,linux/riscv64" -hub ethereum/client-go -upload # This builder does the Linux Azure uploads - stage: build @@ -33,7 +33,7 @@ jobs: os: linux dist: focal sudo: required - go: 1.23.x + go: 1.24.x env: - azure-linux git: @@ -85,7 +85,7 @@ jobs: os: linux arch: amd64 dist: focal - go: 1.23.x + go: 1.24.x script: - travis_wait 45 go run build/ci.go test $TEST_PACKAGES @@ -93,7 +93,7 @@ jobs: if: type = push os: linux dist: focal - go: 1.22.x + go: 1.23.x script: - travis_wait 45 go run build/ci.go test $TEST_PACKAGES @@ -102,7 +102,7 @@ jobs: if: type = cron || (type = push && tag ~= /^v[0-9]/) os: linux dist: focal - go: 1.23.x + go: 1.24.x env: - ubuntu-ppa git: @@ -118,7 +118,7 @@ jobs: if: type = cron os: linux dist: focal - go: 1.23.x + go: 1.24.x env: - azure-purge git: @@ -131,7 +131,7 @@ jobs: if: type = cron os: linux dist: focal - go: 1.23.x + go: 1.24.x env: - racetests script: diff --git a/vendor/github.com/ethereum/go-ethereum/AUTHORS b/vendor/github.com/ethereum/go-ethereum/AUTHORS index 151c85016e..1ec240aeb6 100644 --- a/vendor/github.com/ethereum/go-ethereum/AUTHORS +++ b/vendor/github.com/ethereum/go-ethereum/AUTHORS @@ -1,52 +1,81 @@ # This is the official list of go-ethereum authors for copyright purposes. +0xbeny <55846654+0xbeny@users.noreply.github.com> +0xbstn +0xe3b0c4 <110295932+0xe3b0c4@users.noreply.github.com> 6543 <6543@obermui.de> +6xiaowu9 <736518585@qq.com> a e r t h Aaron Buchwald +Aaron Chen +Aaron Kumavis +Aayush Rajasekaran Abel Nieto +Abirdcfly Adam Babik Adam Schmideg Aditya Aditya Arora +Adrian Sutton Adrià Cidre Afanasii Kurakin Afri Schoedon <5chdn@users.noreply.github.com> Agustin Armellini Fischer +Ahmet Avci Ahyun Airead Alan Chen Alejandro Isaza Aleksey Smyrnov Ales Katona +alex <152680487+bodhi-crypo@users.noreply.github.com> Alex Beregszaszi +Alex Gartner Alex Leverington Alex Mazalov +Alex Mylonas Alex Pozhilenkov Alex Prut <1648497+alexprut@users.noreply.github.com> +Alex Stokes Alex Wu +Alexander Mint Alexander van der Meij Alexander Yastrebov Alexandre Van de Sande Alexey Akhunov Alexey Shekhirin alexwang <39109351+dipingxian2@users.noreply.github.com> +Alfie John Ali Atiia <42751398+aliatiia@users.noreply.github.com> Ali Hajimirza +Alvaro Sevilla am2rican5 +Amin Talebi +AMIR <31338382+amiremohamadi@users.noreply.github.com> AmitBRD <60668103+AmitBRD@users.noreply.github.com> Anatole <62328077+a2br@users.noreply.github.com> +Andre Patta Andrea Franz +Andrei Kostakov Andrei Maiboroda +Andrei Silviu Dragnea +Andrew Ashikhmin <34320705+yperbasis@users.noreply.github.com> Andrey Petrov +Andryanau Kanstantsin ANOTHEL Antoine Rondelet Antoine Toulme Anton Evangelatov Antonio Salazar Cardozo +Antony Denyer +Anusha <63559942+anusha-ctrl@users.noreply.github.com> Arba Sasmoyo Armani Ferrante Armin Braun Aron Fischer +Arran Schlosberg <519948+ARR4N@users.noreply.github.com> +ArtificialPB +Artyom Aminov atsushi-ishibashi Austin Roberts ayeowch @@ -54,83 +83,135 @@ b00ris b1ackd0t bailantaotao baizhenxuan +Bala Murali Krishna Komatireddy Balaji Shetty Pachai <32358081+balajipachai@users.noreply.github.com> Balint Gabor baptiste-b-pegasys <85155432+baptiste-b-pegasys@users.noreply.github.com> Bas van Kervel Benjamin Brent +Benjamin Prosnitz benma Benoit Verkindt +Bin <49082129+songzhibin97@users.noreply.github.com> Binacs +bitcoin-lightning <153181187+AtomicInnovation321@users.noreply.github.com> +bk <5810624+bkellerman@users.noreply.github.com> bloonfield +bnovil Bo Bo Ye Bob Glickstein Boqin Qin +BorkBorked <107079055+BorkBorked@users.noreply.github.com> Brandon Harden +Brandon Liu Brent Brian Schroeder +Brion <4777457+cifer76@users.noreply.github.com> Bruno Škvorc +buddho +bugmaker9371 <167614621+bugmaker9371@users.noreply.github.com> C. Brown Caesar Chad +cam-schultz <78878559+cam-schultz@users.noreply.github.com> Casey Detrio +caseylove CDsigma +Cedrick Ceelog Ceyhun Onur chabashilah changhong +Charles Cooper Chase Wright +Chawin Aiemvaravutigul Chen Quan +chen4903 <108803001+chen4903@users.noreply.github.com> Cheng Li chenglin <910372762@qq.com> chenyufeng +Chirag Garg <38765776+DeVil2O@users.noreply.github.com> +chirag-bgh <76247491+chirag-bgh@users.noreply.github.com> Chris Pacia Chris Ziogas Christian Muehlhaeuser +Christina <156356273+cratiu222@users.noreply.github.com> Christoph Jentzsch +Christopher Harrison <31964100+chrischarlesharrison@users.noreply.github.com> chuwt +cocoyeal <150209682+cocoyeal@users.noreply.github.com> cong Connor Stein Corey Lin <514971757@qq.com> courtier cpusoft +crazeteam <164632007+crazeteam@users.noreply.github.com> Crispin Flowerday croath cui <523516579@qq.com> +cui fliter +cuinix <65650185+cuinix@users.noreply.github.com> +Curith +cygaar <97691933+cygaar@users.noreply.github.com> +Dan Cline <6798349+Rjected@users.noreply.github.com> Dan DeGreef Dan Kinsley +Dan Laine Dan Sosedoff +danceratopz Daniel A. Nagy +Daniel Fernandes <711733+daferna@users.noreply.github.com> +Daniel Katzan <108216499+dkatzan@users.noreply.github.com> +Daniel Knopik <107140945+dknopik@users.noreply.github.com> +Daniel Liu Daniel Perez Daniel Sloof +Danno Ferrin +Danyal Prout Darioush Jalali Darrel Herbst +Darren Kelly <107671032+darrenvechain@users.noreply.github.com> +dashangcun <907225865@qq.com> Dave Appleton Dave McGregor David Cai +David Dzhalaev <72649244+DavidRomanovizc@users.noreply.github.com> David Huie +David Murdoch <187813+davidmurdoch@users.noreply.github.com> +David Theodore <29786815+infosecual@users.noreply.github.com> +ddl +Dean Eigenmann <7621705+decanus@users.noreply.github.com> +Delweng Denver Derek Chiang Derek Gottfrid +deterclosed <164524498+deterclosed@users.noreply.github.com> +Devon Bear Di Peng Diederik Loerakker Diego Siqueira Diep Pham +Dimitris Apostolou dipingxian2 <39109351+dipingxian2@users.noreply.github.com> divergencetech <94644849+divergencetech@users.noreply.github.com> +dknopik <107140945+dknopik@users.noreply.github.com> dm4 Dmitrij Koniajev Dmitry Shulyak Dmitry Zenovich Domino Valdano +DongXi Huang <418498589@qq.com> Dragan Milic dragonvslinux <35779158+dragononcrypto@users.noreply.github.com> +Dylan Vassallo +easyfold <137396765+easyfold@users.noreply.github.com> Edgar Aroutiounian Eduard S Egon Elbre Elad Eli Elias Naur +Elias Rad <146735585+nnsW3@users.noreply.github.com> Elliot Shepherd Emil emile @@ -151,11 +232,13 @@ Evgeny Evgeny Danilenko <6655321@bk.ru> evgk Evolution404 <35091674+Evolution404@users.noreply.github.com> +Exca-DK <85954505+Exca-DK@users.noreply.github.com> EXEC Fabian Vogelsteller Fabio Barone Fabio Berger FaceHo +felipe Felipe Strozberg <48066928+FelStroz@users.noreply.github.com> Felix Lange Ferenc Szabo @@ -163,68 +246,102 @@ ferhat elmas Ferran Borreguero Fiisio Fire Man <55934298+basdevelop@users.noreply.github.com> +FletcherMan flowerofdream <775654398@qq.com> fomotrader <82184770+fomotrader@users.noreply.github.com> +Ford <153042616+guerrierindien@users.noreply.github.com> ForLina <471133417@qq.com> Frank Szendzielarz <33515470+FrankSzendzielarz@users.noreply.github.com> Frank Wang Franklin +Freeman Jiang Furkan KAMACI Fuyang Deng GagziW Gary Rong Gautam Botrel +Gealber Morales <48373523+Gealber@users.noreply.github.com> +George Ma <164313692+availhang@users.noreply.github.com> George Ornbo +georgehao +gitglorythegreat Giuseppe Bertone Greg Colvin Gregg Dourgarian Gregory Markou <16929357+GregTheGreek@users.noreply.github.com> +guangwu +Guido Vranken Guifel Guilherme Salgado Guillaume Ballet +Guillaume Michel Guillaume Nicolas GuiltyMorishita Guruprasad Kamath <48196632+gurukamath@users.noreply.github.com> Gus Gustav Simonsson +Gustavo Silva Gísli Kristjánsson Ha ĐANG HackyMiner -hadv +Halimao <1065621723@qq.com> Hanjiang Yu Hao Bryan Cheng Hao Duan +haoran <159284258+hr98w@users.noreply.github.com> +Haotian <51777534+tmelhao@users.noreply.github.com> HAOYUatHZ <37070449+HAOYUatHZ@users.noreply.github.com> Harry Dutton +Harry Kalodner haryu703 <34744512+haryu703@users.noreply.github.com> +hattizai Hendrik Hofstadt Henning Diedrich henopied <13500516+henopied@users.noreply.github.com> +henridf +Henry <101552941+henry-0@users.noreply.github.com> hero5512 holisticode Hongbin Mao Hsien-Tang Kao hsyodyssey <47173566+hsyodyssey@users.noreply.github.com> +Hteev Oli Husam Ibrahim <39692071+HusamIbrahim@users.noreply.github.com> Hwanjo Heo <34005989+hwanjo@users.noreply.github.com> hydai +hyhnet +hyunchel <3271191+hyunchel@users.noreply.github.com> Hyung-Kyu Hqueue Choi +Hyunsoo Shin (Lake) +hzysvilla Håvard Anda Estensen Ian Macalinao Ian Norden +Icarus Wu icodezjb -Ikko Ashimine +ids +Ignacio Hagopian +Ikko Eltociear Ashimine Ilan Gitter <8359193+gitteri@users.noreply.github.com> +imalasong <55082705+imalasong@users.noreply.github.com> ImanSharaf <78227895+ImanSharaf@users.noreply.github.com> +imulmat4 <117636097+imulmat4@users.noreply.github.com> +Inphi +int88 <106391185+int88@users.noreply.github.com> Isidoro Ghezzi Iskander (Alex) Sharipov +Ivan Aracki Ivan Bogatyy Ivan Daniluk Ivo Georgiev +j2gg0s jacksoom +jackyin <648588267@qq.com> Jae Kwon -James Prestwich <10149425+prestwich@users.noreply.github.com> +Jakub Freebit <49676311+jakub-freebit@users.noreply.github.com> +James Prestwich Jamie Pitts +Janko Simonovic Janoš Guljaš Jared Wasinger Jason Carver @@ -239,42 +356,63 @@ Jeff Wentworth Jeffery Robert Walsh Jeffrey Wilcke Jens Agerberg +Jens W <8270201+DragonDev1906@users.noreply.github.com> Jeremy McNevin Jeremy Schlatter Jerzy Lasyk Jesse Tane Jia Chenhui Jim McDonald +jin <35813306+lochjin@users.noreply.github.com> jk-jeongkyun <45347815+jeongkyun-oh@users.noreply.github.com> jkcomment +Joe Netti JoeGruffins <34998433+JoeGruffins@users.noreply.github.com> Joel Burget John C. Vernaleo +John Chase <68833933+joohhnnn@users.noreply.github.com> John Difool +John Hilliard +John Xu Johns Beharry +Jolly Zhao Jonas Jonathan Brown Jonathan Chappelow Jonathan Gimeno +Jonathan Otto JoranHonig Jordan Krage +Jorge Jorropo Joseph Chow +Joseph Cook <33655003+jmcook1186@users.noreply.github.com> Joshua Colvin Joshua Gutow jovijovi +jp-imx <109574657+jp-imx@users.noreply.github.com> jtakalai JU HYEONG PARK Julian Y Justin Clark-Casey +Justin Dhillon Justin Drake +Justin Traglia <95511699+jtraglia@users.noreply.github.com> Justus +KAI <35927054+ThreeAndTwo@users.noreply.github.com> +kaliubuntu0206 <139627505+kaliubuntu0206@users.noreply.github.com> +Karl Bartel +Karol Chojnowski Kawashima <91420903+sscodereth@users.noreply.github.com> +kazak ken10100147 Kenji Siu Kenso Trabing +Kero +kevaundray Kevin kevin.xu +Kiarash Hajian <133909368+kiarash8112@users.noreply.github.com> KibGzr kiel barry kilic @@ -282,8 +420,10 @@ kimmylin <30611210+kimmylin@users.noreply.github.com> Kitten King <53072918+kittenking@users.noreply.github.com> knarfeh Kobi Gurkan +Koichi Shiraishi komika Konrad Feldmeier +Kosuke Taniguchi <73885532+TaniguchiKosuke@users.noreply.github.com> Kris Shinn Kristofer Peterson Kumar Anirudha @@ -296,6 +436,8 @@ Lefteris Karapetsas Leif Jurvetson Leo Shklovskii LeoLiao +Leon <316032931@qq.com> +levisyin <150114626+levisyin@users.noreply.github.com> Lewis Marshall lhendre Li Dongwei @@ -305,36 +447,58 @@ libby kent libotony LieutenantRoger ligi +lilasxie +Lindlof Lio李欧 -lmittmann +Liyi Guo <102356659+colinlyguo@users.noreply.github.com> +llkhacquan <3724362+llkhacquan@users.noreply.github.com> +lmittmann <3458786+lmittmann@users.noreply.github.com> +lorenzo <31852651+lorenzo-dev1@users.noreply.github.com> Lorenzo Manacorda Louis Holbrook Luca Zeug +Lucas Lucas Hendren +Luozhu <70309026+LuozhuZhang@users.noreply.github.com> +lwh lzhfromustc <43191155+lzhfromustc@users.noreply.github.com> +Maciej Kulawik <10907694+magicxyyz@users.noreply.github.com> +Madhur Shrimal Magicking +makcandrov manlio +Manoj Kumar Maran Hidskes +Marcin Sobczak <77129288+marcindsobczak@users.noreply.github.com> +Marcus Baldassarre Marek Kotewicz Mariano Cortesi +Mario Vega +Marius G <90795310+bearpebble@users.noreply.github.com> +Marius Kjærstad Marius van der Wijden Mark Mark Rushakoff +Mark Tyneway mark.lin +markus <55011443+mdymalla@users.noreply.github.com> +Marquis Shanahan <29431502+9547@users.noreply.github.com> Martin Alex Philip Dawson Martin Holst Swende Martin Klepsch Martin Lundfall Martin Michlmayr Martin Redmond <21436+reds@users.noreply.github.com> +maskpp Mason Fischer Mateusz Morusiewicz <11313015+Ruteri@users.noreply.github.com> Mats Julian Olsen -Matt Garnett <14004106+lightclient@users.noreply.github.com> +Matt Garnett Matt K <1036969+mkrump@users.noreply.github.com> Matthew Di Ferrante Matthew Halpern Matthew Wampler-Doty +Matthieu Vachon Max Sistemich Maxim Zhiburt Maximilian Meister @@ -342,34 +506,55 @@ me020523 Melvin Junhee Woo meowsbits Micah Zoltu +Michael de Hoog Michael Forney Michael Riabzev Michael Ruminer michael1011 Miguel Mota Mike Burr +Mikel Cortes <45786396+cortze@users.noreply.github.com> Mikhail Mikheev +Mikhail Vazhnov +miles <66052478+miles-six@users.noreply.github.com> +Miles Chen milesvant +minh-bq <97180373+minh-bq@users.noreply.github.com> +Mio Miro Miya Chen +mmsqe +Mobin Mohanan <47410557+tr1sm0s1n@users.noreply.github.com> Mohanson +moomin <67548026+nothingmin@users.noreply.github.com> mr_franklin +Mskxn <118117161+Mskxn@users.noreply.github.com> Mudit Gupta Mymskmkt <1847234666@qq.com> Nalin Bhardwaj +nand2 +Nathan +Nathan Jo <162083209+qqqeck@users.noreply.github.com> Natsu Kagami +Naveen <116692862+naveen-imtb@users.noreply.github.com> Nchinda Nchinda -nebojsa94 +Nebojsa Urosevic necaremus nedifi <103940716+nedifi@users.noreply.github.com> needkane <604476380@qq.com> +Newt6611 <45097780+Newt6611@users.noreply.github.com> +Ng Wei Han <47109095+weiihann@users.noreply.github.com> Nguyen Kien Trung Nguyen Sy Thanh Son Nic Jansma +Nicholas Nick Dodson Nick Johnson +Nicola Cocchiaro <3538109+ncocchiaro@users.noreply.github.com> Nicolas Feignon +Nicolas Gotchac Nicolas Guillaume +Nikhil Suri Nikita Kozhemyakin Nikola Madjarevic Nilesh Trivedi @@ -379,32 +564,47 @@ njupt-moon <1015041018@njupt.edu.cn> nkbai noam-alchemy <76969113+noam-alchemy@users.noreply.github.com> nobody +noel <72006780+0x00Duke@users.noreply.github.com> Noman +norwnd <112318969+norwnd@users.noreply.github.com> nujabes403 Nye Liu +Obtuse7772 <117080049+Obtuse7772@users.noreply.github.com> Oleg Kovalov Oli Bye Oliver Tale-Yazdi Olivier Hervieu +openex Or Neeman +oseau Osoro Bironga Osuke +panicalways <113693386+panicalways@users.noreply.github.com> Pantelis Peslis +Parithosh Jayanthi +Park Changwan Pascal Dierich Patrick O'Grady Pau +Paul <41552663+molecula451@users.noreply.github.com> Paul Berg +Paul Lange Paul Litvak Paul-Armand Verhaegen Paulo L F Casaretto +Pawan Dhananjay Paweł Bylica Pedro Gomes Pedro Pombeiro +persmor <166146971+persmor@users.noreply.github.com> +Peter (bitfly) <1674920+peterbitfly@users.noreply.github.com> Peter Broadhurst peter cresswell Peter Pratscher Peter Simard +Peter Straus <153843855+krauspt@users.noreply.github.com> Petr Mikusek +phenix3443 Philip Schlump Pierre Neter Pierre R @@ -412,15 +612,24 @@ piersy PilkyuJung Piotr Dyraga ploui <64719999+ploui@users.noreply.github.com> +PolyMa <151764357+polymaer@users.noreply.github.com> Preston Van Loon Prince Sinha +psogv0308 +puhtaytow <18026645+puhtaytow@users.noreply.github.com> Péter Szilágyi +qcrao qd-ethan <31876119+qdgogogo@users.noreply.github.com> Qian Bin +qiuhaohao +Qt +Quentin McGaw Quest Henkart +Rachel Bousfield Rachel Franks Rafael Matias Raghav Sood +Rajaram Gaunker Ralph Caraveo Ramesh Nair rangzen @@ -430,45 +639,65 @@ rhaps107 Ricardo Catalinas Jiménez Ricardo Domingos Richard Hart +RichΛrd Rick RJ Catalano Rob Rob Mulholand Robert Zaremba +Roberto Bayardo Roc Yu +Roman Krasiuk Roman Mazalov <83914728+gopherxyz@users.noreply.github.com> Ross <9055337+Chadsr@users.noreply.github.com> +Rossen Krastev +Roy Crihfield Runchao Han +Ruohui Wang Russ Cox Ryan Schneider +Ryan Tinianov ryanc414 Rémy Roy S. Matthew English salanfe Sam <39165351+Xia-Sam@users.noreply.github.com> +Saman H. Pasha <51169592+saman-pasha@users.noreply.github.com> Sammy Libre <7374093+sammy007@users.noreply.github.com> Samuel Marks +Sanghee Choi <32831939+pengin7384@users.noreply.github.com> +SangIlMo <156392700+SangIlMo@users.noreply.github.com> sanskarkhare +SanYe Sarlor Sasuke1964 Satpal <28562234+SatpalSandhu61@users.noreply.github.com> Saulius Grigaitis Sean +seayyyy <163325936+seay404@users.noreply.github.com> +Sebastian Stammler Serhat Şevki Dinçer +Seungbae Yu +Seungmin Kim Shane Bammel shawn <36943337+lxex@users.noreply.github.com> shigeyuki azuchi Shihao Xia Shiming +Shiming Zhang Shintaro Kaneko shiqinfeng1 <150627601@qq.com> +Shivam Sandbhor +shivhg Shuai Qi Shude Li Shunsuke Watanabe +shuo silence Simon Jentzsch Sina Mahmoodi <1591639+s1na@users.noreply.github.com> sixdays +sjlee1125 <47561537+sjlee1125@users.noreply.github.com> SjonHortensius Slava Karpenko slumber1122 @@ -477,17 +706,29 @@ soc1c Sorin Neacsu Sparty Stein Dekker +Stephen Flynn +Stephen Guo Steve Gattuso +Steve Milk Steve Ruckdashel Steve Waldman Steven E. Harris Steven Roose stompesi stormpang +storyicon +strykerin +sudeep +SuiYuan <165623542+suiyuan1314@users.noreply.github.com> +Sungwoo Kim sunxiaojun2014 Suriyaa Sundararuban Sylvain Laurent +Szupingwang +tactical_retreat +Taeguk Kwon Taeik Lim +taiking tamirms Tangui Clairet Tatsuya Shimoda @@ -495,21 +736,35 @@ Taylor Gerring TColl <38299499+TColl@users.noreply.github.com> terasum tgyKomgo <52910426+tgyKomgo@users.noreply.github.com> +Thabokani <149070269+Thabokani@users.noreply.github.com> Thad Guidry +therainisme Thomas Bocek thomasmodeneis thumb8432 Ti Zhou tia-99 <67107070+tia-99@users.noreply.github.com> +tianyeyouyou +Tien Nguyen <116023870+htiennv@users.noreply.github.com> Tim Cooijmans +TinyFoxy Tobias Hildebrandt <79341166+tobias-hildebrandt@users.noreply.github.com> +tokikuch +Tom <45168162+tomdever@users.noreply.github.com> Tosh Camille +trillo +Tristan-Wilson <87238672+Tristan-Wilson@users.noreply.github.com> +trocher tsarpaul +TY <45994721+tylerK1294@users.noreply.github.com> Tyler Chambers <2775339+tylerchambers@users.noreply.github.com> +tylerni7 tzapu -ucwong +ucwong uji <49834542+uji@users.noreply.github.com> ult-bobonovski +Undefinedor +Ursulafe <152976968+Ursulafe@users.noreply.github.com> Valentin Trinqué Valentin Wüstholz Vedhavyas Singareddi @@ -528,39 +783,60 @@ Vitaly V Vivek Anand Vlad Bokov Vlad Gluhovsky +VM <112189277+sysvm@users.noreply.github.com> +vuittont60 <81072379+vuittont60@users.noreply.github.com> +wangjingcun +wangyifan Ward Bradt Water <44689567+codeoneline@users.noreply.github.com> wbt +Wei Tang weimumu <934657014@qq.com> Wenbiao Zheng Wenshao Zhong +Wihan de Beer Will Villanueva William Morriss William Setzer williambannas +willian.eth +winniehere +winterjihwan <113398351+winterjihwan@users.noreply.github.com> wuff1996 <33193253+wuff1996@users.noreply.github.com> Wuxiang Xiaobing Jiang +xiaodong <81516175+javaandfly@users.noreply.github.com> xiekeyang +xinbenlv xincaosu xinluyin <31590468+xinluyin@users.noreply.github.com> +xiyang <90125263+JBossBC@users.noreply.github.com> Xudong Liu <33193253+r1cs@users.noreply.github.com> xwjack yahtoo Yang Hau YaoZengzeng +ycyraum YH-Zhou +Yier <90763233+yierx@users.noreply.github.com> Yihau Chen +yihuang Yohann Léon Yoichi Hirai Yole <007yuyue@gmail.com> Yondon Fu +yong <33920876+yzhaoyu@users.noreply.github.com> YOSHIDA Masanori yoza +ysh0566 +yudrywet <166895665+yudrywet@users.noreply.github.com> +yujinpark +yukionfire yumiel yoomee1313 Yusup yutianwu ywzqwwt <39263032+ywzqwwt@users.noreply.github.com> +yzb <335357057@qq.com> zaccoding Zach Zachinquarantine @@ -568,24 +844,34 @@ zah Zahoor Mohamed Zak Cole zcheng9 +zeim839 <50573884+zeim839@users.noreply.github.com> zer0to0ne <36526113+zer0to0ne@users.noreply.github.com> zgfzgf <48779939+zgfzgf@users.noreply.github.com> Zhang Zhuo zhangsoledad <787953403@qq.com> zhaochonghe <41711151+zhaochonghe@users.noreply.github.com> +zhen peng <505380967@qq.com> Zhenguo Niu +Zheyuan He +Zhihao Lin <3955922+kkqy@users.noreply.github.com> zhiqiangxu <652732310@qq.com> Zhou Zhiyao Ziyuan Zhong Zoe Nolan +zoereco <158379334+zoereco@users.noreply.github.com> +Zoo +Zoro <40222601+BabyHalimao@users.noreply.github.com> Zou Guangxian Zsolt Felföldi Łukasz Kurowski Łukasz Zimnoch ΞTHΞЯSPHΞЯΞ <{viktor.tron,nagydani,zsfelfoldi}@gmail.com> Максим Чусовлянов +かげ <47621124+ronething-bot@users.noreply.github.com> +スパイク <1311798+spkjp@users.noreply.github.com> 大彬 沉风 +牛晓婕 <30611384+niuxiaojie81@users.noreply.github.com> 贺鹏飞 陈佳 유용환 <33824408+eric-yoo@users.noreply.github.com> diff --git a/vendor/github.com/ethereum/go-ethereum/Dockerfile b/vendor/github.com/ethereum/go-ethereum/Dockerfile index ff89e92f25..9b70e9e8a0 100644 --- a/vendor/github.com/ethereum/go-ethereum/Dockerfile +++ b/vendor/github.com/ethereum/go-ethereum/Dockerfile @@ -4,7 +4,7 @@ ARG VERSION="" ARG BUILDNUM="" # Build Geth in a stock Go builder container -FROM golang:1.23-alpine AS builder +FROM golang:1.24-alpine AS builder RUN apk add --no-cache gcc musl-dev linux-headers git diff --git a/vendor/github.com/ethereum/go-ethereum/Dockerfile.alltools b/vendor/github.com/ethereum/go-ethereum/Dockerfile.alltools index 44d5065af0..ac9303c678 100644 --- a/vendor/github.com/ethereum/go-ethereum/Dockerfile.alltools +++ b/vendor/github.com/ethereum/go-ethereum/Dockerfile.alltools @@ -4,7 +4,7 @@ ARG VERSION="" ARG BUILDNUM="" # Build Geth in a stock Go builder container -FROM golang:1.23-alpine AS builder +FROM golang:1.24-alpine AS builder RUN apk add --no-cache gcc musl-dev linux-headers git diff --git a/vendor/github.com/ethereum/go-ethereum/README.md b/vendor/github.com/ethereum/go-ethereum/README.md index 182464c639..9ccfe933aa 100644 --- a/vendor/github.com/ethereum/go-ethereum/README.md +++ b/vendor/github.com/ethereum/go-ethereum/README.md @@ -16,7 +16,7 @@ archives are published at https://geth.ethereum.org/downloads/. For prerequisites and detailed build instructions please read the [Installation Instructions](https://geth.ethereum.org/docs/getting-started/installing-geth). -Building `geth` requires both a Go (version 1.22 or later) and a C compiler. You can install +Building `geth` requires both a Go (version 1.23 or later) and a C compiler. You can install them using your favourite package manager. Once the dependencies are installed, run ```shell @@ -40,7 +40,6 @@ directory. | `clef` | Stand-alone signing tool, which can be used as a backend signer for `geth`. | | `devp2p` | Utilities to interact with nodes on the networking layer, without running a full blockchain. | | `abigen` | Source code generator to convert Ethereum contract definitions into easy-to-use, compile-time type-safe Go packages. It operates on plain [Ethereum contract ABIs](https://docs.soliditylang.org/en/develop/abi-spec.html) with expanded functionality if the contract bytecode is also available. However, it also accepts Solidity source files, making development much more streamlined. Please see our [Native DApps](https://geth.ethereum.org/docs/developers/dapp-developer/native-bindings) page for details. | -| `bootnode` | Stripped down version of our Ethereum client implementation that only takes part in the network node discovery protocol, but does not run any of the higher level application protocols. It can be used as a lightweight bootstrap node to aid in finding peers in private networks. | | `evm` | Developer utility version of the EVM (Ethereum Virtual Machine) that is capable of running bytecode snippets within a configurable environment and execution mode. Its purpose is to allow isolated, fine-grained debugging of EVM opcodes (e.g. `evm --code 60ff60ff --debug run`). | | `rlpdump` | Developer utility tool to convert binary RLP ([Recursive Length Prefix](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp)) dumps (data encoding used by the Ethereum protocol both network as well as consensus wise) to user-friendlier hierarchical representation (e.g. `rlpdump --hex CE0183FFFFFFC4C304050583616263`). | @@ -55,14 +54,14 @@ on how you can run your own `geth` instance. Minimum: -* CPU with 2+ cores -* 4GB RAM +* CPU with 4+ cores +* 8GB RAM * 1TB free storage space to sync the Mainnet * 8 MBit/sec download Internet service Recommended: -* Fast CPU with 4+ cores +* Fast CPU with 8+ cores * 16GB+ RAM * High-performance SSD with at least 1TB of free space * 25+ MBit/sec download Internet service @@ -139,8 +138,6 @@ export your existing configuration: $ geth --your-favourite-flags dumpconfig ``` -*Note: This works only with `geth` v1.6.0 and above.* - #### Docker quick start One of the quickest ways to get Ethereum up and running on your machine is by using @@ -181,14 +178,13 @@ HTTP based JSON-RPC API options: * `--http.addr` HTTP-RPC server listening interface (default: `localhost`) * `--http.port` HTTP-RPC server listening port (default: `8545`) * `--http.api` API's offered over the HTTP-RPC interface (default: `eth,net,web3`) - * `--http.corsdomain` Comma separated list of domains from which to accept cross origin requests (browser enforced) + * `--http.corsdomain` Comma separated list of domains from which to accept cross-origin requests (browser enforced) * `--ws` Enable the WS-RPC server * `--ws.addr` WS-RPC server listening interface (default: `localhost`) * `--ws.port` WS-RPC server listening port (default: `8546`) * `--ws.api` API's offered over the WS-RPC interface (default: `eth,net,web3`) * `--ws.origins` Origins from which to accept WebSocket requests * `--ipcdisable` Disable the IPC-RPC server - * `--ipcapi` API's offered over the IPC-RPC interface (default: `admin,debug,eth,miner,net,personal,txpool,web3`) * `--ipcpath` Filename for IPC socket/pipe within the datadir (explicit paths escape it) You'll need to use your own programming environments' capabilities (libraries, tools, etc) to @@ -207,113 +203,14 @@ APIs!** Maintaining your own private network is more involved as a lot of configurations taken for granted in the official networks need to be manually set up. -#### Defining the private genesis state - -First, you'll need to create the genesis state of your networks, which all nodes need to be -aware of and agree upon. This consists of a small JSON file (e.g. call it `genesis.json`): - -```json -{ - "config": { - "chainId": , - "homesteadBlock": 0, - "eip150Block": 0, - "eip155Block": 0, - "eip158Block": 0, - "byzantiumBlock": 0, - "constantinopleBlock": 0, - "petersburgBlock": 0, - "istanbulBlock": 0, - "berlinBlock": 0, - "londonBlock": 0 - }, - "alloc": {}, - "coinbase": "0x0000000000000000000000000000000000000000", - "difficulty": "0x20000", - "extraData": "", - "gasLimit": "0x2fefd8", - "nonce": "0x0000000000000042", - "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000", - "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000", - "timestamp": "0x00" -} -``` - -The above fields should be fine for most purposes, although we'd recommend changing -the `nonce` to some random value so you prevent unknown remote nodes from being able -to connect to you. If you'd like to pre-fund some accounts for easier testing, create -the accounts and populate the `alloc` field with their addresses. - -```json -"alloc": { - "0x0000000000000000000000000000000000000001": { - "balance": "111111111" - }, - "0x0000000000000000000000000000000000000002": { - "balance": "222222222" - } -} -``` - -With the genesis state defined in the above JSON file, you'll need to initialize **every** -`geth` node with it prior to starting it up to ensure all blockchain parameters are correctly -set: - -```shell -$ geth init path/to/genesis.json -``` - -#### Creating the rendezvous point - -With all nodes that you want to run initialized to the desired genesis state, you'll need to -start a bootstrap node that others can use to find each other in your network and/or over -the internet. The clean way is to configure and run a dedicated bootnode: - -```shell -$ bootnode --genkey=boot.key -$ bootnode --nodekey=boot.key -``` - -With the bootnode online, it will display an [`enode` URL](https://ethereum.org/en/developers/docs/networking-layer/network-addresses/#enode) -that other nodes can use to connect to it and exchange peer information. Make sure to -replace the displayed IP address information (most probably `[::]`) with your externally -accessible IP to get the actual `enode` URL. - -*Note: You could also use a full-fledged `geth` node as a bootnode, but it's the less -recommended way.* - -#### Starting up your member nodes - -With the bootnode operational and externally reachable (you can try -`telnet ` to ensure it's indeed reachable), start every subsequent `geth` -node pointed to the bootnode for peer discovery via the `--bootnodes` flag. It will -probably also be desirable to keep the data directory of your private network separated, so -do also specify a custom `--datadir` flag. - -```shell -$ geth --datadir=path/to/custom/data/folder --bootnodes= -``` +Unfortunately since [the Merge](https://ethereum.org/en/roadmap/merge/) it is no longer possible +to easily set up a network of geth nodes without also setting up a corresponding beacon chain. -*Note: Since your network will be completely cut off from the main and test networks, you'll -also need to configure a miner to process transactions and create new blocks for you.* - -#### Running a private miner - - -In a private network setting a single CPU miner instance is more than enough for -practical purposes as it can produce a stable stream of blocks at the correct intervals -without needing heavy resources (consider running on a single thread, no need for multiple -ones either). To start a `geth` instance for mining, run it with all your usual flags, extended -by: - -```shell -$ geth --mine --miner.threads=1 --miner.etherbase=0x0000000000000000000000000000000000000000 -``` +There are three different solutions depending on your use case: -Which will start mining blocks and transactions on a single CPU thread, crediting all -proceedings to the account specified by `--miner.etherbase`. You can further tune the mining -by changing the default gas limit blocks converge to (`--miner.targetgaslimit`) and the price -transactions are accepted at (`--miner.gasprice`). + * If you are looking for a simple way to test smart contracts from go in your CI, you can use the [Simulated Backend](https://geth.ethereum.org/docs/developers/dapp-developer/native-bindings#blockchain-simulator). + * If you want a convenient single node environment for testing, you can use our [Dev Mode](https://geth.ethereum.org/docs/developers/dapp-developer/dev-mode). + * If you are looking for a multiple node test network, you can set one up quite easily with [Kurtosis](https://geth.ethereum.org/docs/fundamentals/kurtosis). ## Contribution diff --git a/vendor/github.com/ethereum/go-ethereum/accounts/abi/abi.go b/vendor/github.com/ethereum/go-ethereum/accounts/abi/abi.go index c7bc2b4541..f75278c8b1 100644 --- a/vendor/github.com/ethereum/go-ethereum/accounts/abi/abi.go +++ b/vendor/github.com/ethereum/go-ethereum/accounts/abi/abi.go @@ -84,7 +84,7 @@ func (abi ABI) Pack(name string, args ...interface{}) ([]byte, error) { func (abi ABI) getArguments(name string, data []byte) (Arguments, error) { // since there can't be naming collisions with contracts and events, - // we need to decide whether we're calling a method or an event + // we need to decide whether we're calling a method, event or an error var args Arguments if method, ok := abi.Methods[name]; ok { if len(data)%32 != 0 { @@ -95,8 +95,11 @@ func (abi ABI) getArguments(name string, data []byte) (Arguments, error) { if event, ok := abi.Events[name]; ok { args = event.Inputs } + if err, ok := abi.Errors[name]; ok { + args = err.Inputs + } if args == nil { - return nil, fmt.Errorf("abi: could not locate named method or event: %s", name) + return nil, fmt.Errorf("abi: could not locate named method, event or error: %s", name) } return args, nil } diff --git a/vendor/github.com/ethereum/go-ethereum/accounts/abi/bind/util.go b/vendor/github.com/ethereum/go-ethereum/accounts/abi/bind/util.go index b931fbb04d..c83116e9a1 100644 --- a/vendor/github.com/ethereum/go-ethereum/accounts/abi/bind/util.go +++ b/vendor/github.com/ethereum/go-ethereum/accounts/abi/bind/util.go @@ -30,12 +30,18 @@ import ( // WaitMined waits for tx to be mined on the blockchain. // It stops waiting when the context is canceled. func WaitMined(ctx context.Context, b DeployBackend, tx *types.Transaction) (*types.Receipt, error) { + return WaitMinedHash(ctx, b, tx.Hash()) +} + +// WaitMinedHash waits for a transaction with the provided hash to be mined on the blockchain. +// It stops waiting when the context is canceled. +func WaitMinedHash(ctx context.Context, b DeployBackend, hash common.Hash) (*types.Receipt, error) { queryTicker := time.NewTicker(time.Second) defer queryTicker.Stop() - logger := log.New("hash", tx.Hash()) + logger := log.New("hash", hash) for { - receipt, err := b.TransactionReceipt(ctx, tx.Hash()) + receipt, err := b.TransactionReceipt(ctx, hash) if err == nil { return receipt, nil } @@ -61,7 +67,13 @@ func WaitDeployed(ctx context.Context, b DeployBackend, tx *types.Transaction) ( if tx.To() != nil { return common.Address{}, errors.New("tx is not contract creation") } - receipt, err := WaitMined(ctx, b, tx) + return WaitDeployedHash(ctx, b, tx.Hash()) +} + +// WaitDeployedHash waits for a contract deployment transaction with the provided hash and returns the on-chain +// contract address when it is mined. It stops waiting when ctx is canceled. +func WaitDeployedHash(ctx context.Context, b DeployBackend, hash common.Hash) (common.Address, error) { + receipt, err := WaitMinedHash(ctx, b, hash) if err != nil { return common.Address{}, err } diff --git a/vendor/github.com/ethereum/go-ethereum/accounts/abi/topics.go b/vendor/github.com/ethereum/go-ethereum/accounts/abi/topics.go index 7ce9b7273c..4819334ae6 100644 --- a/vendor/github.com/ethereum/go-ethereum/accounts/abi/topics.go +++ b/vendor/github.com/ethereum/go-ethereum/accounts/abi/topics.go @@ -42,7 +42,7 @@ func MakeTopics(query ...[]interface{}) ([][]common.Hash, error) { case common.Address: copy(topic[common.HashLength-common.AddressLength:], rule[:]) case *big.Int: - copy(topic[:], math.U256Bytes(rule)) + copy(topic[:], math.U256Bytes(new(big.Int).Set(rule))) case bool: if rule { topic[common.HashLength-1] = 1 diff --git a/vendor/github.com/ethereum/go-ethereum/accounts/accounts.go b/vendor/github.com/ethereum/go-ethereum/accounts/accounts.go index b995498a6d..7bd911577a 100644 --- a/vendor/github.com/ethereum/go-ethereum/accounts/accounts.go +++ b/vendor/github.com/ethereum/go-ethereum/accounts/accounts.go @@ -214,7 +214,9 @@ const ( // of starting any background processes such as automatic key derivation. WalletOpened - // WalletDropped + // WalletDropped is fired when a wallet is removed or disconnected, either via USB + // or due to a filesystem event in the keystore. This event indicates that the wallet + // is no longer available for operations. WalletDropped ) diff --git a/vendor/github.com/ethereum/go-ethereum/accounts/external/backend.go b/vendor/github.com/ethereum/go-ethereum/accounts/external/backend.go index 62322753da..42eaf661cc 100644 --- a/vendor/github.com/ethereum/go-ethereum/accounts/external/backend.go +++ b/vendor/github.com/ethereum/go-ethereum/accounts/external/backend.go @@ -215,7 +215,7 @@ func (api *ExternalSigner) SignTx(account accounts.Account, tx *types.Transactio switch tx.Type() { case types.LegacyTxType, types.AccessListTxType: args.GasPrice = (*hexutil.Big)(tx.GasPrice()) - case types.DynamicFeeTxType, types.BlobTxType: + case types.DynamicFeeTxType, types.BlobTxType, types.SetCodeTxType: args.MaxFeePerGas = (*hexutil.Big)(tx.GasFeeCap()) args.MaxPriorityFeePerGas = (*hexutil.Big)(tx.GasTipCap()) default: diff --git a/vendor/github.com/ethereum/go-ethereum/appveyor.yml b/vendor/github.com/ethereum/go-ethereum/appveyor.yml index 1543211edc..ae1c74c18e 100644 --- a/vendor/github.com/ethereum/go-ethereum/appveyor.yml +++ b/vendor/github.com/ethereum/go-ethereum/appveyor.yml @@ -24,7 +24,6 @@ for: - image: Ubuntu build_script: - go run build/ci.go lint - - go run build/ci.go check_tidy - go run build/ci.go check_generate - go run build/ci.go check_baddeps - go run build/ci.go install -dlgo diff --git a/vendor/github.com/ethereum/go-ethereum/core/types/block.go b/vendor/github.com/ethereum/go-ethereum/core/types/block.go index f20fc7d778..b284fb3b16 100644 --- a/vendor/github.com/ethereum/go-ethereum/core/types/block.go +++ b/vendor/github.com/ethereum/go-ethereum/core/types/block.go @@ -105,7 +105,7 @@ type Header struct { ParentBeaconRoot *common.Hash `json:"parentBeaconBlockRoot" rlp:"optional"` // RequestsHash was added by EIP-7685 and is ignored in legacy headers. - RequestsHash *common.Hash `json:"requestsRoot" rlp:"optional"` + RequestsHash *common.Hash `json:"requestsHash" rlp:"optional"` } // field type overrides for gencodec @@ -237,6 +237,9 @@ type extblock struct { // // The body elements and the receipts are used to recompute and overwrite the // relevant portions of the header. +// +// The receipt's bloom must already calculated for the block's bloom to be +// correctly calculated. func NewBlock(header *Header, body *Body, receipts []*Receipt, hasher TrieHasher) *Block { if body == nil { body = &Body{} @@ -260,7 +263,10 @@ func NewBlock(header *Header, body *Body, receipts []*Receipt, hasher TrieHasher b.header.ReceiptHash = EmptyReceiptsHash } else { b.header.ReceiptHash = DeriveSha(Receipts(receipts), hasher) - b.header.Bloom = CreateBloom(receipts) + // Receipts must go through MakeReceipt to calculate the receipt's bloom + // already. Merge the receipt's bloom together instead of recalculating + // everything. + b.header.Bloom = MergeBloom(receipts) } if len(uncles) == 0 { @@ -463,9 +469,11 @@ func CalcRequestsHash(requests [][]byte) common.Hash { h1, h2 := sha256.New(), sha256.New() var buf common.Hash for _, item := range requests { - h1.Reset() - h1.Write(item) - h2.Write(h1.Sum(buf[:0])) + if len(item) > 1 { // skip items with only requestType and no data. + h1.Reset() + h1.Write(item) + h2.Write(h1.Sum(buf[:0])) + } } h2.Sum(buf[:0]) return buf diff --git a/vendor/github.com/ethereum/go-ethereum/core/types/bloom9.go b/vendor/github.com/ethereum/go-ethereum/core/types/bloom9.go index a560a20724..962ba46d47 100644 --- a/vendor/github.com/ethereum/go-ethereum/core/types/bloom9.go +++ b/vendor/github.com/ethereum/go-ethereum/core/types/bloom9.go @@ -100,32 +100,35 @@ func (b *Bloom) UnmarshalText(input []byte) error { return hexutil.UnmarshalFixedText("Bloom", input, b[:]) } -// CreateBloom creates a bloom filter out of the give Receipts (+Logs) -func CreateBloom(receipts Receipts) Bloom { - buf := make([]byte, 6) - var bin Bloom - for _, receipt := range receipts { - for _, log := range receipt.Logs { - bin.add(log.Address.Bytes(), buf) - for _, b := range log.Topics { - bin.add(b[:], buf) - } +// CreateBloom creates a bloom filter out of the give Receipt (+Logs) +func CreateBloom(receipt *Receipt) Bloom { + var ( + bin Bloom + buf = make([]byte, 6) + ) + for _, log := range receipt.Logs { + bin.add(log.Address.Bytes(), buf) + for _, b := range log.Topics { + bin.add(b[:], buf) } } return bin } -// LogsBloom returns the bloom bytes for the given logs -func LogsBloom(logs []*Log) []byte { - buf := make([]byte, 6) +// MergeBloom merges the precomputed bloom filters in the Receipts without +// recalculating them. It assumes that each receipt’s Bloom field is already +// correctly populated. +func MergeBloom(receipts Receipts) Bloom { var bin Bloom - for _, log := range logs { - bin.add(log.Address.Bytes(), buf) - for _, b := range log.Topics { - bin.add(b[:], buf) + for _, receipt := range receipts { + if len(receipt.Logs) != 0 { + bl := receipt.Bloom.Bytes() + for i := range bin { + bin[i] |= bl[i] + } } } - return bin[:] + return bin } // Bloom9 returns the bloom filter for the given data diff --git a/vendor/github.com/ethereum/go-ethereum/core/types/deposit.go b/vendor/github.com/ethereum/go-ethereum/core/types/deposit.go index 3bba2c7aa4..8015f29ca7 100644 --- a/vendor/github.com/ethereum/go-ethereum/core/types/deposit.go +++ b/vendor/github.com/ethereum/go-ethereum/core/types/deposit.go @@ -24,7 +24,7 @@ const ( depositRequestSize = 192 ) -// UnpackIntoDeposit unpacks a serialized DepositEvent. +// DepositLogToRequest unpacks a serialized DepositEvent. func DepositLogToRequest(data []byte) ([]byte, error) { if len(data) != 576 { return nil, fmt.Errorf("deposit wrong length: want 576, have %d", len(data)) diff --git a/vendor/github.com/ethereum/go-ethereum/core/types/gen_authorization.go b/vendor/github.com/ethereum/go-ethereum/core/types/gen_authorization.go new file mode 100644 index 0000000000..57069cbb1f --- /dev/null +++ b/vendor/github.com/ethereum/go-ethereum/core/types/gen_authorization.go @@ -0,0 +1,75 @@ +// Code generated by github.com/fjl/gencodec. DO NOT EDIT. + +package types + +import ( + "encoding/json" + "errors" + + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/holiman/uint256" +) + +var _ = (*authorizationMarshaling)(nil) + +// MarshalJSON marshals as JSON. +func (s SetCodeAuthorization) MarshalJSON() ([]byte, error) { + type SetCodeAuthorization struct { + ChainID hexutil.U256 `json:"chainId" gencodec:"required"` + Address common.Address `json:"address" gencodec:"required"` + Nonce hexutil.Uint64 `json:"nonce" gencodec:"required"` + V hexutil.Uint64 `json:"yParity" gencodec:"required"` + R hexutil.U256 `json:"r" gencodec:"required"` + S hexutil.U256 `json:"s" gencodec:"required"` + } + var enc SetCodeAuthorization + enc.ChainID = hexutil.U256(s.ChainID) + enc.Address = s.Address + enc.Nonce = hexutil.Uint64(s.Nonce) + enc.V = hexutil.Uint64(s.V) + enc.R = hexutil.U256(s.R) + enc.S = hexutil.U256(s.S) + return json.Marshal(&enc) +} + +// UnmarshalJSON unmarshals from JSON. +func (s *SetCodeAuthorization) UnmarshalJSON(input []byte) error { + type SetCodeAuthorization struct { + ChainID *hexutil.U256 `json:"chainId" gencodec:"required"` + Address *common.Address `json:"address" gencodec:"required"` + Nonce *hexutil.Uint64 `json:"nonce" gencodec:"required"` + V *hexutil.Uint64 `json:"yParity" gencodec:"required"` + R *hexutil.U256 `json:"r" gencodec:"required"` + S *hexutil.U256 `json:"s" gencodec:"required"` + } + var dec SetCodeAuthorization + if err := json.Unmarshal(input, &dec); err != nil { + return err + } + if dec.ChainID == nil { + return errors.New("missing required field 'chainId' for SetCodeAuthorization") + } + s.ChainID = uint256.Int(*dec.ChainID) + if dec.Address == nil { + return errors.New("missing required field 'address' for SetCodeAuthorization") + } + s.Address = *dec.Address + if dec.Nonce == nil { + return errors.New("missing required field 'nonce' for SetCodeAuthorization") + } + s.Nonce = uint64(*dec.Nonce) + if dec.V == nil { + return errors.New("missing required field 'yParity' for SetCodeAuthorization") + } + s.V = uint8(*dec.V) + if dec.R == nil { + return errors.New("missing required field 'r' for SetCodeAuthorization") + } + s.R = uint256.Int(*dec.R) + if dec.S == nil { + return errors.New("missing required field 's' for SetCodeAuthorization") + } + s.S = uint256.Int(*dec.S) + return nil +} diff --git a/vendor/github.com/ethereum/go-ethereum/core/types/gen_header_json.go b/vendor/github.com/ethereum/go-ethereum/core/types/gen_header_json.go index 322c5d5642..0af12500bd 100644 --- a/vendor/github.com/ethereum/go-ethereum/core/types/gen_header_json.go +++ b/vendor/github.com/ethereum/go-ethereum/core/types/gen_header_json.go @@ -36,7 +36,7 @@ func (h Header) MarshalJSON() ([]byte, error) { BlobGasUsed *hexutil.Uint64 `json:"blobGasUsed" rlp:"optional"` ExcessBlobGas *hexutil.Uint64 `json:"excessBlobGas" rlp:"optional"` ParentBeaconRoot *common.Hash `json:"parentBeaconBlockRoot" rlp:"optional"` - RequestsHash *common.Hash `json:"requestsRoot" rlp:"optional"` + RequestsHash *common.Hash `json:"requestsHash" rlp:"optional"` Hash common.Hash `json:"hash"` } var enc Header @@ -88,7 +88,7 @@ func (h *Header) UnmarshalJSON(input []byte) error { BlobGasUsed *hexutil.Uint64 `json:"blobGasUsed" rlp:"optional"` ExcessBlobGas *hexutil.Uint64 `json:"excessBlobGas" rlp:"optional"` ParentBeaconRoot *common.Hash `json:"parentBeaconBlockRoot" rlp:"optional"` - RequestsHash *common.Hash `json:"requestsRoot" rlp:"optional"` + RequestsHash *common.Hash `json:"requestsHash" rlp:"optional"` } var dec Header if err := json.Unmarshal(input, &dec); err != nil { diff --git a/vendor/github.com/ethereum/go-ethereum/core/types/hashes.go b/vendor/github.com/ethereum/go-ethereum/core/types/hashes.go index 43e9130fd1..05cfaeed74 100644 --- a/vendor/github.com/ethereum/go-ethereum/core/types/hashes.go +++ b/vendor/github.com/ethereum/go-ethereum/core/types/hashes.go @@ -19,7 +19,6 @@ package types import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/log" ) var ( @@ -41,16 +40,9 @@ var ( // EmptyWithdrawalsHash is the known hash of the empty withdrawal set. EmptyWithdrawalsHash = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421") + // EmptyRequestsHash is the known hash of an empty request set, sha256(""). + EmptyRequestsHash = common.HexToHash("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855") + // EmptyVerkleHash is the known hash of an empty verkle trie. EmptyVerkleHash = common.Hash{} ) - -// TrieRootHash returns the hash itself if it's non-empty or the predefined -// emptyHash one instead. -func TrieRootHash(hash common.Hash) common.Hash { - if hash == (common.Hash{}) { - log.Error("Zero trie root hash!") - return EmptyRootHash - } - return hash -} diff --git a/vendor/github.com/ethereum/go-ethereum/core/types/receipt.go b/vendor/github.com/ethereum/go-ethereum/core/types/receipt.go index 4f96fde59c..e52a0c6477 100644 --- a/vendor/github.com/ethereum/go-ethereum/core/types/receipt.go +++ b/vendor/github.com/ethereum/go-ethereum/core/types/receipt.go @@ -204,7 +204,7 @@ func (r *Receipt) decodeTyped(b []byte) error { return errShortTypedReceipt } switch b[0] { - case DynamicFeeTxType, AccessListTxType, BlobTxType: + case DynamicFeeTxType, AccessListTxType, BlobTxType, SetCodeTxType: var data receiptRLP err := rlp.DecodeBytes(b[1:], &data) if err != nil { @@ -291,7 +291,7 @@ func (r *ReceiptForStorage) DecodeRLP(s *rlp.Stream) error { } r.CumulativeGasUsed = stored.CumulativeGasUsed r.Logs = stored.Logs - r.Bloom = CreateBloom(Receipts{(*Receipt)(r)}) + r.Bloom = CreateBloom((*Receipt)(r)) return nil } @@ -312,7 +312,7 @@ func (rs Receipts) EncodeIndex(i int, w *bytes.Buffer) { } w.WriteByte(r.Type) switch r.Type { - case AccessListTxType, DynamicFeeTxType, BlobTxType: + case AccessListTxType, DynamicFeeTxType, BlobTxType, SetCodeTxType: rlp.Encode(w, data) default: // For unsupported types, write nothing. Since this is for diff --git a/vendor/github.com/ethereum/go-ethereum/core/types/transaction.go b/vendor/github.com/ethereum/go-ethereum/core/types/transaction.go index ea6f5ad6b9..4e48248b4a 100644 --- a/vendor/github.com/ethereum/go-ethereum/core/types/transaction.go +++ b/vendor/github.com/ethereum/go-ethereum/core/types/transaction.go @@ -48,6 +48,7 @@ const ( AccessListTxType = 0x01 DynamicFeeTxType = 0x02 BlobTxType = 0x03 + SetCodeTxType = 0x04 ) // Transaction is an Ethereum transaction. @@ -205,6 +206,8 @@ func (tx *Transaction) decodeTyped(b []byte) (TxData, error) { inner = new(DynamicFeeTx) case BlobTxType: inner = new(BlobTx) + case SetCodeTxType: + inner = new(SetCodeTx) default: return nil, ErrTxTypeNotSupported } @@ -471,6 +474,38 @@ func (tx *Transaction) WithBlobTxSidecar(sideCar *BlobTxSidecar) *Transaction { return cpy } +// SetCodeAuthorizations returns the authorizations list of the transaction. +func (tx *Transaction) SetCodeAuthorizations() []SetCodeAuthorization { + setcodetx, ok := tx.inner.(*SetCodeTx) + if !ok { + return nil + } + return setcodetx.AuthList +} + +// SetCodeAuthorities returns a list of unique authorities from the +// authorization list. +func (tx *Transaction) SetCodeAuthorities() []common.Address { + setcodetx, ok := tx.inner.(*SetCodeTx) + if !ok { + return nil + } + var ( + marks = make(map[common.Address]bool) + auths = make([]common.Address, 0, len(setcodetx.AuthList)) + ) + for _, auth := range setcodetx.AuthList { + if addr, err := auth.Authority(); err == nil { + if marks[addr] { + continue + } + marks[addr] = true + auths = append(auths, addr) + } + } + return auths +} + // SetTime sets the decoding time of a transaction. This is used by tests to set // arbitrary times and by persistent transaction pools when loading old txs from // disk. diff --git a/vendor/github.com/ethereum/go-ethereum/core/types/transaction_marshalling.go b/vendor/github.com/ethereum/go-ethereum/core/types/transaction_marshalling.go index 4d5b2bcdd4..f76d4b92e9 100644 --- a/vendor/github.com/ethereum/go-ethereum/core/types/transaction_marshalling.go +++ b/vendor/github.com/ethereum/go-ethereum/core/types/transaction_marshalling.go @@ -31,22 +31,23 @@ import ( type txJSON struct { Type hexutil.Uint64 `json:"type"` - ChainID *hexutil.Big `json:"chainId,omitempty"` - Nonce *hexutil.Uint64 `json:"nonce"` - To *common.Address `json:"to"` - Gas *hexutil.Uint64 `json:"gas"` - GasPrice *hexutil.Big `json:"gasPrice"` - MaxPriorityFeePerGas *hexutil.Big `json:"maxPriorityFeePerGas"` - MaxFeePerGas *hexutil.Big `json:"maxFeePerGas"` - MaxFeePerBlobGas *hexutil.Big `json:"maxFeePerBlobGas,omitempty"` - Value *hexutil.Big `json:"value"` - Input *hexutil.Bytes `json:"input"` - AccessList *AccessList `json:"accessList,omitempty"` - BlobVersionedHashes []common.Hash `json:"blobVersionedHashes,omitempty"` - V *hexutil.Big `json:"v"` - R *hexutil.Big `json:"r"` - S *hexutil.Big `json:"s"` - YParity *hexutil.Uint64 `json:"yParity,omitempty"` + ChainID *hexutil.Big `json:"chainId,omitempty"` + Nonce *hexutil.Uint64 `json:"nonce"` + To *common.Address `json:"to"` + Gas *hexutil.Uint64 `json:"gas"` + GasPrice *hexutil.Big `json:"gasPrice"` + MaxPriorityFeePerGas *hexutil.Big `json:"maxPriorityFeePerGas"` + MaxFeePerGas *hexutil.Big `json:"maxFeePerGas"` + MaxFeePerBlobGas *hexutil.Big `json:"maxFeePerBlobGas,omitempty"` + Value *hexutil.Big `json:"value"` + Input *hexutil.Bytes `json:"input"` + AccessList *AccessList `json:"accessList,omitempty"` + BlobVersionedHashes []common.Hash `json:"blobVersionedHashes,omitempty"` + AuthorizationList []SetCodeAuthorization `json:"authorizationList,omitempty"` + V *hexutil.Big `json:"v"` + R *hexutil.Big `json:"r"` + S *hexutil.Big `json:"s"` + YParity *hexutil.Uint64 `json:"yParity,omitempty"` // Blob transaction sidecar encoding: Blobs []kzg4844.Blob `json:"blobs,omitempty"` @@ -153,6 +154,22 @@ func (tx *Transaction) MarshalJSON() ([]byte, error) { enc.Commitments = itx.Sidecar.Commitments enc.Proofs = itx.Sidecar.Proofs } + case *SetCodeTx: + enc.ChainID = (*hexutil.Big)(itx.ChainID.ToBig()) + enc.Nonce = (*hexutil.Uint64)(&itx.Nonce) + enc.To = tx.To() + enc.Gas = (*hexutil.Uint64)(&itx.Gas) + enc.MaxFeePerGas = (*hexutil.Big)(itx.GasFeeCap.ToBig()) + enc.MaxPriorityFeePerGas = (*hexutil.Big)(itx.GasTipCap.ToBig()) + enc.Value = (*hexutil.Big)(itx.Value.ToBig()) + enc.Input = (*hexutil.Bytes)(&itx.Data) + enc.AccessList = &itx.AccessList + enc.AuthorizationList = itx.AuthList + enc.V = (*hexutil.Big)(itx.V.ToBig()) + enc.R = (*hexutil.Big)(itx.R.ToBig()) + enc.S = (*hexutil.Big)(itx.S.ToBig()) + yparity := itx.V.Uint64() + enc.YParity = (*hexutil.Uint64)(&yparity) } return json.Marshal(&enc) } @@ -336,7 +353,11 @@ func (tx *Transaction) UnmarshalJSON(input []byte) error { if dec.ChainID == nil { return errors.New("missing required field 'chainId' in transaction") } - itx.ChainID = uint256.MustFromBig((*big.Int)(dec.ChainID)) + var overflow bool + itx.ChainID, overflow = uint256.FromBig(dec.ChainID.ToInt()) + if overflow { + return errors.New("'chainId' value overflows uint256") + } if dec.Nonce == nil { return errors.New("missing required field 'nonce' in transaction") } @@ -378,7 +399,84 @@ func (tx *Transaction) UnmarshalJSON(input []byte) error { itx.BlobHashes = dec.BlobVersionedHashes // signature R + if dec.R == nil { + return errors.New("missing required field 'r' in transaction") + } + itx.R, overflow = uint256.FromBig((*big.Int)(dec.R)) + if overflow { + return errors.New("'r' value overflows uint256") + } + // signature S + if dec.S == nil { + return errors.New("missing required field 's' in transaction") + } + itx.S, overflow = uint256.FromBig((*big.Int)(dec.S)) + if overflow { + return errors.New("'s' value overflows uint256") + } + // signature V + vbig, err := dec.yParityValue() + if err != nil { + return err + } + itx.V, overflow = uint256.FromBig(vbig) + if overflow { + return errors.New("'v' value overflows uint256") + } + if itx.V.Sign() != 0 || itx.R.Sign() != 0 || itx.S.Sign() != 0 { + if err := sanityCheckSignature(vbig, itx.R.ToBig(), itx.S.ToBig(), false); err != nil { + return err + } + } + + case SetCodeTxType: + var itx SetCodeTx + inner = &itx + if dec.ChainID == nil { + return errors.New("missing required field 'chainId' in transaction") + } var overflow bool + itx.ChainID, overflow = uint256.FromBig(dec.ChainID.ToInt()) + if overflow { + return errors.New("'chainId' value overflows uint256") + } + if dec.Nonce == nil { + return errors.New("missing required field 'nonce' in transaction") + } + itx.Nonce = uint64(*dec.Nonce) + if dec.To == nil { + return errors.New("missing required field 'to' in transaction") + } + itx.To = *dec.To + if dec.Gas == nil { + return errors.New("missing required field 'gas' for txdata") + } + itx.Gas = uint64(*dec.Gas) + if dec.MaxPriorityFeePerGas == nil { + return errors.New("missing required field 'maxPriorityFeePerGas' for txdata") + } + itx.GasTipCap = uint256.MustFromBig((*big.Int)(dec.MaxPriorityFeePerGas)) + if dec.MaxFeePerGas == nil { + return errors.New("missing required field 'maxFeePerGas' for txdata") + } + itx.GasFeeCap = uint256.MustFromBig((*big.Int)(dec.MaxFeePerGas)) + if dec.Value == nil { + return errors.New("missing required field 'value' in transaction") + } + itx.Value = uint256.MustFromBig((*big.Int)(dec.Value)) + if dec.Input == nil { + return errors.New("missing required field 'input' in transaction") + } + itx.Data = *dec.Input + if dec.AccessList != nil { + itx.AccessList = *dec.AccessList + } + if dec.AuthorizationList == nil { + return errors.New("missing required field 'authorizationList' in transaction") + } + itx.AuthList = dec.AuthorizationList + + // signature R if dec.R == nil { return errors.New("missing required field 'r' in transaction") } @@ -416,6 +514,5 @@ func (tx *Transaction) UnmarshalJSON(input []byte) error { // Now set the inner transaction. tx.setDecoded(inner, 0) - // TODO: check hash here? return nil } diff --git a/vendor/github.com/ethereum/go-ethereum/core/types/transaction_signing.go b/vendor/github.com/ethereum/go-ethereum/core/types/transaction_signing.go index 73011e238b..030fc472a0 100644 --- a/vendor/github.com/ethereum/go-ethereum/core/types/transaction_signing.go +++ b/vendor/github.com/ethereum/go-ethereum/core/types/transaction_signing.go @@ -40,6 +40,8 @@ type sigCache struct { func MakeSigner(config *params.ChainConfig, blockNumber *big.Int, blockTime uint64) Signer { var signer Signer switch { + case config.IsPrague(blockNumber, blockTime): + signer = NewPragueSigner(config.ChainID) case config.IsCancun(blockNumber, blockTime): signer = NewCancunSigner(config.ChainID) case config.IsLondon(blockNumber): @@ -67,6 +69,8 @@ func LatestSigner(config *params.ChainConfig) Signer { var signer Signer if config.ChainID != nil { switch { + case config.PragueTime != nil: + signer = NewPragueSigner(config.ChainID) case config.CancunTime != nil: signer = NewCancunSigner(config.ChainID) case config.LondonBlock != nil: @@ -94,7 +98,7 @@ func LatestSigner(config *params.ChainConfig) Signer { func LatestSignerForChainID(chainID *big.Int) Signer { var signer Signer if chainID != nil { - signer = NewCancunSigner(chainID) + signer = NewPragueSigner(chainID) } else { signer = HomesteadSigner{} } @@ -174,6 +178,77 @@ type Signer interface { Equal(Signer) bool } +type pragueSigner struct{ cancunSigner } + +// NewPragueSigner returns a signer that accepts +// - EIP-7702 set code transactions +// - EIP-4844 blob transactions +// - EIP-1559 dynamic fee transactions +// - EIP-2930 access list transactions, +// - EIP-155 replay protected transactions, and +// - legacy Homestead transactions. +func NewPragueSigner(chainId *big.Int) Signer { + signer, _ := NewCancunSigner(chainId).(cancunSigner) + return pragueSigner{signer} +} + +func (s pragueSigner) Sender(tx *Transaction) (common.Address, error) { + if tx.Type() != SetCodeTxType { + return s.cancunSigner.Sender(tx) + } + V, R, S := tx.RawSignatureValues() + + // Set code txs are defined to use 0 and 1 as their recovery + // id, add 27 to become equivalent to unprotected Homestead signatures. + V = new(big.Int).Add(V, big.NewInt(27)) + if tx.ChainId().Cmp(s.chainId) != 0 { + return common.Address{}, fmt.Errorf("%w: have %d want %d", ErrInvalidChainId, tx.ChainId(), s.chainId) + } + return recoverPlain(s.Hash(tx), R, S, V, true) +} + +func (s pragueSigner) Equal(s2 Signer) bool { + x, ok := s2.(pragueSigner) + return ok && x.chainId.Cmp(s.chainId) == 0 +} + +func (s pragueSigner) SignatureValues(tx *Transaction, sig []byte) (R, S, V *big.Int, err error) { + txdata, ok := tx.inner.(*SetCodeTx) + if !ok { + return s.cancunSigner.SignatureValues(tx, sig) + } + // Check that chain ID of tx matches the signer. We also accept ID zero here, + // because it indicates that the chain ID was not specified in the tx. + if txdata.ChainID.Sign() != 0 && txdata.ChainID.CmpBig(s.chainId) != 0 { + return nil, nil, nil, fmt.Errorf("%w: have %d want %d", ErrInvalidChainId, txdata.ChainID, s.chainId) + } + R, S, _ = decodeSignature(sig) + V = big.NewInt(int64(sig[64])) + return R, S, V, nil +} + +// Hash returns the hash to be signed by the sender. +// It does not uniquely identify the transaction. +func (s pragueSigner) Hash(tx *Transaction) common.Hash { + if tx.Type() != SetCodeTxType { + return s.cancunSigner.Hash(tx) + } + return prefixedRlpHash( + tx.Type(), + []interface{}{ + s.chainId, + tx.Nonce(), + tx.GasTipCap(), + tx.GasFeeCap(), + tx.Gas(), + tx.To(), + tx.Value(), + tx.Data(), + tx.AccessList(), + tx.SetCodeAuthorizations(), + }) +} + type cancunSigner struct{ londonSigner } // NewCancunSigner returns a signer that accepts @@ -212,7 +287,7 @@ func (s cancunSigner) SignatureValues(tx *Transaction, sig []byte) (R, S, V *big } // Check that chain ID of tx matches the signer. We also accept ID zero here, // because it indicates that the chain ID was not specified in the tx. - if txdata.ChainID.Sign() != 0 && txdata.ChainID.ToBig().Cmp(s.chainId) != 0 { + if txdata.ChainID.Sign() != 0 && txdata.ChainID.CmpBig(s.chainId) != 0 { return nil, nil, nil, fmt.Errorf("%w: have %d want %d", ErrInvalidChainId, txdata.ChainID, s.chainId) } R, S, _ = decodeSignature(sig) diff --git a/vendor/github.com/ethereum/go-ethereum/core/types/tx_blob.go b/vendor/github.com/ethereum/go-ethereum/core/types/tx_blob.go index ce1f287caa..32401db101 100644 --- a/vendor/github.com/ethereum/go-ethereum/core/types/tx_blob.go +++ b/vendor/github.com/ethereum/go-ethereum/core/types/tx_blob.go @@ -19,6 +19,7 @@ package types import ( "bytes" "crypto/sha256" + "fmt" "math/big" "github.com/ethereum/go-ethereum/common" @@ -47,9 +48,9 @@ type BlobTx struct { Sidecar *BlobTxSidecar `rlp:"-"` // Signature values - V *uint256.Int `json:"v" gencodec:"required"` - R *uint256.Int `json:"r" gencodec:"required"` - S *uint256.Int `json:"s" gencodec:"required"` + V *uint256.Int + R *uint256.Int + S *uint256.Int } // BlobTxSidecar contains the blobs of a blob transaction. @@ -85,6 +86,22 @@ func (sc *BlobTxSidecar) encodedSize() uint64 { return rlp.ListSize(blobs) + rlp.ListSize(commitments) + rlp.ListSize(proofs) } +// ValidateBlobCommitmentHashes checks whether the given hashes correspond to the +// commitments in the sidecar +func (sc *BlobTxSidecar) ValidateBlobCommitmentHashes(hashes []common.Hash) error { + if len(sc.Commitments) != len(hashes) { + return fmt.Errorf("invalid number of %d blob commitments compared to %d blob hashes", len(sc.Commitments), len(hashes)) + } + hasher := sha256.New() + for i, vhash := range hashes { + computed := kzg4844.CalcBlobHashV1(hasher, &sc.Commitments[i]) + if vhash != computed { + return fmt.Errorf("blob %d: computed hash %#x mismatches transaction one %#x", i, computed, vhash) + } + } + return nil +} + // blobTxWithBlobs is used for encoding of transactions when blobs are present. type blobTxWithBlobs struct { BlobTx *BlobTx diff --git a/vendor/github.com/ethereum/go-ethereum/core/types/tx_dynamic_fee.go b/vendor/github.com/ethereum/go-ethereum/core/types/tx_dynamic_fee.go index 8b5b514fde..981755cf70 100644 --- a/vendor/github.com/ethereum/go-ethereum/core/types/tx_dynamic_fee.go +++ b/vendor/github.com/ethereum/go-ethereum/core/types/tx_dynamic_fee.go @@ -37,9 +37,9 @@ type DynamicFeeTx struct { AccessList AccessList // Signature values - V *big.Int `json:"v" gencodec:"required"` - R *big.Int `json:"r" gencodec:"required"` - S *big.Int `json:"s" gencodec:"required"` + V *big.Int + R *big.Int + S *big.Int } // copy creates a deep copy of the transaction data and initializes all fields. diff --git a/vendor/github.com/ethereum/go-ethereum/core/types/tx_setcode.go b/vendor/github.com/ethereum/go-ethereum/core/types/tx_setcode.go new file mode 100644 index 0000000000..894bac10a3 --- /dev/null +++ b/vendor/github.com/ethereum/go-ethereum/core/types/tx_setcode.go @@ -0,0 +1,225 @@ +// Copyright 2024 The go-ethereum Authors +// This file is part of the go-ethereum library. +// +// The go-ethereum library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The go-ethereum library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see . + +package types + +import ( + "bytes" + "crypto/ecdsa" + "errors" + "math/big" + + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/rlp" + "github.com/holiman/uint256" +) + +// DelegationPrefix is used by code to denote the account is delegating to +// another account. +var DelegationPrefix = []byte{0xef, 0x01, 0x00} + +// ParseDelegation tries to parse the address from a delegation slice. +func ParseDelegation(b []byte) (common.Address, bool) { + if len(b) != 23 || !bytes.HasPrefix(b, DelegationPrefix) { + return common.Address{}, false + } + return common.BytesToAddress(b[len(DelegationPrefix):]), true +} + +// AddressToDelegation adds the delegation prefix to the specified address. +func AddressToDelegation(addr common.Address) []byte { + return append(DelegationPrefix, addr.Bytes()...) +} + +// SetCodeTx implements the EIP-7702 transaction type which temporarily installs +// the code at the signer's address. +type SetCodeTx struct { + ChainID *uint256.Int + Nonce uint64 + GasTipCap *uint256.Int // a.k.a. maxPriorityFeePerGas + GasFeeCap *uint256.Int // a.k.a. maxFeePerGas + Gas uint64 + To common.Address + Value *uint256.Int + Data []byte + AccessList AccessList + AuthList []SetCodeAuthorization + + // Signature values + V *uint256.Int + R *uint256.Int + S *uint256.Int +} + +//go:generate go run github.com/fjl/gencodec -type SetCodeAuthorization -field-override authorizationMarshaling -out gen_authorization.go + +// SetCodeAuthorization is an authorization from an account to deploy code at its address. +type SetCodeAuthorization struct { + ChainID uint256.Int `json:"chainId" gencodec:"required"` + Address common.Address `json:"address" gencodec:"required"` + Nonce uint64 `json:"nonce" gencodec:"required"` + V uint8 `json:"yParity" gencodec:"required"` + R uint256.Int `json:"r" gencodec:"required"` + S uint256.Int `json:"s" gencodec:"required"` +} + +// field type overrides for gencodec +type authorizationMarshaling struct { + ChainID hexutil.U256 + Nonce hexutil.Uint64 + V hexutil.Uint64 + R hexutil.U256 + S hexutil.U256 +} + +// SignSetCode creates a signed the SetCode authorization. +func SignSetCode(prv *ecdsa.PrivateKey, auth SetCodeAuthorization) (SetCodeAuthorization, error) { + sighash := auth.sigHash() + sig, err := crypto.Sign(sighash[:], prv) + if err != nil { + return SetCodeAuthorization{}, err + } + r, s, _ := decodeSignature(sig) + return SetCodeAuthorization{ + ChainID: auth.ChainID, + Address: auth.Address, + Nonce: auth.Nonce, + V: sig[64], + R: *uint256.MustFromBig(r), + S: *uint256.MustFromBig(s), + }, nil +} + +func (a *SetCodeAuthorization) sigHash() common.Hash { + return prefixedRlpHash(0x05, []any{ + a.ChainID, + a.Address, + a.Nonce, + }) +} + +// Authority recovers the the authorizing account of an authorization. +func (a *SetCodeAuthorization) Authority() (common.Address, error) { + sighash := a.sigHash() + if !crypto.ValidateSignatureValues(a.V, a.R.ToBig(), a.S.ToBig(), true) { + return common.Address{}, ErrInvalidSig + } + // encode the signature in uncompressed format + var sig [crypto.SignatureLength]byte + a.R.WriteToSlice(sig[:32]) + a.S.WriteToSlice(sig[32:64]) + sig[64] = a.V + // recover the public key from the signature + pub, err := crypto.Ecrecover(sighash[:], sig[:]) + if err != nil { + return common.Address{}, err + } + if len(pub) == 0 || pub[0] != 4 { + return common.Address{}, errors.New("invalid public key") + } + var addr common.Address + copy(addr[:], crypto.Keccak256(pub[1:])[12:]) + return addr, nil +} + +// copy creates a deep copy of the transaction data and initializes all fields. +func (tx *SetCodeTx) copy() TxData { + cpy := &SetCodeTx{ + Nonce: tx.Nonce, + To: tx.To, + Data: common.CopyBytes(tx.Data), + Gas: tx.Gas, + // These are copied below. + AccessList: make(AccessList, len(tx.AccessList)), + AuthList: make([]SetCodeAuthorization, len(tx.AuthList)), + Value: new(uint256.Int), + ChainID: new(uint256.Int), + GasTipCap: new(uint256.Int), + GasFeeCap: new(uint256.Int), + V: new(uint256.Int), + R: new(uint256.Int), + S: new(uint256.Int), + } + copy(cpy.AccessList, tx.AccessList) + copy(cpy.AuthList, tx.AuthList) + if tx.Value != nil { + cpy.Value.Set(tx.Value) + } + if tx.ChainID != nil { + cpy.ChainID.Set(tx.ChainID) + } + if tx.GasTipCap != nil { + cpy.GasTipCap.Set(tx.GasTipCap) + } + if tx.GasFeeCap != nil { + cpy.GasFeeCap.Set(tx.GasFeeCap) + } + if tx.V != nil { + cpy.V.Set(tx.V) + } + if tx.R != nil { + cpy.R.Set(tx.R) + } + if tx.S != nil { + cpy.S.Set(tx.S) + } + return cpy +} + +// accessors for innerTx. +func (tx *SetCodeTx) txType() byte { return SetCodeTxType } +func (tx *SetCodeTx) chainID() *big.Int { return tx.ChainID.ToBig() } +func (tx *SetCodeTx) accessList() AccessList { return tx.AccessList } +func (tx *SetCodeTx) data() []byte { return tx.Data } +func (tx *SetCodeTx) gas() uint64 { return tx.Gas } +func (tx *SetCodeTx) gasFeeCap() *big.Int { return tx.GasFeeCap.ToBig() } +func (tx *SetCodeTx) gasTipCap() *big.Int { return tx.GasTipCap.ToBig() } +func (tx *SetCodeTx) gasPrice() *big.Int { return tx.GasFeeCap.ToBig() } +func (tx *SetCodeTx) value() *big.Int { return tx.Value.ToBig() } +func (tx *SetCodeTx) nonce() uint64 { return tx.Nonce } +func (tx *SetCodeTx) to() *common.Address { tmp := tx.To; return &tmp } + +func (tx *SetCodeTx) effectiveGasPrice(dst *big.Int, baseFee *big.Int) *big.Int { + if baseFee == nil { + return dst.Set(tx.GasFeeCap.ToBig()) + } + tip := dst.Sub(tx.GasFeeCap.ToBig(), baseFee) + if tip.Cmp(tx.GasTipCap.ToBig()) > 0 { + tip.Set(tx.GasTipCap.ToBig()) + } + return tip.Add(tip, baseFee) +} + +func (tx *SetCodeTx) rawSignatureValues() (v, r, s *big.Int) { + return tx.V.ToBig(), tx.R.ToBig(), tx.S.ToBig() +} + +func (tx *SetCodeTx) setSignatureValues(chainID, v, r, s *big.Int) { + tx.ChainID = uint256.MustFromBig(chainID) + tx.V.SetFromBig(v) + tx.R.SetFromBig(r) + tx.S.SetFromBig(s) +} + +func (tx *SetCodeTx) encode(b *bytes.Buffer) error { + return rlp.Encode(b, tx) +} + +func (tx *SetCodeTx) decode(input []byte) error { + return rlp.DecodeBytes(input, tx) +} diff --git a/vendor/github.com/ethereum/go-ethereum/crypto/crypto.go b/vendor/github.com/ethereum/go-ethereum/crypto/crypto.go index f9979aa4bb..13e9b134f0 100644 --- a/vendor/github.com/ethereum/go-ethereum/crypto/crypto.go +++ b/vendor/github.com/ethereum/go-ethereum/crypto/crypto.go @@ -184,6 +184,9 @@ func UnmarshalPubkey(pub []byte) (*ecdsa.PublicKey, error) { return &ecdsa.PublicKey{Curve: S256(), X: x, Y: y}, nil } +// FromECDSAPub converts a secp256k1 public key to bytes. +// Note: it does not use the curve from pub, instead it always +// encodes using secp256k1. func FromECDSAPub(pub *ecdsa.PublicKey) []byte { if pub == nil || pub.X == nil || pub.Y == nil { return nil diff --git a/vendor/github.com/ethereum/go-ethereum/crypto/kzg4844/kzg4844_ckzg_cgo.go b/vendor/github.com/ethereum/go-ethereum/crypto/kzg4844/kzg4844_ckzg_cgo.go index 11bc451b58..dce592b444 100644 --- a/vendor/github.com/ethereum/go-ethereum/crypto/kzg4844/kzg4844_ckzg_cgo.go +++ b/vendor/github.com/ethereum/go-ethereum/crypto/kzg4844/kzg4844_ckzg_cgo.go @@ -14,7 +14,7 @@ // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see . -//go:build ckzg && !nacl && !js && cgo && !gofuzz +//go:build ckzg && !nacl && !js && !wasip1 && cgo && !gofuzz package kzg4844 diff --git a/vendor/github.com/ethereum/go-ethereum/crypto/kzg4844/kzg4844_ckzg_nocgo.go b/vendor/github.com/ethereum/go-ethereum/crypto/kzg4844/kzg4844_ckzg_nocgo.go index 70a78e80d1..0662b2632f 100644 --- a/vendor/github.com/ethereum/go-ethereum/crypto/kzg4844/kzg4844_ckzg_nocgo.go +++ b/vendor/github.com/ethereum/go-ethereum/crypto/kzg4844/kzg4844_ckzg_nocgo.go @@ -14,7 +14,7 @@ // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see . -//go:build !ckzg || nacl || js || !cgo || gofuzz +//go:build !ckzg || nacl || js || wasip1 || !cgo || gofuzz package kzg4844 diff --git a/vendor/github.com/ethereum/go-ethereum/crypto/signature_cgo.go b/vendor/github.com/ethereum/go-ethereum/crypto/signature_cgo.go index 87289253c0..5c7810c14c 100644 --- a/vendor/github.com/ethereum/go-ethereum/crypto/signature_cgo.go +++ b/vendor/github.com/ethereum/go-ethereum/crypto/signature_cgo.go @@ -14,8 +14,8 @@ // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see . -//go:build !nacl && !js && cgo && !gofuzz -// +build !nacl,!js,cgo,!gofuzz +//go:build !nacl && !js && !wasip1 && cgo && !gofuzz +// +build !nacl,!js,!wasip1,cgo,!gofuzz package crypto diff --git a/vendor/github.com/ethereum/go-ethereum/crypto/signature_nocgo.go b/vendor/github.com/ethereum/go-ethereum/crypto/signature_nocgo.go index 16a785a186..2d35b49403 100644 --- a/vendor/github.com/ethereum/go-ethereum/crypto/signature_nocgo.go +++ b/vendor/github.com/ethereum/go-ethereum/crypto/signature_nocgo.go @@ -14,8 +14,8 @@ // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see . -//go:build nacl || js || !cgo || gofuzz -// +build nacl js !cgo gofuzz +//go:build nacl || js || wasip1 || !cgo || gofuzz +// +build nacl js wasip1 !cgo gofuzz package crypto diff --git a/vendor/github.com/ethereum/go-ethereum/metrics/counter.go b/vendor/github.com/ethereum/go-ethereum/metrics/counter.go index dbe8e16a90..0f373b0d92 100644 --- a/vendor/github.com/ethereum/go-ethereum/metrics/counter.go +++ b/vendor/github.com/ethereum/go-ethereum/metrics/counter.go @@ -4,109 +4,55 @@ import ( "sync/atomic" ) -type CounterSnapshot interface { - Count() int64 -} - -// Counter hold an int64 value that can be incremented and decremented. -type Counter interface { - Clear() - Dec(int64) - Inc(int64) - Snapshot() CounterSnapshot -} - // GetOrRegisterCounter returns an existing Counter or constructs and registers -// a new StandardCounter. -func GetOrRegisterCounter(name string, r Registry) Counter { - if nil == r { +// a new Counter. +func GetOrRegisterCounter(name string, r Registry) *Counter { + if r == nil { r = DefaultRegistry } - return r.GetOrRegister(name, NewCounter).(Counter) + return r.GetOrRegister(name, NewCounter).(*Counter) } -// GetOrRegisterCounterForced returns an existing Counter or constructs and registers a -// new Counter no matter the global switch is enabled or not. -// Be sure to unregister the counter from the registry once it is of no use to -// allow for garbage collection. -func GetOrRegisterCounterForced(name string, r Registry) Counter { - if nil == r { - r = DefaultRegistry - } - return r.GetOrRegister(name, NewCounterForced).(Counter) +// NewCounter constructs a new Counter. +func NewCounter() *Counter { + return new(Counter) } -// NewCounter constructs a new StandardCounter. -func NewCounter() Counter { - if !Enabled { - return NilCounter{} - } - return new(StandardCounter) -} - -// NewCounterForced constructs a new StandardCounter and returns it no matter if -// the global switch is enabled or not. -func NewCounterForced() Counter { - return new(StandardCounter) -} - -// NewRegisteredCounter constructs and registers a new StandardCounter. -func NewRegisteredCounter(name string, r Registry) Counter { +// NewRegisteredCounter constructs and registers a new Counter. +func NewRegisteredCounter(name string, r Registry) *Counter { c := NewCounter() - if nil == r { - r = DefaultRegistry - } - r.Register(name, c) - return c -} - -// NewRegisteredCounterForced constructs and registers a new StandardCounter -// and launches a goroutine no matter the global switch is enabled or not. -// Be sure to unregister the counter from the registry once it is of no use to -// allow for garbage collection. -func NewRegisteredCounterForced(name string, r Registry) Counter { - c := NewCounterForced() - if nil == r { + if r == nil { r = DefaultRegistry } r.Register(name, c) return c } -// counterSnapshot is a read-only copy of another Counter. -type counterSnapshot int64 +// CounterSnapshot is a read-only copy of a Counter. +type CounterSnapshot int64 // Count returns the count at the time the snapshot was taken. -func (c counterSnapshot) Count() int64 { return int64(c) } - -// NilCounter is a no-op Counter. -type NilCounter struct{} +func (c CounterSnapshot) Count() int64 { return int64(c) } -func (NilCounter) Clear() {} -func (NilCounter) Dec(i int64) {} -func (NilCounter) Inc(i int64) {} -func (NilCounter) Snapshot() CounterSnapshot { return (*emptySnapshot)(nil) } - -// StandardCounter is the standard implementation of a Counter and uses the -// sync/atomic package to manage a single int64 value. -type StandardCounter atomic.Int64 +// Counter hold an int64 value that can be incremented and decremented. +type Counter atomic.Int64 // Clear sets the counter to zero. -func (c *StandardCounter) Clear() { +func (c *Counter) Clear() { (*atomic.Int64)(c).Store(0) } // Dec decrements the counter by the given amount. -func (c *StandardCounter) Dec(i int64) { +func (c *Counter) Dec(i int64) { (*atomic.Int64)(c).Add(-i) } // Inc increments the counter by the given amount. -func (c *StandardCounter) Inc(i int64) { +func (c *Counter) Inc(i int64) { (*atomic.Int64)(c).Add(i) } // Snapshot returns a read-only copy of the counter. -func (c *StandardCounter) Snapshot() CounterSnapshot { - return counterSnapshot((*atomic.Int64)(c).Load()) +func (c *Counter) Snapshot() CounterSnapshot { + return CounterSnapshot((*atomic.Int64)(c).Load()) } diff --git a/vendor/github.com/ethereum/go-ethereum/metrics/counter_float64.go b/vendor/github.com/ethereum/go-ethereum/metrics/counter_float64.go index 15c81494ef..91c4215c4d 100644 --- a/vendor/github.com/ethereum/go-ethereum/metrics/counter_float64.go +++ b/vendor/github.com/ethereum/go-ethereum/metrics/counter_float64.go @@ -5,114 +5,57 @@ import ( "sync/atomic" ) -type CounterFloat64Snapshot interface { - Count() float64 -} - -// CounterFloat64 holds a float64 value that can be incremented and decremented. -type CounterFloat64 interface { - Clear() - Dec(float64) - Inc(float64) - Snapshot() CounterFloat64Snapshot -} - -// GetOrRegisterCounterFloat64 returns an existing CounterFloat64 or constructs and registers -// a new StandardCounterFloat64. -func GetOrRegisterCounterFloat64(name string, r Registry) CounterFloat64 { +// GetOrRegisterCounterFloat64 returns an existing *CounterFloat64 or constructs and registers +// a new CounterFloat64. +func GetOrRegisterCounterFloat64(name string, r Registry) *CounterFloat64 { if nil == r { r = DefaultRegistry } - return r.GetOrRegister(name, NewCounterFloat64).(CounterFloat64) -} - -// GetOrRegisterCounterFloat64Forced returns an existing CounterFloat64 or constructs and registers a -// new CounterFloat64 no matter the global switch is enabled or not. -// Be sure to unregister the counter from the registry once it is of no use to -// allow for garbage collection. -func GetOrRegisterCounterFloat64Forced(name string, r Registry) CounterFloat64 { - if nil == r { - r = DefaultRegistry - } - return r.GetOrRegister(name, NewCounterFloat64Forced).(CounterFloat64) -} - -// NewCounterFloat64 constructs a new StandardCounterFloat64. -func NewCounterFloat64() CounterFloat64 { - if !Enabled { - return NilCounterFloat64{} - } - return &StandardCounterFloat64{} + return r.GetOrRegister(name, NewCounterFloat64).(*CounterFloat64) } -// NewCounterFloat64Forced constructs a new StandardCounterFloat64 and returns it no matter if -// the global switch is enabled or not. -func NewCounterFloat64Forced() CounterFloat64 { - return &StandardCounterFloat64{} +// NewCounterFloat64 constructs a new CounterFloat64. +func NewCounterFloat64() *CounterFloat64 { + return new(CounterFloat64) } -// NewRegisteredCounterFloat64 constructs and registers a new StandardCounterFloat64. -func NewRegisteredCounterFloat64(name string, r Registry) CounterFloat64 { +// NewRegisteredCounterFloat64 constructs and registers a new CounterFloat64. +func NewRegisteredCounterFloat64(name string, r Registry) *CounterFloat64 { c := NewCounterFloat64() - if nil == r { - r = DefaultRegistry - } - r.Register(name, c) - return c -} - -// NewRegisteredCounterFloat64Forced constructs and registers a new StandardCounterFloat64 -// and launches a goroutine no matter the global switch is enabled or not. -// Be sure to unregister the counter from the registry once it is of no use to -// allow for garbage collection. -func NewRegisteredCounterFloat64Forced(name string, r Registry) CounterFloat64 { - c := NewCounterFloat64Forced() - if nil == r { + if r == nil { r = DefaultRegistry } r.Register(name, c) return c } -// counterFloat64Snapshot is a read-only copy of another CounterFloat64. -type counterFloat64Snapshot float64 +// CounterFloat64Snapshot is a read-only copy of a float64 counter. +type CounterFloat64Snapshot float64 // Count returns the value at the time the snapshot was taken. -func (c counterFloat64Snapshot) Count() float64 { return float64(c) } - -type NilCounterFloat64 struct{} +func (c CounterFloat64Snapshot) Count() float64 { return float64(c) } -func (NilCounterFloat64) Clear() {} -func (NilCounterFloat64) Count() float64 { return 0.0 } -func (NilCounterFloat64) Dec(i float64) {} -func (NilCounterFloat64) Inc(i float64) {} -func (NilCounterFloat64) Snapshot() CounterFloat64Snapshot { return NilCounterFloat64{} } - -// StandardCounterFloat64 is the standard implementation of a CounterFloat64 and uses the -// atomic to manage a single float64 value. -type StandardCounterFloat64 struct { - floatBits atomic.Uint64 -} +// CounterFloat64 holds a float64 value that can be incremented and decremented. +type CounterFloat64 atomic.Uint64 // Clear sets the counter to zero. -func (c *StandardCounterFloat64) Clear() { - c.floatBits.Store(0) +func (c *CounterFloat64) Clear() { + (*atomic.Uint64)(c).Store(0) } // Dec decrements the counter by the given amount. -func (c *StandardCounterFloat64) Dec(v float64) { - atomicAddFloat(&c.floatBits, -v) +func (c *CounterFloat64) Dec(v float64) { + atomicAddFloat((*atomic.Uint64)(c), -v) } // Inc increments the counter by the given amount. -func (c *StandardCounterFloat64) Inc(v float64) { - atomicAddFloat(&c.floatBits, v) +func (c *CounterFloat64) Inc(v float64) { + atomicAddFloat((*atomic.Uint64)(c), v) } // Snapshot returns a read-only copy of the counter. -func (c *StandardCounterFloat64) Snapshot() CounterFloat64Snapshot { - v := math.Float64frombits(c.floatBits.Load()) - return counterFloat64Snapshot(v) +func (c *CounterFloat64) Snapshot() CounterFloat64Snapshot { + return CounterFloat64Snapshot(math.Float64frombits((*atomic.Uint64)(c).Load())) } func atomicAddFloat(fbits *atomic.Uint64, v float64) { diff --git a/vendor/github.com/ethereum/go-ethereum/metrics/cpu_disabled.go b/vendor/github.com/ethereum/go-ethereum/metrics/cpu_disabled.go index 025d97aeb3..8404b0edd4 100644 --- a/vendor/github.com/ethereum/go-ethereum/metrics/cpu_disabled.go +++ b/vendor/github.com/ethereum/go-ethereum/metrics/cpu_disabled.go @@ -14,8 +14,8 @@ // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see . -//go:build ios || js -// +build ios js +//go:build ios || js || wasip1 +// +build ios js wasip1 package metrics diff --git a/vendor/github.com/ethereum/go-ethereum/metrics/cpu_enabled.go b/vendor/github.com/ethereum/go-ethereum/metrics/cpu_enabled.go index 2359028a21..838c32fad8 100644 --- a/vendor/github.com/ethereum/go-ethereum/metrics/cpu_enabled.go +++ b/vendor/github.com/ethereum/go-ethereum/metrics/cpu_enabled.go @@ -14,8 +14,8 @@ // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see . -//go:build !ios && !js -// +build !ios,!js +//go:build !ios && !js && !wasip1 +// +build !ios,!js,!wasip1 package metrics diff --git a/vendor/github.com/ethereum/go-ethereum/metrics/cputime_unix.go b/vendor/github.com/ethereum/go-ethereum/metrics/cputime_unix.go index ad4f812fd2..a44bf80876 100644 --- a/vendor/github.com/ethereum/go-ethereum/metrics/cputime_unix.go +++ b/vendor/github.com/ethereum/go-ethereum/metrics/cputime_unix.go @@ -14,8 +14,8 @@ // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see . -//go:build !windows && !js -// +build !windows,!js +//go:build !windows && !js && !wasip1 +// +build !windows,!js,!wasip1 package metrics diff --git a/vendor/github.com/ethereum/go-ethereum/metrics/debug.go b/vendor/github.com/ethereum/go-ethereum/metrics/debug.go index 9dfee1a866..5d0d3992f1 100644 --- a/vendor/github.com/ethereum/go-ethereum/metrics/debug.go +++ b/vendor/github.com/ethereum/go-ethereum/metrics/debug.go @@ -8,13 +8,13 @@ import ( var ( debugMetrics struct { GCStats struct { - LastGC Gauge - NumGC Gauge + LastGC *Gauge + NumGC *Gauge Pause Histogram //PauseQuantiles Histogram - PauseTotal Gauge + PauseTotal *Gauge } - ReadGCStats Timer + ReadGCStats *Timer } gcStats debug.GCStats ) diff --git a/vendor/github.com/ethereum/go-ethereum/metrics/ewma.go b/vendor/github.com/ethereum/go-ethereum/metrics/ewma.go index 1d7a4f00cf..194527a798 100644 --- a/vendor/github.com/ethereum/go-ethereum/metrics/ewma.go +++ b/vendor/github.com/ethereum/go-ethereum/metrics/ewma.go @@ -7,56 +7,36 @@ import ( "time" ) -type EWMASnapshot interface { - Rate() float64 -} +// EWMASnapshot is a read-only copy of an EWMA. +type EWMASnapshot float64 -// EWMAs continuously calculate an exponentially-weighted moving average -// based on an outside source of clock ticks. -type EWMA interface { - Snapshot() EWMASnapshot - Tick() - Update(int64) -} +// Rate returns the rate of events per second at the time the snapshot was +// taken. +func (a EWMASnapshot) Rate() float64 { return float64(a) } // NewEWMA constructs a new EWMA with the given alpha. -func NewEWMA(alpha float64) EWMA { - return &StandardEWMA{alpha: alpha} +func NewEWMA(alpha float64) *EWMA { + return &EWMA{alpha: alpha} } // NewEWMA1 constructs a new EWMA for a one-minute moving average. -func NewEWMA1() EWMA { +func NewEWMA1() *EWMA { return NewEWMA(1 - math.Exp(-5.0/60.0/1)) } // NewEWMA5 constructs a new EWMA for a five-minute moving average. -func NewEWMA5() EWMA { +func NewEWMA5() *EWMA { return NewEWMA(1 - math.Exp(-5.0/60.0/5)) } // NewEWMA15 constructs a new EWMA for a fifteen-minute moving average. -func NewEWMA15() EWMA { +func NewEWMA15() *EWMA { return NewEWMA(1 - math.Exp(-5.0/60.0/15)) } -// ewmaSnapshot is a read-only copy of another EWMA. -type ewmaSnapshot float64 - -// Rate returns the rate of events per second at the time the snapshot was -// taken. -func (a ewmaSnapshot) Rate() float64 { return float64(a) } - -// NilEWMA is a no-op EWMA. -type NilEWMA struct{} - -func (NilEWMA) Snapshot() EWMASnapshot { return (*emptySnapshot)(nil) } -func (NilEWMA) Tick() {} -func (NilEWMA) Update(n int64) {} - -// StandardEWMA is the standard implementation of an EWMA and tracks the number -// of uncounted events and processes them on each tick. It uses the -// sync/atomic package to manage uncounted events. -type StandardEWMA struct { +// EWMA continuously calculate an exponentially-weighted moving average +// based on an outside source of clock ticks. +type EWMA struct { uncounted atomic.Int64 alpha float64 rate atomic.Uint64 @@ -65,27 +45,27 @@ type StandardEWMA struct { } // Snapshot returns a read-only copy of the EWMA. -func (a *StandardEWMA) Snapshot() EWMASnapshot { +func (a *EWMA) Snapshot() EWMASnapshot { r := math.Float64frombits(a.rate.Load()) * float64(time.Second) - return ewmaSnapshot(r) + return EWMASnapshot(r) } -// Tick ticks the clock to update the moving average. It assumes it is called +// tick ticks the clock to update the moving average. It assumes it is called // every five seconds. -func (a *StandardEWMA) Tick() { +func (a *EWMA) tick() { // Optimization to avoid mutex locking in the hot-path. if a.init.Load() { a.updateRate(a.fetchInstantRate()) return } - // Slow-path: this is only needed on the first Tick() and preserves transactional updating + // Slow-path: this is only needed on the first tick() and preserves transactional updating // of init and rate in the else block. The first conditional is needed below because // a different thread could have set a.init = 1 between the time of the first atomic load and when // the lock was acquired. a.mutex.Lock() if a.init.Load() { // The fetchInstantRate() uses atomic loading, which is unnecessary in this critical section - // but again, this section is only invoked on the first successful Tick() operation. + // but again, this section is only invoked on the first successful tick() operation. a.updateRate(a.fetchInstantRate()) } else { a.init.Store(true) @@ -94,18 +74,18 @@ func (a *StandardEWMA) Tick() { a.mutex.Unlock() } -func (a *StandardEWMA) fetchInstantRate() float64 { +func (a *EWMA) fetchInstantRate() float64 { count := a.uncounted.Swap(0) return float64(count) / float64(5*time.Second) } -func (a *StandardEWMA) updateRate(instantRate float64) { +func (a *EWMA) updateRate(instantRate float64) { currentRate := math.Float64frombits(a.rate.Load()) currentRate += a.alpha * (instantRate - currentRate) a.rate.Store(math.Float64bits(currentRate)) } // Update adds n uncounted events. -func (a *StandardEWMA) Update(n int64) { +func (a *EWMA) Update(n int64) { a.uncounted.Add(n) } diff --git a/vendor/github.com/ethereum/go-ethereum/metrics/gauge.go b/vendor/github.com/ethereum/go-ethereum/metrics/gauge.go index 6d10bbf856..ba7843e03b 100644 --- a/vendor/github.com/ethereum/go-ethereum/metrics/gauge.go +++ b/vendor/github.com/ethereum/go-ethereum/metrics/gauge.go @@ -2,97 +2,69 @@ package metrics import "sync/atomic" -// GaugeSnapshot contains a readonly int64. -type GaugeSnapshot interface { - Value() int64 -} +// GaugeSnapshot is a read-only copy of a Gauge. +type GaugeSnapshot int64 -// Gauge holds an int64 value that can be set arbitrarily. -type Gauge interface { - Snapshot() GaugeSnapshot - Update(int64) - UpdateIfGt(int64) - Dec(int64) - Inc(int64) -} +// Value returns the value at the time the snapshot was taken. +func (g GaugeSnapshot) Value() int64 { return int64(g) } // GetOrRegisterGauge returns an existing Gauge or constructs and registers a -// new StandardGauge. -func GetOrRegisterGauge(name string, r Registry) Gauge { - if nil == r { +// new Gauge. +func GetOrRegisterGauge(name string, r Registry) *Gauge { + if r == nil { r = DefaultRegistry } - return r.GetOrRegister(name, NewGauge).(Gauge) + return r.GetOrRegister(name, NewGauge).(*Gauge) } -// NewGauge constructs a new StandardGauge. -func NewGauge() Gauge { - if !Enabled { - return NilGauge{} - } - return &StandardGauge{} +// NewGauge constructs a new Gauge. +func NewGauge() *Gauge { + return &Gauge{} } -// NewRegisteredGauge constructs and registers a new StandardGauge. -func NewRegisteredGauge(name string, r Registry) Gauge { +// NewRegisteredGauge constructs and registers a new Gauge. +func NewRegisteredGauge(name string, r Registry) *Gauge { c := NewGauge() - if nil == r { + if r == nil { r = DefaultRegistry } r.Register(name, c) return c } -// gaugeSnapshot is a read-only copy of another Gauge. -type gaugeSnapshot int64 - -// Value returns the value at the time the snapshot was taken. -func (g gaugeSnapshot) Value() int64 { return int64(g) } - -// NilGauge is a no-op Gauge. -type NilGauge struct{} - -func (NilGauge) Snapshot() GaugeSnapshot { return (*emptySnapshot)(nil) } -func (NilGauge) Update(v int64) {} -func (NilGauge) UpdateIfGt(v int64) {} -func (NilGauge) Dec(i int64) {} -func (NilGauge) Inc(i int64) {} - -// StandardGauge is the standard implementation of a Gauge and uses the -// sync/atomic package to manage a single int64 value. -type StandardGauge struct { - value atomic.Int64 -} +// Gauge holds an int64 value that can be set arbitrarily. +type Gauge atomic.Int64 // Snapshot returns a read-only copy of the gauge. -func (g *StandardGauge) Snapshot() GaugeSnapshot { - return gaugeSnapshot(g.value.Load()) +func (g *Gauge) Snapshot() GaugeSnapshot { + return GaugeSnapshot((*atomic.Int64)(g).Load()) } // Update updates the gauge's value. -func (g *StandardGauge) Update(v int64) { - g.value.Store(v) +func (g *Gauge) Update(v int64) { + (*atomic.Int64)(g).Store(v) } // UpdateIfGt updates the gauge's value if v is larger then the current value. -func (g *StandardGauge) UpdateIfGt(v int64) { +func (g *Gauge) UpdateIfGt(v int64) { + value := (*atomic.Int64)(g) for { - exist := g.value.Load() + exist := value.Load() if exist >= v { break } - if g.value.CompareAndSwap(exist, v) { + if value.CompareAndSwap(exist, v) { break } } } // Dec decrements the gauge's current value by the given amount. -func (g *StandardGauge) Dec(i int64) { - g.value.Add(-i) +func (g *Gauge) Dec(i int64) { + (*atomic.Int64)(g).Add(-i) } // Inc increments the gauge's current value by the given amount. -func (g *StandardGauge) Inc(i int64) { - g.value.Add(i) +func (g *Gauge) Inc(i int64) { + (*atomic.Int64)(g).Add(i) } diff --git a/vendor/github.com/ethereum/go-ethereum/metrics/gauge_float64.go b/vendor/github.com/ethereum/go-ethereum/metrics/gauge_float64.go index c1c3c6b6e6..05b401ef9c 100644 --- a/vendor/github.com/ethereum/go-ethereum/metrics/gauge_float64.go +++ b/vendor/github.com/ethereum/go-ethereum/metrics/gauge_float64.go @@ -5,35 +5,28 @@ import ( "sync/atomic" ) -type GaugeFloat64Snapshot interface { - Value() float64 -} - -// GaugeFloat64 hold a float64 value that can be set arbitrarily. -type GaugeFloat64 interface { - Snapshot() GaugeFloat64Snapshot - Update(float64) -} - // GetOrRegisterGaugeFloat64 returns an existing GaugeFloat64 or constructs and registers a -// new StandardGaugeFloat64. -func GetOrRegisterGaugeFloat64(name string, r Registry) GaugeFloat64 { +// new GaugeFloat64. +func GetOrRegisterGaugeFloat64(name string, r Registry) *GaugeFloat64 { if nil == r { r = DefaultRegistry } - return r.GetOrRegister(name, NewGaugeFloat64()).(GaugeFloat64) + return r.GetOrRegister(name, NewGaugeFloat64()).(*GaugeFloat64) } -// NewGaugeFloat64 constructs a new StandardGaugeFloat64. -func NewGaugeFloat64() GaugeFloat64 { - if !Enabled { - return NilGaugeFloat64{} - } - return &StandardGaugeFloat64{} +// GaugeFloat64Snapshot is a read-only copy of a GaugeFloat64. +type GaugeFloat64Snapshot float64 + +// Value returns the value at the time the snapshot was taken. +func (g GaugeFloat64Snapshot) Value() float64 { return float64(g) } + +// NewGaugeFloat64 constructs a new GaugeFloat64. +func NewGaugeFloat64() *GaugeFloat64 { + return new(GaugeFloat64) } -// NewRegisteredGaugeFloat64 constructs and registers a new StandardGaugeFloat64. -func NewRegisteredGaugeFloat64(name string, r Registry) GaugeFloat64 { +// NewRegisteredGaugeFloat64 constructs and registers a new GaugeFloat64. +func NewRegisteredGaugeFloat64(name string, r Registry) *GaugeFloat64 { c := NewGaugeFloat64() if nil == r { r = DefaultRegistry @@ -42,32 +35,16 @@ func NewRegisteredGaugeFloat64(name string, r Registry) GaugeFloat64 { return c } -// gaugeFloat64Snapshot is a read-only copy of another GaugeFloat64. -type gaugeFloat64Snapshot float64 - -// Value returns the value at the time the snapshot was taken. -func (g gaugeFloat64Snapshot) Value() float64 { return float64(g) } - -// NilGaugeFloat64 is a no-op Gauge. -type NilGaugeFloat64 struct{} - -func (NilGaugeFloat64) Snapshot() GaugeFloat64Snapshot { return NilGaugeFloat64{} } -func (NilGaugeFloat64) Update(v float64) {} -func (NilGaugeFloat64) Value() float64 { return 0.0 } - -// StandardGaugeFloat64 is the standard implementation of a GaugeFloat64 and uses -// atomic to manage a single float64 value. -type StandardGaugeFloat64 struct { - floatBits atomic.Uint64 -} +// GaugeFloat64 hold a float64 value that can be set arbitrarily. +type GaugeFloat64 atomic.Uint64 // Snapshot returns a read-only copy of the gauge. -func (g *StandardGaugeFloat64) Snapshot() GaugeFloat64Snapshot { - v := math.Float64frombits(g.floatBits.Load()) - return gaugeFloat64Snapshot(v) +func (g *GaugeFloat64) Snapshot() GaugeFloat64Snapshot { + v := math.Float64frombits((*atomic.Uint64)(g).Load()) + return GaugeFloat64Snapshot(v) } // Update updates the gauge's value. -func (g *StandardGaugeFloat64) Update(v float64) { - g.floatBits.Store(math.Float64bits(v)) +func (g *GaugeFloat64) Update(v float64) { + (*atomic.Uint64)(g).Store(math.Float64bits(v)) } diff --git a/vendor/github.com/ethereum/go-ethereum/metrics/gauge_info.go b/vendor/github.com/ethereum/go-ethereum/metrics/gauge_info.go index 0010edc324..1862ed55c5 100644 --- a/vendor/github.com/ethereum/go-ethereum/metrics/gauge_info.go +++ b/vendor/github.com/ethereum/go-ethereum/metrics/gauge_info.go @@ -5,16 +5,6 @@ import ( "sync" ) -type GaugeInfoSnapshot interface { - Value() GaugeInfoValue -} - -// GaugeInfo holds a GaugeInfoValue value that can be set arbitrarily. -type GaugeInfo interface { - Update(GaugeInfoValue) - Snapshot() GaugeInfoSnapshot -} - // GaugeInfoValue is a mapping of keys to values type GaugeInfoValue map[string]string @@ -24,26 +14,23 @@ func (val GaugeInfoValue) String() string { } // GetOrRegisterGaugeInfo returns an existing GaugeInfo or constructs and registers a -// new StandardGaugeInfo. -func GetOrRegisterGaugeInfo(name string, r Registry) GaugeInfo { +// new GaugeInfo. +func GetOrRegisterGaugeInfo(name string, r Registry) *GaugeInfo { if nil == r { r = DefaultRegistry } - return r.GetOrRegister(name, NewGaugeInfo()).(GaugeInfo) + return r.GetOrRegister(name, NewGaugeInfo()).(*GaugeInfo) } -// NewGaugeInfo constructs a new StandardGaugeInfo. -func NewGaugeInfo() GaugeInfo { - if !Enabled { - return NilGaugeInfo{} - } - return &StandardGaugeInfo{ +// NewGaugeInfo constructs a new GaugeInfo. +func NewGaugeInfo() *GaugeInfo { + return &GaugeInfo{ value: GaugeInfoValue{}, } } -// NewRegisteredGaugeInfo constructs and registers a new StandardGaugeInfo. -func NewRegisteredGaugeInfo(name string, r Registry) GaugeInfo { +// NewRegisteredGaugeInfo constructs and registers a new GaugeInfo. +func NewRegisteredGaugeInfo(name string, r Registry) *GaugeInfo { c := NewGaugeInfo() if nil == r { r = DefaultRegistry @@ -52,32 +39,25 @@ func NewRegisteredGaugeInfo(name string, r Registry) GaugeInfo { return c } -// gaugeInfoSnapshot is a read-only copy of another GaugeInfo. -type gaugeInfoSnapshot GaugeInfoValue +// GaugeInfoSnapshot is a read-only copy of another GaugeInfo. +type GaugeInfoSnapshot GaugeInfoValue // Value returns the value at the time the snapshot was taken. -func (g gaugeInfoSnapshot) Value() GaugeInfoValue { return GaugeInfoValue(g) } - -type NilGaugeInfo struct{} - -func (NilGaugeInfo) Snapshot() GaugeInfoSnapshot { return NilGaugeInfo{} } -func (NilGaugeInfo) Update(v GaugeInfoValue) {} -func (NilGaugeInfo) Value() GaugeInfoValue { return GaugeInfoValue{} } +func (g GaugeInfoSnapshot) Value() GaugeInfoValue { return GaugeInfoValue(g) } -// StandardGaugeInfo is the standard implementation of a GaugeInfo and uses -// sync.Mutex to manage a single string value. -type StandardGaugeInfo struct { +// GaugeInfo maintains a set of key/value mappings. +type GaugeInfo struct { mutex sync.Mutex value GaugeInfoValue } // Snapshot returns a read-only copy of the gauge. -func (g *StandardGaugeInfo) Snapshot() GaugeInfoSnapshot { - return gaugeInfoSnapshot(g.value) +func (g *GaugeInfo) Snapshot() GaugeInfoSnapshot { + return GaugeInfoSnapshot(g.value) } // Update updates the gauge's value. -func (g *StandardGaugeInfo) Update(v GaugeInfoValue) { +func (g *GaugeInfo) Update(v GaugeInfoValue) { g.mutex.Lock() defer g.mutex.Unlock() g.value = v diff --git a/vendor/github.com/ethereum/go-ethereum/metrics/graphite.go b/vendor/github.com/ethereum/go-ethereum/metrics/graphite.go deleted file mode 100644 index aba752e0ed..0000000000 --- a/vendor/github.com/ethereum/go-ethereum/metrics/graphite.go +++ /dev/null @@ -1,117 +0,0 @@ -package metrics - -import ( - "bufio" - "fmt" - "log" - "net" - "strconv" - "strings" - "time" -) - -// GraphiteConfig provides a container with configuration parameters for -// the Graphite exporter -type GraphiteConfig struct { - Addr *net.TCPAddr // Network address to connect to - Registry Registry // Registry to be exported - FlushInterval time.Duration // Flush interval - DurationUnit time.Duration // Time conversion unit for durations - Prefix string // Prefix to be prepended to metric names - Percentiles []float64 // Percentiles to export from timers and histograms -} - -// Graphite is a blocking exporter function which reports metrics in r -// to a graphite server located at addr, flushing them every d duration -// and prepending metric names with prefix. -func Graphite(r Registry, d time.Duration, prefix string, addr *net.TCPAddr) { - GraphiteWithConfig(GraphiteConfig{ - Addr: addr, - Registry: r, - FlushInterval: d, - DurationUnit: time.Nanosecond, - Prefix: prefix, - Percentiles: []float64{0.5, 0.75, 0.95, 0.99, 0.999}, - }) -} - -// GraphiteWithConfig is a blocking exporter function just like Graphite, -// but it takes a GraphiteConfig instead. -func GraphiteWithConfig(c GraphiteConfig) { - log.Printf("WARNING: This go-metrics client has been DEPRECATED! It has been moved to https://github.com/cyberdelia/go-metrics-graphite and will be removed from rcrowley/go-metrics on August 12th 2015") - for range time.Tick(c.FlushInterval) { - if err := graphite(&c); nil != err { - log.Println(err) - } - } -} - -// GraphiteOnce performs a single submission to Graphite, returning a -// non-nil error on failed connections. This can be used in a loop -// similar to GraphiteWithConfig for custom error handling. -func GraphiteOnce(c GraphiteConfig) error { - log.Printf("WARNING: This go-metrics client has been DEPRECATED! It has been moved to https://github.com/cyberdelia/go-metrics-graphite and will be removed from rcrowley/go-metrics on August 12th 2015") - return graphite(&c) -} - -func graphite(c *GraphiteConfig) error { - now := time.Now().Unix() - du := float64(c.DurationUnit) - conn, err := net.DialTCP("tcp", nil, c.Addr) - if nil != err { - return err - } - defer conn.Close() - w := bufio.NewWriter(conn) - c.Registry.Each(func(name string, i interface{}) { - switch metric := i.(type) { - case Counter: - fmt.Fprintf(w, "%s.%s.count %d %d\n", c.Prefix, name, metric.Snapshot().Count(), now) - case CounterFloat64: - fmt.Fprintf(w, "%s.%s.count %f %d\n", c.Prefix, name, metric.Snapshot().Count(), now) - case Gauge: - fmt.Fprintf(w, "%s.%s.value %d %d\n", c.Prefix, name, metric.Snapshot().Value(), now) - case GaugeFloat64: - fmt.Fprintf(w, "%s.%s.value %f %d\n", c.Prefix, name, metric.Snapshot().Value(), now) - case GaugeInfo: - fmt.Fprintf(w, "%s.%s.value %s %d\n", c.Prefix, name, metric.Snapshot().Value().String(), now) - case Histogram: - h := metric.Snapshot() - ps := h.Percentiles(c.Percentiles) - fmt.Fprintf(w, "%s.%s.count %d %d\n", c.Prefix, name, h.Count(), now) - fmt.Fprintf(w, "%s.%s.min %d %d\n", c.Prefix, name, h.Min(), now) - fmt.Fprintf(w, "%s.%s.max %d %d\n", c.Prefix, name, h.Max(), now) - fmt.Fprintf(w, "%s.%s.mean %.2f %d\n", c.Prefix, name, h.Mean(), now) - fmt.Fprintf(w, "%s.%s.std-dev %.2f %d\n", c.Prefix, name, h.StdDev(), now) - for psIdx, psKey := range c.Percentiles { - key := strings.Replace(strconv.FormatFloat(psKey*100.0, 'f', -1, 64), ".", "", 1) - fmt.Fprintf(w, "%s.%s.%s-percentile %.2f %d\n", c.Prefix, name, key, ps[psIdx], now) - } - case Meter: - m := metric.Snapshot() - fmt.Fprintf(w, "%s.%s.count %d %d\n", c.Prefix, name, m.Count(), now) - fmt.Fprintf(w, "%s.%s.one-minute %.2f %d\n", c.Prefix, name, m.Rate1(), now) - fmt.Fprintf(w, "%s.%s.five-minute %.2f %d\n", c.Prefix, name, m.Rate5(), now) - fmt.Fprintf(w, "%s.%s.fifteen-minute %.2f %d\n", c.Prefix, name, m.Rate15(), now) - fmt.Fprintf(w, "%s.%s.mean %.2f %d\n", c.Prefix, name, m.RateMean(), now) - case Timer: - t := metric.Snapshot() - ps := t.Percentiles(c.Percentiles) - fmt.Fprintf(w, "%s.%s.count %d %d\n", c.Prefix, name, t.Count(), now) - fmt.Fprintf(w, "%s.%s.min %d %d\n", c.Prefix, name, t.Min()/int64(du), now) - fmt.Fprintf(w, "%s.%s.max %d %d\n", c.Prefix, name, t.Max()/int64(du), now) - fmt.Fprintf(w, "%s.%s.mean %.2f %d\n", c.Prefix, name, t.Mean()/du, now) - fmt.Fprintf(w, "%s.%s.std-dev %.2f %d\n", c.Prefix, name, t.StdDev()/du, now) - for psIdx, psKey := range c.Percentiles { - key := strings.Replace(strconv.FormatFloat(psKey*100.0, 'f', -1, 64), ".", "", 1) - fmt.Fprintf(w, "%s.%s.%s-percentile %.2f %d\n", c.Prefix, name, key, ps[psIdx], now) - } - fmt.Fprintf(w, "%s.%s.one-minute %.2f %d\n", c.Prefix, name, t.Rate1(), now) - fmt.Fprintf(w, "%s.%s.five-minute %.2f %d\n", c.Prefix, name, t.Rate5(), now) - fmt.Fprintf(w, "%s.%s.fifteen-minute %.2f %d\n", c.Prefix, name, t.Rate15(), now) - fmt.Fprintf(w, "%s.%s.mean-rate %.2f %d\n", c.Prefix, name, t.RateMean(), now) - } - w.Flush() - }) - return nil -} diff --git a/vendor/github.com/ethereum/go-ethereum/metrics/healthcheck.go b/vendor/github.com/ethereum/go-ethereum/metrics/healthcheck.go index adcd15ab58..435e5e0bf9 100644 --- a/vendor/github.com/ethereum/go-ethereum/metrics/healthcheck.go +++ b/vendor/github.com/ethereum/go-ethereum/metrics/healthcheck.go @@ -1,61 +1,35 @@ package metrics -// Healthcheck holds an error value describing an arbitrary up/down status. -type Healthcheck interface { - Check() - Error() error - Healthy() - Unhealthy(error) -} - // NewHealthcheck constructs a new Healthcheck which will use the given // function to update its status. -func NewHealthcheck(f func(Healthcheck)) Healthcheck { - if !Enabled { - return NilHealthcheck{} - } - return &StandardHealthcheck{nil, f} +func NewHealthcheck(f func(*Healthcheck)) *Healthcheck { + return &Healthcheck{nil, f} } -// NilHealthcheck is a no-op. -type NilHealthcheck struct{} - -// Check is a no-op. -func (NilHealthcheck) Check() {} - -// Error is a no-op. -func (NilHealthcheck) Error() error { return nil } - -// Healthy is a no-op. -func (NilHealthcheck) Healthy() {} - -// Unhealthy is a no-op. -func (NilHealthcheck) Unhealthy(error) {} - -// StandardHealthcheck is the standard implementation of a Healthcheck and +// Healthcheck is the standard implementation of a Healthcheck and // stores the status and a function to call to update the status. -type StandardHealthcheck struct { +type Healthcheck struct { err error - f func(Healthcheck) + f func(*Healthcheck) } // Check runs the healthcheck function to update the healthcheck's status. -func (h *StandardHealthcheck) Check() { +func (h *Healthcheck) Check() { h.f(h) } // Error returns the healthcheck's status, which will be nil if it is healthy. -func (h *StandardHealthcheck) Error() error { +func (h *Healthcheck) Error() error { return h.err } // Healthy marks the healthcheck as healthy. -func (h *StandardHealthcheck) Healthy() { +func (h *Healthcheck) Healthy() { h.err = nil } // Unhealthy marks the healthcheck as unhealthy. The error is stored and // may be retrieved by the Error method. -func (h *StandardHealthcheck) Unhealthy(err error) { +func (h *Healthcheck) Unhealthy(err error) { h.err = err } diff --git a/vendor/github.com/ethereum/go-ethereum/metrics/histogram.go b/vendor/github.com/ethereum/go-ethereum/metrics/histogram.go index 10259a2463..7c27bcc928 100644 --- a/vendor/github.com/ethereum/go-ethereum/metrics/histogram.go +++ b/vendor/github.com/ethereum/go-ethereum/metrics/histogram.go @@ -1,7 +1,16 @@ package metrics type HistogramSnapshot interface { - SampleSnapshot + Count() int64 + Max() int64 + Mean() float64 + Min() int64 + Percentile(float64) float64 + Percentiles([]float64) []float64 + Size() int + StdDev() float64 + Sum() int64 + Variance() float64 } // Histogram calculates distribution statistics from a series of int64 values. @@ -31,10 +40,7 @@ func GetOrRegisterHistogramLazy(name string, r Registry, s func() Sample) Histog // NewHistogram constructs a new StandardHistogram from a Sample. func NewHistogram(s Sample) Histogram { - if !Enabled { - return NilHistogram{} - } - return &StandardHistogram{sample: s} + return &StandardHistogram{s} } // NewRegisteredHistogram constructs and registers a new StandardHistogram from @@ -48,13 +54,6 @@ func NewRegisteredHistogram(name string, r Registry, s Sample) Histogram { return c } -// NilHistogram is a no-op Histogram. -type NilHistogram struct{} - -func (NilHistogram) Clear() {} -func (NilHistogram) Snapshot() HistogramSnapshot { return (*emptySnapshot)(nil) } -func (NilHistogram) Update(v int64) {} - // StandardHistogram is the standard implementation of a Histogram and uses a // Sample to bound its memory use. type StandardHistogram struct { diff --git a/vendor/github.com/ethereum/go-ethereum/metrics/inactive.go b/vendor/github.com/ethereum/go-ethereum/metrics/inactive.go deleted file mode 100644 index 1f47f0210a..0000000000 --- a/vendor/github.com/ethereum/go-ethereum/metrics/inactive.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2023 The go-ethereum Authors -// This file is part of the go-ethereum library. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -package metrics - -// compile-time checks that interfaces are implemented. -var ( - _ SampleSnapshot = (*emptySnapshot)(nil) - _ HistogramSnapshot = (*emptySnapshot)(nil) - _ CounterSnapshot = (*emptySnapshot)(nil) - _ GaugeSnapshot = (*emptySnapshot)(nil) - _ MeterSnapshot = (*emptySnapshot)(nil) - _ EWMASnapshot = (*emptySnapshot)(nil) - _ TimerSnapshot = (*emptySnapshot)(nil) -) - -type emptySnapshot struct{} - -func (*emptySnapshot) Count() int64 { return 0 } -func (*emptySnapshot) Max() int64 { return 0 } -func (*emptySnapshot) Mean() float64 { return 0.0 } -func (*emptySnapshot) Min() int64 { return 0 } -func (*emptySnapshot) Percentile(p float64) float64 { return 0.0 } -func (*emptySnapshot) Percentiles(ps []float64) []float64 { return make([]float64, len(ps)) } -func (*emptySnapshot) Size() int { return 0 } -func (*emptySnapshot) StdDev() float64 { return 0.0 } -func (*emptySnapshot) Sum() int64 { return 0 } -func (*emptySnapshot) Values() []int64 { return []int64{} } -func (*emptySnapshot) Variance() float64 { return 0.0 } -func (*emptySnapshot) Value() int64 { return 0 } -func (*emptySnapshot) Rate() float64 { return 0.0 } -func (*emptySnapshot) Rate1() float64 { return 0.0 } -func (*emptySnapshot) Rate5() float64 { return 0.0 } -func (*emptySnapshot) Rate15() float64 { return 0.0 } -func (*emptySnapshot) RateMean() float64 { return 0.0 } diff --git a/vendor/github.com/ethereum/go-ethereum/metrics/log.go b/vendor/github.com/ethereum/go-ethereum/metrics/log.go index 3b9773faa7..08f3effb81 100644 --- a/vendor/github.com/ethereum/go-ethereum/metrics/log.go +++ b/vendor/github.com/ethereum/go-ethereum/metrics/log.go @@ -12,7 +12,7 @@ func Log(r Registry, freq time.Duration, l Logger) { LogScaled(r, freq, time.Nanosecond, l) } -// Output each metric in the given registry periodically using the given +// LogScaled outputs each metric in the given registry periodically using the given // logger. Print timings in `scale` units (eg time.Millisecond) rather than nanos. func LogScaled(r Registry, freq time.Duration, scale time.Duration, l Logger) { du := float64(scale) @@ -21,25 +21,21 @@ func LogScaled(r Registry, freq time.Duration, scale time.Duration, l Logger) { for range time.Tick(freq) { r.Each(func(name string, i interface{}) { switch metric := i.(type) { - case Counter: + case *Counter: l.Printf("counter %s\n", name) l.Printf(" count: %9d\n", metric.Snapshot().Count()) - case CounterFloat64: + case *CounterFloat64: l.Printf("counter %s\n", name) l.Printf(" count: %f\n", metric.Snapshot().Count()) - case Gauge: + case *Gauge: l.Printf("gauge %s\n", name) l.Printf(" value: %9d\n", metric.Snapshot().Value()) - case GaugeFloat64: + case *GaugeFloat64: l.Printf("gauge %s\n", name) l.Printf(" value: %f\n", metric.Snapshot().Value()) - case GaugeInfo: + case *GaugeInfo: l.Printf("gauge %s\n", name) l.Printf(" value: %s\n", metric.Snapshot().Value()) - case Healthcheck: - metric.Check() - l.Printf("healthcheck %s\n", name) - l.Printf(" error: %v\n", metric.Error()) case Histogram: h := metric.Snapshot() ps := h.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999}) @@ -54,7 +50,7 @@ func LogScaled(r Registry, freq time.Duration, scale time.Duration, l Logger) { l.Printf(" 95%%: %12.2f\n", ps[2]) l.Printf(" 99%%: %12.2f\n", ps[3]) l.Printf(" 99.9%%: %12.2f\n", ps[4]) - case Meter: + case *Meter: m := metric.Snapshot() l.Printf("meter %s\n", name) l.Printf(" count: %9d\n", m.Count()) @@ -62,7 +58,7 @@ func LogScaled(r Registry, freq time.Duration, scale time.Duration, l Logger) { l.Printf(" 5-min rate: %12.2f\n", m.Rate5()) l.Printf(" 15-min rate: %12.2f\n", m.Rate15()) l.Printf(" mean rate: %12.2f\n", m.RateMean()) - case Timer: + case *Timer: t := metric.Snapshot() ps := t.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999}) l.Printf("timer %s\n", name) diff --git a/vendor/github.com/ethereum/go-ethereum/metrics/meter.go b/vendor/github.com/ethereum/go-ethereum/metrics/meter.go index 432838f4ef..194bd1f304 100644 --- a/vendor/github.com/ethereum/go-ethereum/metrics/meter.go +++ b/vendor/github.com/ethereum/go-ethereum/metrics/meter.go @@ -7,114 +7,78 @@ import ( "time" ) -type MeterSnapshot interface { - Count() int64 - Rate1() float64 - Rate5() float64 - Rate15() float64 - RateMean() float64 -} - -// Meters count events to produce exponentially-weighted moving average rates -// at one-, five-, and fifteen-minutes and a mean rate. -type Meter interface { - Mark(int64) - Snapshot() MeterSnapshot - Stop() -} - // GetOrRegisterMeter returns an existing Meter or constructs and registers a -// new StandardMeter. +// new Meter. // Be sure to unregister the meter from the registry once it is of no use to // allow for garbage collection. -func GetOrRegisterMeter(name string, r Registry) Meter { - if nil == r { +func GetOrRegisterMeter(name string, r Registry) *Meter { + if r == nil { r = DefaultRegistry } - return r.GetOrRegister(name, NewMeter).(Meter) + return r.GetOrRegister(name, NewMeter).(*Meter) } -// NewMeter constructs a new StandardMeter and launches a goroutine. +// NewMeter constructs a new Meter and launches a goroutine. // Be sure to call Stop() once the meter is of no use to allow for garbage collection. -func NewMeter() Meter { - if !Enabled { - return NilMeter{} - } - m := newStandardMeter() - arbiter.Lock() - defer arbiter.Unlock() - arbiter.meters[m] = struct{}{} - if !arbiter.started { - arbiter.started = true - go arbiter.tick() - } +func NewMeter() *Meter { + m := newMeter() + arbiter.add(m) return m } // NewInactiveMeter returns a meter but does not start any goroutines. This // method is mainly intended for testing. -func NewInactiveMeter() Meter { - if !Enabled { - return NilMeter{} - } - m := newStandardMeter() - return m +func NewInactiveMeter() *Meter { + return newMeter() } -// NewRegisteredMeter constructs and registers a new StandardMeter +// NewRegisteredMeter constructs and registers a new Meter // and launches a goroutine. // Be sure to unregister the meter from the registry once it is of no use to // allow for garbage collection. -func NewRegisteredMeter(name string, r Registry) Meter { +func NewRegisteredMeter(name string, r Registry) *Meter { return GetOrRegisterMeter(name, r) } -// meterSnapshot is a read-only copy of the meter's internal values. -type meterSnapshot struct { +// MeterSnapshot is a read-only copy of the meter's internal values. +type MeterSnapshot struct { count int64 rate1, rate5, rate15, rateMean float64 } // Count returns the count of events at the time the snapshot was taken. -func (m *meterSnapshot) Count() int64 { return m.count } +func (m *MeterSnapshot) Count() int64 { return m.count } // Rate1 returns the one-minute moving average rate of events per second at the // time the snapshot was taken. -func (m *meterSnapshot) Rate1() float64 { return m.rate1 } +func (m *MeterSnapshot) Rate1() float64 { return m.rate1 } // Rate5 returns the five-minute moving average rate of events per second at // the time the snapshot was taken. -func (m *meterSnapshot) Rate5() float64 { return m.rate5 } +func (m *MeterSnapshot) Rate5() float64 { return m.rate5 } // Rate15 returns the fifteen-minute moving average rate of events per second // at the time the snapshot was taken. -func (m *meterSnapshot) Rate15() float64 { return m.rate15 } +func (m *MeterSnapshot) Rate15() float64 { return m.rate15 } // RateMean returns the meter's mean rate of events per second at the time the // snapshot was taken. -func (m *meterSnapshot) RateMean() float64 { return m.rateMean } - -// NilMeter is a no-op Meter. -type NilMeter struct{} +func (m *MeterSnapshot) RateMean() float64 { return m.rateMean } -func (NilMeter) Count() int64 { return 0 } -func (NilMeter) Mark(n int64) {} -func (NilMeter) Snapshot() MeterSnapshot { return (*emptySnapshot)(nil) } -func (NilMeter) Stop() {} - -// StandardMeter is the standard implementation of a Meter. -type StandardMeter struct { +// Meter count events to produce exponentially-weighted moving average rates +// at one-, five-, and fifteen-minutes and a mean rate. +type Meter struct { count atomic.Int64 uncounted atomic.Int64 // not yet added to the EWMAs rateMean atomic.Uint64 - a1, a5, a15 EWMA + a1, a5, a15 *EWMA startTime time.Time stopped atomic.Bool } -func newStandardMeter() *StandardMeter { - return &StandardMeter{ +func newMeter() *Meter { + return &Meter{ a1: NewEWMA1(), a5: NewEWMA5(), a15: NewEWMA15(), @@ -123,22 +87,20 @@ func newStandardMeter() *StandardMeter { } // Stop stops the meter, Mark() will be a no-op if you use it after being stopped. -func (m *StandardMeter) Stop() { +func (m *Meter) Stop() { if stopped := m.stopped.Swap(true); !stopped { - arbiter.Lock() - delete(arbiter.meters, m) - arbiter.Unlock() + arbiter.remove(m) } } // Mark records the occurrence of n events. -func (m *StandardMeter) Mark(n int64) { +func (m *Meter) Mark(n int64) { m.uncounted.Add(n) } // Snapshot returns a read-only copy of the meter. -func (m *StandardMeter) Snapshot() MeterSnapshot { - return &meterSnapshot{ +func (m *Meter) Snapshot() *MeterSnapshot { + return &MeterSnapshot{ count: m.count.Load() + m.uncounted.Load(), rate1: m.a1.Snapshot().Rate(), rate5: m.a5.Snapshot().Rate(), @@ -147,7 +109,7 @@ func (m *StandardMeter) Snapshot() MeterSnapshot { } } -func (m *StandardMeter) tick() { +func (m *Meter) tick() { // Take the uncounted values, add to count n := m.uncounted.Swap(0) count := m.count.Add(n) @@ -157,33 +119,51 @@ func (m *StandardMeter) tick() { m.a5.Update(n) m.a15.Update(n) // And trigger them to calculate the rates - m.a1.Tick() - m.a5.Tick() - m.a15.Tick() + m.a1.tick() + m.a5.tick() + m.a15.tick() } -// meterArbiter ticks meters every 5s from a single goroutine. +var arbiter = meterTicker{meters: make(map[*Meter]struct{})} + +// meterTicker ticks meters every 5s from a single goroutine. // meters are references in a set for future stopping. -type meterArbiter struct { - sync.RWMutex +type meterTicker struct { + mu sync.RWMutex + started bool - meters map[*StandardMeter]struct{} - ticker *time.Ticker + meters map[*Meter]struct{} } -var arbiter = meterArbiter{ticker: time.NewTicker(5 * time.Second), meters: make(map[*StandardMeter]struct{})} - -// tick meters on the scheduled interval -func (ma *meterArbiter) tick() { - for range ma.ticker.C { - ma.tickMeters() +// add adds another *Meter ot the arbiter, and starts the arbiter ticker. +func (ma *meterTicker) add(m *Meter) { + ma.mu.Lock() + defer ma.mu.Unlock() + ma.meters[m] = struct{}{} + if !ma.started { + ma.started = true + go ma.loop() } } -func (ma *meterArbiter) tickMeters() { - ma.RLock() - defer ma.RUnlock() - for meter := range ma.meters { - meter.tick() +// remove removes a meter from the set of ticked meters. +func (ma *meterTicker) remove(m *Meter) { + ma.mu.Lock() + delete(ma.meters, m) + ma.mu.Unlock() +} + +// loop ticks meters on a 5 second interval. +func (ma *meterTicker) loop() { + ticker := time.NewTicker(5 * time.Second) + for range ticker.C { + if !metricsEnabled { + continue + } + ma.mu.RLock() + for meter := range ma.meters { + meter.tick() + } + ma.mu.RUnlock() } } diff --git a/vendor/github.com/ethereum/go-ethereum/metrics/metrics.go b/vendor/github.com/ethereum/go-ethereum/metrics/metrics.go index c7fe5c7333..c4c43b7576 100644 --- a/vendor/github.com/ethereum/go-ethereum/metrics/metrics.go +++ b/vendor/github.com/ethereum/go-ethereum/metrics/metrics.go @@ -3,55 +3,33 @@ // // // Coda Hale's original work: + package metrics import ( - "os" "runtime/metrics" "runtime/pprof" - "strconv" - "strings" - "syscall" "time" +) - "github.com/ethereum/go-ethereum/log" +var ( + metricsEnabled = false ) -// Enabled is checked by the constructor functions for all of the -// standard metrics. If it is true, the metric returned is a stub. +// Enabled is checked by functions that are deemed 'expensive', e.g. if a +// meter-type does locking and/or non-trivial math operations during update. +func Enabled() bool { + return metricsEnabled +} + +// Enable enables the metrics system. +// The Enabled-flag is expected to be set, once, during startup, but toggling off and on +// is not supported. // -// This global kill-switch helps quantify the observer effect and makes -// for less cluttered pprof profiles. -var Enabled = false - -// enablerFlags is the CLI flag names to use to enable metrics collections. -var enablerFlags = []string{"metrics"} - -// enablerEnvVars is the env var names to use to enable metrics collections. -var enablerEnvVars = []string{"GETH_METRICS"} - -// init enables or disables the metrics system. Since we need this to run before -// any other code gets to create meters and timers, we'll actually do an ugly hack -// and peek into the command line args for the metrics flag. -func init() { - for _, enabler := range enablerEnvVars { - if val, found := syscall.Getenv(enabler); found && !Enabled { - if enable, _ := strconv.ParseBool(val); enable { // ignore error, flag parser will choke on it later - log.Info("Enabling metrics collection") - Enabled = true - } - } - } - for _, arg := range os.Args { - flag := strings.TrimLeft(arg, "-") - - for _, enabler := range enablerFlags { - if !Enabled && flag == enabler { - log.Info("Enabling metrics collection") - Enabled = true - } - } - } +// Enable is not safe to call concurrently. You need to call this as early as possible in +// the program, before any metrics collection will happen. +func Enable() { + metricsEnabled = true } var threadCreateProfile = pprof.Lookup("threadcreate") @@ -128,7 +106,7 @@ func readRuntimeStats(v *runtimeStats) { // CollectProcessMetrics periodically collects various metrics about the running process. func CollectProcessMetrics(refresh time.Duration) { // Short circuit if the metrics system is disabled - if !Enabled { + if !metricsEnabled { return } diff --git a/vendor/github.com/ethereum/go-ethereum/metrics/opentsdb.go b/vendor/github.com/ethereum/go-ethereum/metrics/opentsdb.go index e81690f943..57af3d025e 100644 --- a/vendor/github.com/ethereum/go-ethereum/metrics/opentsdb.go +++ b/vendor/github.com/ethereum/go-ethereum/metrics/opentsdb.go @@ -64,15 +64,15 @@ func (c *OpenTSDBConfig) writeRegistry(w io.Writer, now int64, shortHostname str c.Registry.Each(func(name string, i interface{}) { switch metric := i.(type) { - case Counter: + case *Counter: fmt.Fprintf(w, "put %s.%s.count %d %d host=%s\n", c.Prefix, name, now, metric.Snapshot().Count(), shortHostname) - case CounterFloat64: + case *CounterFloat64: fmt.Fprintf(w, "put %s.%s.count %d %f host=%s\n", c.Prefix, name, now, metric.Snapshot().Count(), shortHostname) - case Gauge: + case *Gauge: fmt.Fprintf(w, "put %s.%s.value %d %d host=%s\n", c.Prefix, name, now, metric.Snapshot().Value(), shortHostname) - case GaugeFloat64: + case *GaugeFloat64: fmt.Fprintf(w, "put %s.%s.value %d %f host=%s\n", c.Prefix, name, now, metric.Snapshot().Value(), shortHostname) - case GaugeInfo: + case *GaugeInfo: fmt.Fprintf(w, "put %s.%s.value %d %s host=%s\n", c.Prefix, name, now, metric.Snapshot().Value().String(), shortHostname) case Histogram: h := metric.Snapshot() @@ -87,14 +87,14 @@ func (c *OpenTSDBConfig) writeRegistry(w io.Writer, now int64, shortHostname str fmt.Fprintf(w, "put %s.%s.95-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[2], shortHostname) fmt.Fprintf(w, "put %s.%s.99-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[3], shortHostname) fmt.Fprintf(w, "put %s.%s.999-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[4], shortHostname) - case Meter: + case *Meter: m := metric.Snapshot() fmt.Fprintf(w, "put %s.%s.count %d %d host=%s\n", c.Prefix, name, now, m.Count(), shortHostname) fmt.Fprintf(w, "put %s.%s.one-minute %d %.2f host=%s\n", c.Prefix, name, now, m.Rate1(), shortHostname) fmt.Fprintf(w, "put %s.%s.five-minute %d %.2f host=%s\n", c.Prefix, name, now, m.Rate5(), shortHostname) fmt.Fprintf(w, "put %s.%s.fifteen-minute %d %.2f host=%s\n", c.Prefix, name, now, m.Rate15(), shortHostname) fmt.Fprintf(w, "put %s.%s.mean %d %.2f host=%s\n", c.Prefix, name, now, m.RateMean(), shortHostname) - case Timer: + case *Timer: t := metric.Snapshot() ps := t.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999}) fmt.Fprintf(w, "put %s.%s.count %d %d host=%s\n", c.Prefix, name, now, t.Count(), shortHostname) diff --git a/vendor/github.com/ethereum/go-ethereum/metrics/registry.go b/vendor/github.com/ethereum/go-ethereum/metrics/registry.go index ca4741feef..527da6238d 100644 --- a/vendor/github.com/ethereum/go-ethereum/metrics/registry.go +++ b/vendor/github.com/ethereum/go-ethereum/metrics/registry.go @@ -1,6 +1,7 @@ package metrics import ( + "errors" "fmt" "reflect" "sort" @@ -8,14 +9,10 @@ import ( "sync" ) -// DuplicateMetric is the error returned by Registry. Register when a metric +// ErrDuplicateMetric is the error returned by Registry.Register when a metric // already exists. If you mean to Register that metric you must first // Unregister the existing metric. -type DuplicateMetric string - -func (err DuplicateMetric) Error() string { - return fmt.Sprintf("duplicate metric: %s", string(err)) -} +var ErrDuplicateMetric = errors.New("duplicate metric") // A Registry holds references to a set of metrics by name and can iterate // over them, calling callback functions provided by the user. @@ -114,13 +111,13 @@ func (r *StandardRegistry) GetOrRegister(name string, i interface{}) interface{} return item } -// Register the given metric under the given name. Returns a DuplicateMetric +// Register the given metric under the given name. Returns a ErrDuplicateMetric // if a metric by the given name is already registered. func (r *StandardRegistry) Register(name string, i interface{}) error { // fast path _, ok := r.metrics.Load(name) if ok { - return DuplicateMetric(name) + return fmt.Errorf("%w: %v", ErrDuplicateMetric, name) } if v := reflect.ValueOf(i); v.Kind() == reflect.Func { @@ -128,7 +125,7 @@ func (r *StandardRegistry) Register(name string, i interface{}) error { } _, loaded, _ := r.loadOrRegister(name, i) if loaded { - return DuplicateMetric(name) + return fmt.Errorf("%w: %v", ErrDuplicateMetric, name) } return nil } @@ -136,7 +133,7 @@ func (r *StandardRegistry) Register(name string, i interface{}) error { // RunHealthchecks run all registered healthchecks. func (r *StandardRegistry) RunHealthchecks() { r.metrics.Range(func(key, value any) bool { - if h, ok := value.(Healthcheck); ok { + if h, ok := value.(*Healthcheck); ok { h.Check() } return true @@ -149,15 +146,15 @@ func (r *StandardRegistry) GetAll() map[string]map[string]interface{} { r.Each(func(name string, i interface{}) { values := make(map[string]interface{}) switch metric := i.(type) { - case Counter: + case *Counter: values["count"] = metric.Snapshot().Count() - case CounterFloat64: + case *CounterFloat64: values["count"] = metric.Snapshot().Count() - case Gauge: + case *Gauge: values["value"] = metric.Snapshot().Value() - case GaugeFloat64: + case *GaugeFloat64: values["value"] = metric.Snapshot().Value() - case Healthcheck: + case *Healthcheck: values["error"] = nil metric.Check() if err := metric.Error(); nil != err { @@ -176,14 +173,14 @@ func (r *StandardRegistry) GetAll() map[string]map[string]interface{} { values["95%"] = ps[2] values["99%"] = ps[3] values["99.9%"] = ps[4] - case Meter: + case *Meter: m := metric.Snapshot() values["count"] = m.Count() values["1m.rate"] = m.Rate1() values["5m.rate"] = m.Rate5() values["15m.rate"] = m.Rate15() values["mean.rate"] = m.RateMean() - case Timer: + case *Timer: t := metric.Snapshot() ps := t.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999}) values["count"] = t.Count() @@ -214,7 +211,7 @@ func (r *StandardRegistry) Unregister(name string) { func (r *StandardRegistry) loadOrRegister(name string, i interface{}) (interface{}, bool, bool) { switch i.(type) { - case Counter, CounterFloat64, Gauge, GaugeFloat64, GaugeInfo, Healthcheck, Histogram, Meter, Timer, ResettingTimer: + case *Counter, *CounterFloat64, *Gauge, *GaugeFloat64, *GaugeInfo, *Healthcheck, Histogram, *Meter, *Timer, *ResettingTimer: default: return nil, false, false } @@ -326,9 +323,7 @@ func (r *PrefixedRegistry) Unregister(name string) { } var ( - DefaultRegistry = NewRegistry() - EphemeralRegistry = NewRegistry() - AccountingRegistry = NewRegistry() // registry used in swarm + DefaultRegistry = NewRegistry() ) // Each call the given function for each registered metric. @@ -347,7 +342,7 @@ func GetOrRegister(name string, i interface{}) interface{} { return DefaultRegistry.GetOrRegister(name, i) } -// Register the given metric under the given name. Returns a DuplicateMetric +// Register the given metric under the given name. Returns a ErrDuplicateMetric // if a metric by the given name is already registered. func Register(name string, i interface{}) error { return DefaultRegistry.Register(name, i) diff --git a/vendor/github.com/ethereum/go-ethereum/metrics/resetting_sample.go b/vendor/github.com/ethereum/go-ethereum/metrics/resetting_sample.go index c38ffcd3ec..730ef93416 100644 --- a/vendor/github.com/ethereum/go-ethereum/metrics/resetting_sample.go +++ b/vendor/github.com/ethereum/go-ethereum/metrics/resetting_sample.go @@ -17,7 +17,7 @@ type resettingSample struct { } // Snapshot returns a read-only copy of the sample with the original reset. -func (rs *resettingSample) Snapshot() SampleSnapshot { +func (rs *resettingSample) Snapshot() *sampleSnapshot { s := rs.Sample.Snapshot() rs.Sample.Clear() return s diff --git a/vendor/github.com/ethereum/go-ethereum/metrics/resetting_timer.go b/vendor/github.com/ethereum/go-ethereum/metrics/resetting_timer.go index 6802e3fcea..66458bdb91 100644 --- a/vendor/github.com/ethereum/go-ethereum/metrics/resetting_timer.go +++ b/vendor/github.com/ethereum/go-ethereum/metrics/resetting_timer.go @@ -5,36 +5,17 @@ import ( "time" ) -// Initial slice capacity for the values stored in a ResettingTimer -const InitialResettingTimerSliceCap = 10 - -type ResettingTimerSnapshot interface { - Count() int - Mean() float64 - Max() int64 - Min() int64 - Percentiles([]float64) []float64 -} - -// ResettingTimer is used for storing aggregated values for timers, which are reset on every flush interval. -type ResettingTimer interface { - Snapshot() ResettingTimerSnapshot - Time(func()) - Update(time.Duration) - UpdateSince(time.Time) -} - // GetOrRegisterResettingTimer returns an existing ResettingTimer or constructs and registers a -// new StandardResettingTimer. -func GetOrRegisterResettingTimer(name string, r Registry) ResettingTimer { +// new ResettingTimer. +func GetOrRegisterResettingTimer(name string, r Registry) *ResettingTimer { if nil == r { r = DefaultRegistry } - return r.GetOrRegister(name, NewResettingTimer).(ResettingTimer) + return r.GetOrRegister(name, NewResettingTimer).(*ResettingTimer) } -// NewRegisteredResettingTimer constructs and registers a new StandardResettingTimer. -func NewRegisteredResettingTimer(name string, r Registry) ResettingTimer { +// NewRegisteredResettingTimer constructs and registers a new ResettingTimer. +func NewRegisteredResettingTimer(name string, r Registry) *ResettingTimer { c := NewResettingTimer() if nil == r { r = DefaultRegistry @@ -43,33 +24,15 @@ func NewRegisteredResettingTimer(name string, r Registry) ResettingTimer { return c } -// NewResettingTimer constructs a new StandardResettingTimer -func NewResettingTimer() ResettingTimer { - if !Enabled { - return NilResettingTimer{} - } - return &StandardResettingTimer{ - values: make([]int64, 0, InitialResettingTimerSliceCap), +// NewResettingTimer constructs a new ResettingTimer +func NewResettingTimer() *ResettingTimer { + return &ResettingTimer{ + values: make([]int64, 0, 10), } } -// NilResettingTimer is a no-op ResettingTimer. -type NilResettingTimer struct{} - -func (NilResettingTimer) Values() []int64 { return nil } -func (n NilResettingTimer) Snapshot() ResettingTimerSnapshot { return n } -func (NilResettingTimer) Time(f func()) { f() } -func (NilResettingTimer) Update(time.Duration) {} -func (NilResettingTimer) Percentiles([]float64) []float64 { return nil } -func (NilResettingTimer) Mean() float64 { return 0.0 } -func (NilResettingTimer) Max() int64 { return 0 } -func (NilResettingTimer) Min() int64 { return 0 } -func (NilResettingTimer) UpdateSince(time.Time) {} -func (NilResettingTimer) Count() int { return 0 } - -// StandardResettingTimer is the standard implementation of a ResettingTimer. -// and Meter. -type StandardResettingTimer struct { +// ResettingTimer is used for storing aggregated values for timers, which are reset on every flush interval. +type ResettingTimer struct { values []int64 sum int64 // sum is a running count of the total sum, used later to calculate mean @@ -77,41 +40,44 @@ type StandardResettingTimer struct { } // Snapshot resets the timer and returns a read-only copy of its contents. -func (t *StandardResettingTimer) Snapshot() ResettingTimerSnapshot { +func (t *ResettingTimer) Snapshot() *ResettingTimerSnapshot { t.mutex.Lock() defer t.mutex.Unlock() - snapshot := &resettingTimerSnapshot{} + snapshot := &ResettingTimerSnapshot{} if len(t.values) > 0 { snapshot.mean = float64(t.sum) / float64(len(t.values)) snapshot.values = t.values - t.values = make([]int64, 0, InitialResettingTimerSliceCap) + t.values = make([]int64, 0, 10) } t.sum = 0 return snapshot } -// Record the duration of the execution of the given function. -func (t *StandardResettingTimer) Time(f func()) { +// Time records the duration of the execution of the given function. +func (t *ResettingTimer) Time(f func()) { ts := time.Now() f() t.Update(time.Since(ts)) } -// Record the duration of an event. -func (t *StandardResettingTimer) Update(d time.Duration) { +// Update records the duration of an event. +func (t *ResettingTimer) Update(d time.Duration) { + if !metricsEnabled { + return + } t.mutex.Lock() defer t.mutex.Unlock() t.values = append(t.values, int64(d)) t.sum += int64(d) } -// Record the duration of an event that started at a time and ends now. -func (t *StandardResettingTimer) UpdateSince(ts time.Time) { +// UpdateSince records the duration of an event that started at a time and ends now. +func (t *ResettingTimer) UpdateSince(ts time.Time) { t.Update(time.Since(ts)) } -// resettingTimerSnapshot is a point-in-time copy of another ResettingTimer. -type resettingTimerSnapshot struct { +// ResettingTimerSnapshot is a point-in-time copy of another ResettingTimer. +type ResettingTimerSnapshot struct { values []int64 mean float64 max int64 @@ -121,20 +87,20 @@ type resettingTimerSnapshot struct { } // Count return the length of the values from snapshot. -func (t *resettingTimerSnapshot) Count() int { +func (t *ResettingTimerSnapshot) Count() int { return len(t.values) } // Percentiles returns the boundaries for the input percentiles. // note: this method is not thread safe -func (t *resettingTimerSnapshot) Percentiles(percentiles []float64) []float64 { +func (t *ResettingTimerSnapshot) Percentiles(percentiles []float64) []float64 { t.calc(percentiles) return t.thresholdBoundaries } // Mean returns the mean of the snapshotted values // note: this method is not thread safe -func (t *resettingTimerSnapshot) Mean() float64 { +func (t *ResettingTimerSnapshot) Mean() float64 { if !t.calculated { t.calc(nil) } @@ -144,7 +110,7 @@ func (t *resettingTimerSnapshot) Mean() float64 { // Max returns the max of the snapshotted values // note: this method is not thread safe -func (t *resettingTimerSnapshot) Max() int64 { +func (t *ResettingTimerSnapshot) Max() int64 { if !t.calculated { t.calc(nil) } @@ -153,14 +119,14 @@ func (t *resettingTimerSnapshot) Max() int64 { // Min returns the min of the snapshotted values // note: this method is not thread safe -func (t *resettingTimerSnapshot) Min() int64 { +func (t *ResettingTimerSnapshot) Min() int64 { if !t.calculated { t.calc(nil) } return t.min } -func (t *resettingTimerSnapshot) calc(percentiles []float64) { +func (t *ResettingTimerSnapshot) calc(percentiles []float64) { scores := CalculatePercentiles(t.values, percentiles) t.thresholdBoundaries = scores if len(t.values) == 0 { diff --git a/vendor/github.com/ethereum/go-ethereum/metrics/sample.go b/vendor/github.com/ethereum/go-ethereum/metrics/sample.go index 17b2bee28f..dc8167809f 100644 --- a/vendor/github.com/ethereum/go-ethereum/metrics/sample.go +++ b/vendor/github.com/ethereum/go-ethereum/metrics/sample.go @@ -10,27 +10,123 @@ import ( const rescaleThreshold = time.Hour -type SampleSnapshot interface { - Count() int64 - Max() int64 - Mean() float64 - Min() int64 - Percentile(float64) float64 - Percentiles([]float64) []float64 - Size() int - StdDev() float64 - Sum() int64 - Variance() float64 -} - -// Samples maintain a statistically-significant selection of values from +// Sample maintains a statistically-significant selection of values from // a stream. type Sample interface { - Snapshot() SampleSnapshot + Snapshot() *sampleSnapshot Clear() Update(int64) } +var ( + _ Sample = (*ExpDecaySample)(nil) + _ Sample = (*UniformSample)(nil) + _ Sample = (*resettingSample)(nil) +) + +// sampleSnapshot is a read-only copy of a Sample. +type sampleSnapshot struct { + count int64 + values []int64 + + max int64 + min int64 + mean float64 + sum int64 + variance float64 +} + +// newSampleSnapshotPrecalculated creates a read-only sampleSnapShot, using +// precalculated sums to avoid iterating the values +func newSampleSnapshotPrecalculated(count int64, values []int64, min, max, sum int64) *sampleSnapshot { + if len(values) == 0 { + return &sampleSnapshot{ + count: count, + values: values, + } + } + return &sampleSnapshot{ + count: count, + values: values, + max: max, + min: min, + mean: float64(sum) / float64(len(values)), + sum: sum, + } +} + +// newSampleSnapshot creates a read-only sampleSnapShot, and calculates some +// numbers. +func newSampleSnapshot(count int64, values []int64) *sampleSnapshot { + var ( + max int64 = math.MinInt64 + min int64 = math.MaxInt64 + sum int64 + ) + for _, v := range values { + sum += v + if v > max { + max = v + } + if v < min { + min = v + } + } + return newSampleSnapshotPrecalculated(count, values, min, max, sum) +} + +// Count returns the count of inputs at the time the snapshot was taken. +func (s *sampleSnapshot) Count() int64 { return s.count } + +// Max returns the maximal value at the time the snapshot was taken. +func (s *sampleSnapshot) Max() int64 { return s.max } + +// Mean returns the mean value at the time the snapshot was taken. +func (s *sampleSnapshot) Mean() float64 { return s.mean } + +// Min returns the minimal value at the time the snapshot was taken. +func (s *sampleSnapshot) Min() int64 { return s.min } + +// Percentile returns an arbitrary percentile of values at the time the +// snapshot was taken. +func (s *sampleSnapshot) Percentile(p float64) float64 { + return SamplePercentile(s.values, p) +} + +// Percentiles returns a slice of arbitrary percentiles of values at the time +// the snapshot was taken. +func (s *sampleSnapshot) Percentiles(ps []float64) []float64 { + return CalculatePercentiles(s.values, ps) +} + +// Size returns the size of the sample at the time the snapshot was taken. +func (s *sampleSnapshot) Size() int { return len(s.values) } + +// StdDev returns the standard deviation of values at the time the snapshot was +// taken. +func (s *sampleSnapshot) StdDev() float64 { + if s.variance == 0.0 { + s.variance = SampleVariance(s.mean, s.values) + } + return math.Sqrt(s.variance) +} + +// Sum returns the sum of values at the time the snapshot was taken. +func (s *sampleSnapshot) Sum() int64 { return s.sum } + +// Values returns a copy of the values in the sample. +func (s *sampleSnapshot) Values() []int64 { + return slices.Clone(s.values) +} + +// Variance returns the variance of values at the time the snapshot was taken. +func (s *sampleSnapshot) Variance() float64 { + if s.variance == 0.0 { + s.variance = SampleVariance(s.mean, s.values) + } + return s.variance +} + // ExpDecaySample is an exponentially-decaying sample using a forward-decaying // priority reservoir. See Cormode et al's "Forward Decay: A Practical Time // Decay Model for Streaming Systems". @@ -49,9 +145,6 @@ type ExpDecaySample struct { // NewExpDecaySample constructs a new exponentially-decaying sample with the // given reservoir size and alpha. func NewExpDecaySample(reservoirSize int, alpha float64) Sample { - if !Enabled { - return NilSample{} - } s := &ExpDecaySample{ alpha: alpha, reservoirSize: reservoirSize, @@ -79,7 +172,7 @@ func (s *ExpDecaySample) Clear() { } // Snapshot returns a read-only copy of the sample. -func (s *ExpDecaySample) Snapshot() SampleSnapshot { +func (s *ExpDecaySample) Snapshot() *sampleSnapshot { s.mutex.Lock() defer s.mutex.Unlock() var ( @@ -105,6 +198,9 @@ func (s *ExpDecaySample) Snapshot() SampleSnapshot { // Update samples a new value. func (s *ExpDecaySample) Update(v int64) { + if !metricsEnabled { + return + } s.update(time.Now(), v) } @@ -140,13 +236,6 @@ func (s *ExpDecaySample) update(t time.Time, v int64) { } } -// NilSample is a no-op Sample. -type NilSample struct{} - -func (NilSample) Clear() {} -func (NilSample) Snapshot() SampleSnapshot { return (*emptySnapshot)(nil) } -func (NilSample) Update(v int64) {} - // SamplePercentile returns an arbitrary percentile of the slice of int64. func SamplePercentile(values []int64, p float64) float64 { return CalculatePercentiles(values, []float64{p})[0] @@ -181,114 +270,6 @@ func CalculatePercentiles(values []int64, ps []float64) []float64 { return scores } -// sampleSnapshot is a read-only copy of another Sample. -type sampleSnapshot struct { - count int64 - values []int64 - - max int64 - min int64 - mean float64 - sum int64 - variance float64 -} - -// newSampleSnapshotPrecalculated creates a read-only sampleSnapShot, using -// precalculated sums to avoid iterating the values -func newSampleSnapshotPrecalculated(count int64, values []int64, min, max, sum int64) *sampleSnapshot { - if len(values) == 0 { - return &sampleSnapshot{ - count: count, - values: values, - } - } - return &sampleSnapshot{ - count: count, - values: values, - max: max, - min: min, - mean: float64(sum) / float64(len(values)), - sum: sum, - } -} - -// newSampleSnapshot creates a read-only sampleSnapShot, and calculates some -// numbers. -func newSampleSnapshot(count int64, values []int64) *sampleSnapshot { - var ( - max int64 = math.MinInt64 - min int64 = math.MaxInt64 - sum int64 - ) - for _, v := range values { - sum += v - if v > max { - max = v - } - if v < min { - min = v - } - } - return newSampleSnapshotPrecalculated(count, values, min, max, sum) -} - -// Count returns the count of inputs at the time the snapshot was taken. -func (s *sampleSnapshot) Count() int64 { return s.count } - -// Max returns the maximal value at the time the snapshot was taken. -func (s *sampleSnapshot) Max() int64 { return s.max } - -// Mean returns the mean value at the time the snapshot was taken. -func (s *sampleSnapshot) Mean() float64 { return s.mean } - -// Min returns the minimal value at the time the snapshot was taken. -func (s *sampleSnapshot) Min() int64 { return s.min } - -// Percentile returns an arbitrary percentile of values at the time the -// snapshot was taken. -func (s *sampleSnapshot) Percentile(p float64) float64 { - return SamplePercentile(s.values, p) -} - -// Percentiles returns a slice of arbitrary percentiles of values at the time -// the snapshot was taken. -func (s *sampleSnapshot) Percentiles(ps []float64) []float64 { - return CalculatePercentiles(s.values, ps) -} - -// Size returns the size of the sample at the time the snapshot was taken. -func (s *sampleSnapshot) Size() int { return len(s.values) } - -// Snapshot returns the snapshot. -func (s *sampleSnapshot) Snapshot() SampleSnapshot { return s } - -// StdDev returns the standard deviation of values at the time the snapshot was -// taken. -func (s *sampleSnapshot) StdDev() float64 { - if s.variance == 0.0 { - s.variance = SampleVariance(s.mean, s.values) - } - return math.Sqrt(s.variance) -} - -// Sum returns the sum of values at the time the snapshot was taken. -func (s *sampleSnapshot) Sum() int64 { return s.sum } - -// Values returns a copy of the values in the sample. -func (s *sampleSnapshot) Values() []int64 { - values := make([]int64, len(s.values)) - copy(values, s.values) - return values -} - -// Variance returns the variance of values at the time the snapshot was taken. -func (s *sampleSnapshot) Variance() float64 { - if s.variance == 0.0 { - s.variance = SampleVariance(s.mean, s.values) - } - return s.variance -} - // SampleVariance returns the variance of the slice of int64. func SampleVariance(mean float64, values []int64) float64 { if len(values) == 0 { @@ -302,7 +283,7 @@ func SampleVariance(mean float64, values []int64) float64 { return sum / float64(len(values)) } -// A uniform sample using Vitter's Algorithm R. +// UniformSample implements a uniform sample using Vitter's Algorithm R. // // type UniformSample struct { @@ -316,9 +297,6 @@ type UniformSample struct { // NewUniformSample constructs a new uniform sample with the given reservoir // size. func NewUniformSample(reservoirSize int) Sample { - if !Enabled { - return NilSample{} - } return &UniformSample{ reservoirSize: reservoirSize, values: make([]int64, 0, reservoirSize), @@ -336,14 +314,13 @@ func (s *UniformSample) Clear() { s.mutex.Lock() defer s.mutex.Unlock() s.count = 0 - s.values = make([]int64, 0, s.reservoirSize) + clear(s.values) } // Snapshot returns a read-only copy of the sample. -func (s *UniformSample) Snapshot() SampleSnapshot { +func (s *UniformSample) Snapshot() *sampleSnapshot { s.mutex.Lock() - values := make([]int64, len(s.values)) - copy(values, s.values) + values := slices.Clone(s.values) count := s.count s.mutex.Unlock() return newSampleSnapshot(count, values) @@ -351,21 +328,24 @@ func (s *UniformSample) Snapshot() SampleSnapshot { // Update samples a new value. func (s *UniformSample) Update(v int64) { + if !metricsEnabled { + return + } s.mutex.Lock() defer s.mutex.Unlock() s.count++ if len(s.values) < s.reservoirSize { s.values = append(s.values, v) + return + } + var r int64 + if s.rand != nil { + r = s.rand.Int63n(s.count) } else { - var r int64 - if s.rand != nil { - r = s.rand.Int63n(s.count) - } else { - r = rand.Int63n(s.count) - } - if r < int64(len(s.values)) { - s.values[int(r)] = v - } + r = rand.Int63n(s.count) + } + if r < int64(len(s.values)) { + s.values[int(r)] = v } } diff --git a/vendor/github.com/ethereum/go-ethereum/metrics/syslog.go b/vendor/github.com/ethereum/go-ethereum/metrics/syslog.go index fd856d6973..b265328f87 100644 --- a/vendor/github.com/ethereum/go-ethereum/metrics/syslog.go +++ b/vendor/github.com/ethereum/go-ethereum/metrics/syslog.go @@ -9,23 +9,23 @@ import ( "time" ) -// Output each metric in the given registry to syslog periodically using +// Syslog outputs each metric in the given registry to syslog periodically using // the given syslogger. func Syslog(r Registry, d time.Duration, w *syslog.Writer) { for range time.Tick(d) { r.Each(func(name string, i interface{}) { switch metric := i.(type) { - case Counter: + case *Counter: w.Info(fmt.Sprintf("counter %s: count: %d", name, metric.Snapshot().Count())) - case CounterFloat64: + case *CounterFloat64: w.Info(fmt.Sprintf("counter %s: count: %f", name, metric.Snapshot().Count())) - case Gauge: + case *Gauge: w.Info(fmt.Sprintf("gauge %s: value: %d", name, metric.Snapshot().Value())) - case GaugeFloat64: + case *GaugeFloat64: w.Info(fmt.Sprintf("gauge %s: value: %f", name, metric.Snapshot().Value())) - case GaugeInfo: + case *GaugeInfo: w.Info(fmt.Sprintf("gauge %s: value: %s", name, metric.Snapshot().Value())) - case Healthcheck: + case *Healthcheck: metric.Check() w.Info(fmt.Sprintf("healthcheck %s: error: %v", name, metric.Error())) case Histogram: @@ -45,7 +45,7 @@ func Syslog(r Registry, d time.Duration, w *syslog.Writer) { ps[3], ps[4], )) - case Meter: + case *Meter: m := metric.Snapshot() w.Info(fmt.Sprintf( "meter %s: count: %d 1-min: %.2f 5-min: %.2f 15-min: %.2f mean: %.2f", @@ -56,7 +56,7 @@ func Syslog(r Registry, d time.Duration, w *syslog.Writer) { m.Rate15(), m.RateMean(), )) - case Timer: + case *Timer: t := metric.Snapshot() ps := t.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999}) w.Info(fmt.Sprintf( diff --git a/vendor/github.com/ethereum/go-ethereum/metrics/timer.go b/vendor/github.com/ethereum/go-ethereum/metrics/timer.go index fc2a88f508..9df15c967a 100644 --- a/vendor/github.com/ethereum/go-ethereum/metrics/timer.go +++ b/vendor/github.com/ethereum/go-ethereum/metrics/timer.go @@ -5,47 +5,30 @@ import ( "time" ) -type TimerSnapshot interface { - HistogramSnapshot - MeterSnapshot -} - -// Timer capture the duration and rate of events. -type Timer interface { - Snapshot() TimerSnapshot - Stop() - Time(func()) - UpdateSince(time.Time) - Update(time.Duration) -} - // GetOrRegisterTimer returns an existing Timer or constructs and registers a -// new StandardTimer. +// new Timer. // Be sure to unregister the meter from the registry once it is of no use to // allow for garbage collection. -func GetOrRegisterTimer(name string, r Registry) Timer { +func GetOrRegisterTimer(name string, r Registry) *Timer { if nil == r { r = DefaultRegistry } - return r.GetOrRegister(name, NewTimer).(Timer) + return r.GetOrRegister(name, NewTimer).(*Timer) } -// NewCustomTimer constructs a new StandardTimer from a Histogram and a Meter. +// NewCustomTimer constructs a new Timer from a Histogram and a Meter. // Be sure to call Stop() once the timer is of no use to allow for garbage collection. -func NewCustomTimer(h Histogram, m Meter) Timer { - if !Enabled { - return NilTimer{} - } - return &StandardTimer{ +func NewCustomTimer(h Histogram, m *Meter) *Timer { + return &Timer{ histogram: h, meter: m, } } -// NewRegisteredTimer constructs and registers a new StandardTimer. +// NewRegisteredTimer constructs and registers a new Timer. // Be sure to unregister the meter from the registry once it is of no use to // allow for garbage collection. -func NewRegisteredTimer(name string, r Registry) Timer { +func NewRegisteredTimer(name string, r Registry) *Timer { c := NewTimer() if nil == r { r = DefaultRegistry @@ -54,60 +37,47 @@ func NewRegisteredTimer(name string, r Registry) Timer { return c } -// NewTimer constructs a new StandardTimer using an exponentially-decaying +// NewTimer constructs a new Timer using an exponentially-decaying // sample with the same reservoir size and alpha as UNIX load averages. // Be sure to call Stop() once the timer is of no use to allow for garbage collection. -func NewTimer() Timer { - if !Enabled { - return NilTimer{} - } - return &StandardTimer{ +func NewTimer() *Timer { + return &Timer{ histogram: NewHistogram(NewExpDecaySample(1028, 0.015)), meter: NewMeter(), } } -// NilTimer is a no-op Timer. -type NilTimer struct{} - -func (NilTimer) Snapshot() TimerSnapshot { return (*emptySnapshot)(nil) } -func (NilTimer) Stop() {} -func (NilTimer) Time(f func()) { f() } -func (NilTimer) Update(time.Duration) {} -func (NilTimer) UpdateSince(time.Time) {} - -// StandardTimer is the standard implementation of a Timer and uses a Histogram -// and Meter. -type StandardTimer struct { +// Timer captures the duration and rate of events, using a Histogram and a Meter. +type Timer struct { histogram Histogram - meter Meter + meter *Meter mutex sync.Mutex } // Snapshot returns a read-only copy of the timer. -func (t *StandardTimer) Snapshot() TimerSnapshot { +func (t *Timer) Snapshot() *TimerSnapshot { t.mutex.Lock() defer t.mutex.Unlock() - return &timerSnapshot{ + return &TimerSnapshot{ histogram: t.histogram.Snapshot(), meter: t.meter.Snapshot(), } } // Stop stops the meter. -func (t *StandardTimer) Stop() { +func (t *Timer) Stop() { t.meter.Stop() } // Time record the duration of the execution of the given function. -func (t *StandardTimer) Time(f func()) { +func (t *Timer) Time(f func()) { ts := time.Now() f() t.Update(time.Since(ts)) } // Update the duration of an event, in nanoseconds. -func (t *StandardTimer) Update(d time.Duration) { +func (t *Timer) Update(d time.Duration) { t.mutex.Lock() defer t.mutex.Unlock() t.histogram.Update(d.Nanoseconds()) @@ -116,67 +86,67 @@ func (t *StandardTimer) Update(d time.Duration) { // UpdateSince update the duration of an event that started at a time and ends now. // The record uses nanoseconds. -func (t *StandardTimer) UpdateSince(ts time.Time) { +func (t *Timer) UpdateSince(ts time.Time) { t.Update(time.Since(ts)) } -// timerSnapshot is a read-only copy of another Timer. -type timerSnapshot struct { +// TimerSnapshot is a read-only copy of another Timer. +type TimerSnapshot struct { histogram HistogramSnapshot - meter MeterSnapshot + meter *MeterSnapshot } // Count returns the number of events recorded at the time the snapshot was // taken. -func (t *timerSnapshot) Count() int64 { return t.histogram.Count() } +func (t *TimerSnapshot) Count() int64 { return t.histogram.Count() } // Max returns the maximum value at the time the snapshot was taken. -func (t *timerSnapshot) Max() int64 { return t.histogram.Max() } +func (t *TimerSnapshot) Max() int64 { return t.histogram.Max() } // Size returns the size of the sample at the time the snapshot was taken. -func (t *timerSnapshot) Size() int { return t.histogram.Size() } +func (t *TimerSnapshot) Size() int { return t.histogram.Size() } // Mean returns the mean value at the time the snapshot was taken. -func (t *timerSnapshot) Mean() float64 { return t.histogram.Mean() } +func (t *TimerSnapshot) Mean() float64 { return t.histogram.Mean() } // Min returns the minimum value at the time the snapshot was taken. -func (t *timerSnapshot) Min() int64 { return t.histogram.Min() } +func (t *TimerSnapshot) Min() int64 { return t.histogram.Min() } // Percentile returns an arbitrary percentile of sampled values at the time the // snapshot was taken. -func (t *timerSnapshot) Percentile(p float64) float64 { +func (t *TimerSnapshot) Percentile(p float64) float64 { return t.histogram.Percentile(p) } // Percentiles returns a slice of arbitrary percentiles of sampled values at // the time the snapshot was taken. -func (t *timerSnapshot) Percentiles(ps []float64) []float64 { +func (t *TimerSnapshot) Percentiles(ps []float64) []float64 { return t.histogram.Percentiles(ps) } // Rate1 returns the one-minute moving average rate of events per second at the // time the snapshot was taken. -func (t *timerSnapshot) Rate1() float64 { return t.meter.Rate1() } +func (t *TimerSnapshot) Rate1() float64 { return t.meter.Rate1() } // Rate5 returns the five-minute moving average rate of events per second at // the time the snapshot was taken. -func (t *timerSnapshot) Rate5() float64 { return t.meter.Rate5() } +func (t *TimerSnapshot) Rate5() float64 { return t.meter.Rate5() } // Rate15 returns the fifteen-minute moving average rate of events per second // at the time the snapshot was taken. -func (t *timerSnapshot) Rate15() float64 { return t.meter.Rate15() } +func (t *TimerSnapshot) Rate15() float64 { return t.meter.Rate15() } // RateMean returns the meter's mean rate of events per second at the time the // snapshot was taken. -func (t *timerSnapshot) RateMean() float64 { return t.meter.RateMean() } +func (t *TimerSnapshot) RateMean() float64 { return t.meter.RateMean() } // StdDev returns the standard deviation of the values at the time the snapshot // was taken. -func (t *timerSnapshot) StdDev() float64 { return t.histogram.StdDev() } +func (t *TimerSnapshot) StdDev() float64 { return t.histogram.StdDev() } // Sum returns the sum at the time the snapshot was taken. -func (t *timerSnapshot) Sum() int64 { return t.histogram.Sum() } +func (t *TimerSnapshot) Sum() int64 { return t.histogram.Sum() } // Variance returns the variance of the values at the time the snapshot was // taken. -func (t *timerSnapshot) Variance() float64 { return t.histogram.Variance() } +func (t *TimerSnapshot) Variance() float64 { return t.histogram.Variance() } diff --git a/vendor/github.com/ethereum/go-ethereum/metrics/writer.go b/vendor/github.com/ethereum/go-ethereum/metrics/writer.go index c211c5046b..2a41f8e1fe 100644 --- a/vendor/github.com/ethereum/go-ethereum/metrics/writer.go +++ b/vendor/github.com/ethereum/go-ethereum/metrics/writer.go @@ -26,22 +26,22 @@ func WriteOnce(r Registry, w io.Writer) { slices.SortFunc(namedMetrics, namedMetric.cmp) for _, namedMetric := range namedMetrics { switch metric := namedMetric.m.(type) { - case Counter: + case *Counter: fmt.Fprintf(w, "counter %s\n", namedMetric.name) fmt.Fprintf(w, " count: %9d\n", metric.Snapshot().Count()) - case CounterFloat64: + case *CounterFloat64: fmt.Fprintf(w, "counter %s\n", namedMetric.name) fmt.Fprintf(w, " count: %f\n", metric.Snapshot().Count()) - case Gauge: + case *Gauge: fmt.Fprintf(w, "gauge %s\n", namedMetric.name) fmt.Fprintf(w, " value: %9d\n", metric.Snapshot().Value()) - case GaugeFloat64: + case *GaugeFloat64: fmt.Fprintf(w, "gauge %s\n", namedMetric.name) fmt.Fprintf(w, " value: %f\n", metric.Snapshot().Value()) - case GaugeInfo: + case *GaugeInfo: fmt.Fprintf(w, "gauge %s\n", namedMetric.name) fmt.Fprintf(w, " value: %s\n", metric.Snapshot().Value().String()) - case Healthcheck: + case *Healthcheck: metric.Check() fmt.Fprintf(w, "healthcheck %s\n", namedMetric.name) fmt.Fprintf(w, " error: %v\n", metric.Error()) @@ -59,7 +59,7 @@ func WriteOnce(r Registry, w io.Writer) { fmt.Fprintf(w, " 95%%: %12.2f\n", ps[2]) fmt.Fprintf(w, " 99%%: %12.2f\n", ps[3]) fmt.Fprintf(w, " 99.9%%: %12.2f\n", ps[4]) - case Meter: + case *Meter: m := metric.Snapshot() fmt.Fprintf(w, "meter %s\n", namedMetric.name) fmt.Fprintf(w, " count: %9d\n", m.Count()) @@ -67,7 +67,7 @@ func WriteOnce(r Registry, w io.Writer) { fmt.Fprintf(w, " 5-min rate: %12.2f\n", m.Rate5()) fmt.Fprintf(w, " 15-min rate: %12.2f\n", m.Rate15()) fmt.Fprintf(w, " mean rate: %12.2f\n", m.RateMean()) - case Timer: + case *Timer: t := metric.Snapshot() ps := t.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999}) fmt.Fprintf(w, "timer %s\n", namedMetric.name) diff --git a/vendor/github.com/ethereum/go-ethereum/oss-fuzz.sh b/vendor/github.com/ethereum/go-ethereum/oss-fuzz.sh index 5e4aa1c253..4db245a781 100644 --- a/vendor/github.com/ethereum/go-ethereum/oss-fuzz.sh +++ b/vendor/github.com/ethereum/go-ethereum/oss-fuzz.sh @@ -160,14 +160,6 @@ compile_fuzzer github.com/ethereum/go-ethereum/tests/fuzzers/bls12381 \ FuzzG1Add fuzz_g1_add\ $repo/tests/fuzzers/bls12381/bls12381_test.go -compile_fuzzer github.com/ethereum/go-ethereum/tests/fuzzers/bls12381 \ - FuzzCrossG1Mul fuzz_cross_g1_mul\ - $repo/tests/fuzzers/bls12381/bls12381_test.go - -compile_fuzzer github.com/ethereum/go-ethereum/tests/fuzzers/bls12381 \ - FuzzG1Mul fuzz_g1_mul\ - $repo/tests/fuzzers/bls12381/bls12381_test.go - compile_fuzzer github.com/ethereum/go-ethereum/tests/fuzzers/bls12381 \ FuzzG1MultiExp fuzz_g1_multiexp \ $repo/tests/fuzzers/bls12381/bls12381_test.go @@ -176,14 +168,6 @@ compile_fuzzer github.com/ethereum/go-ethereum/tests/fuzzers/bls12381 \ FuzzG2Add fuzz_g2_add \ $repo/tests/fuzzers/bls12381/bls12381_test.go -compile_fuzzer github.com/ethereum/go-ethereum/tests/fuzzers/bls12381 \ - FuzzCrossG2Mul fuzz_cross_g2_mul\ - $repo/tests/fuzzers/bls12381/bls12381_test.go - -compile_fuzzer github.com/ethereum/go-ethereum/tests/fuzzers/bls12381 \ - FuzzG2Mul fuzz_g2_mul\ - $repo/tests/fuzzers/bls12381/bls12381_test.go - compile_fuzzer github.com/ethereum/go-ethereum/tests/fuzzers/bls12381 \ FuzzG2MultiExp fuzz_g2_multiexp \ $repo/tests/fuzzers/bls12381/bls12381_test.go @@ -234,10 +218,6 @@ compile_fuzzer github.com/ethereum/go-ethereum/tests/fuzzers/secp256k1 \ compile_fuzzer github.com/ethereum/go-ethereum/eth/protocols/eth \ FuzzEthProtocolHandlers fuzz_eth_protocol_handlers \ - $repo/eth/protocols/eth/handler_test.go - + $repo/eth/protocols/eth/handler_test.go,$repo/eth/protocols/eth/peer_test.go -#compile_fuzzer tests/fuzzers/vflux FuzzClientPool fuzzClientPool -#compile_fuzzer tests/fuzzers/difficulty Fuzz fuzzDifficulty -#compile_fuzzer tests/fuzzers/les Fuzz fuzzLes diff --git a/vendor/github.com/ethereum/go-ethereum/p2p/netutil/net.go b/vendor/github.com/ethereum/go-ethereum/p2p/netutil/net.go index 7d8da88670..696c331859 100644 --- a/vendor/github.com/ethereum/go-ethereum/p2p/netutil/net.go +++ b/vendor/github.com/ethereum/go-ethereum/p2p/netutil/net.go @@ -21,12 +21,11 @@ import ( "bytes" "errors" "fmt" + "maps" "net" "net/netip" "slices" "strings" - - "golang.org/x/exp/maps" ) var special4, special6 Netlist @@ -324,8 +323,7 @@ func (s *DistinctNetSet) key(ip netip.Addr) netip.Prefix { // String implements fmt.Stringer func (s DistinctNetSet) String() string { - keys := maps.Keys(s.members) - slices.SortFunc(keys, func(a, b netip.Prefix) int { + keys := slices.SortedFunc(maps.Keys(s.members), func(a, b netip.Prefix) int { return strings.Compare(a.String(), b.String()) }) diff --git a/vendor/github.com/ethereum/go-ethereum/params/config.go b/vendor/github.com/ethereum/go-ethereum/params/config.go index 9b3b92484a..593c70b139 100644 --- a/vendor/github.com/ethereum/go-ethereum/params/config.go +++ b/vendor/github.com/ethereum/go-ethereum/params/config.go @@ -17,6 +17,7 @@ package params import ( + "errors" "fmt" "math" "math/big" @@ -60,6 +61,9 @@ var ( CancunTime: newUint64(1710338135), DepositContractAddress: common.HexToAddress("0x00000000219ab540356cbb839cbe05303d7705fa"), Ethash: new(EthashConfig), + BlobScheduleConfig: &BlobScheduleConfig{ + Cancun: DefaultCancunBlobConfig, + }, } // HoleskyChainConfig contains the chain parameters to run a node on the Holesky test network. HoleskyChainConfig = &ChainConfig{ @@ -83,7 +87,13 @@ var ( MergeNetsplitBlock: nil, ShanghaiTime: newUint64(1696000704), CancunTime: newUint64(1707305664), + PragueTime: newUint64(1740434112), + DepositContractAddress: common.HexToAddress("0x4242424242424242424242424242424242424242"), Ethash: new(EthashConfig), + BlobScheduleConfig: &BlobScheduleConfig{ + Cancun: DefaultCancunBlobConfig, + Prague: DefaultPragueBlobConfig, + }, } // SepoliaChainConfig contains the chain parameters to run a node on the Sepolia test network. SepoliaChainConfig = &ChainConfig{ @@ -107,7 +117,13 @@ var ( MergeNetsplitBlock: big.NewInt(1735371), ShanghaiTime: newUint64(1677557088), CancunTime: newUint64(1706655072), + PragueTime: newUint64(1741159776), + DepositContractAddress: common.HexToAddress("0x7f02c3e3c98b133055b8b348b2ac625669ed295d"), Ethash: new(EthashConfig), + BlobScheduleConfig: &BlobScheduleConfig{ + Cancun: DefaultCancunBlobConfig, + Prague: DefaultPragueBlobConfig, + }, } // AllEthashProtocolChanges contains every protocol change (EIPs) introduced // and accepted by the Ethereum core developers into the Ethash consensus. @@ -133,6 +149,7 @@ var ( ShanghaiTime: nil, CancunTime: nil, PragueTime: nil, + OsakaTime: nil, VerkleTime: nil, Ethash: new(EthashConfig), Clique: nil, @@ -157,6 +174,10 @@ var ( CancunTime: newUint64(0), TerminalTotalDifficulty: big.NewInt(0), PragueTime: newUint64(0), + BlobScheduleConfig: &BlobScheduleConfig{ + Cancun: DefaultCancunBlobConfig, + Prague: DefaultPragueBlobConfig, + }, } // AllCliqueProtocolChanges contains every protocol change (EIPs) introduced @@ -182,6 +203,7 @@ var ( ShanghaiTime: nil, CancunTime: nil, PragueTime: nil, + OsakaTime: nil, VerkleTime: nil, TerminalTotalDifficulty: big.NewInt(math.MaxInt64), Ethash: nil, @@ -211,6 +233,7 @@ var ( ShanghaiTime: nil, CancunTime: nil, PragueTime: nil, + OsakaTime: nil, VerkleTime: nil, TerminalTotalDifficulty: big.NewInt(math.MaxInt64), Ethash: new(EthashConfig), @@ -240,10 +263,15 @@ var ( ShanghaiTime: newUint64(0), CancunTime: newUint64(0), PragueTime: newUint64(0), + OsakaTime: nil, VerkleTime: nil, TerminalTotalDifficulty: big.NewInt(0), Ethash: new(EthashConfig), Clique: nil, + BlobScheduleConfig: &BlobScheduleConfig{ + Cancun: DefaultCancunBlobConfig, + Prague: DefaultPragueBlobConfig, + }, } // NonActivatedConfig defines the chain configuration without activating @@ -269,6 +297,7 @@ var ( ShanghaiTime: nil, CancunTime: nil, PragueTime: nil, + OsakaTime: nil, VerkleTime: nil, TerminalTotalDifficulty: big.NewInt(math.MaxInt64), Ethash: new(EthashConfig), @@ -277,6 +306,33 @@ var ( TestRules = TestChainConfig.Rules(new(big.Int), false, 0) ) +var ( + // DefaultCancunBlobConfig is the default blob configuration for the Cancun fork. + DefaultCancunBlobConfig = &BlobConfig{ + Target: 3, + Max: 6, + UpdateFraction: 3338477, + } + // DefaultPragueBlobConfig is the default blob configuration for the Prague fork. + DefaultPragueBlobConfig = &BlobConfig{ + Target: 6, + Max: 9, + UpdateFraction: 5007716, + } + // DefaultOsakaBlobConfig is the default blob configuration for the Osaka fork. + DefaultOsakaBlobConfig = &BlobConfig{ + Target: 6, + Max: 9, + UpdateFraction: 5007716, + } + // DefaultBlobSchedule is the latest configured blob schedule for test chains. + DefaultBlobSchedule = &BlobScheduleConfig{ + Cancun: DefaultCancunBlobConfig, + Prague: DefaultPragueBlobConfig, + Osaka: DefaultOsakaBlobConfig, + } +) + // NetworkNames are user friendly names to use in the chain spec banner. var NetworkNames = map[string]string{ MainnetChainConfig.ChainID.String(): "mainnet", @@ -318,6 +374,7 @@ type ChainConfig struct { ShanghaiTime *uint64 `json:"shanghaiTime,omitempty"` // Shanghai switch time (nil = no fork, 0 = already on shanghai) CancunTime *uint64 `json:"cancunTime,omitempty"` // Cancun switch time (nil = no fork, 0 = already on cancun) PragueTime *uint64 `json:"pragueTime,omitempty"` // Prague switch time (nil = no fork, 0 = already on prague) + OsakaTime *uint64 `json:"osakaTime,omitempty"` // Osaka switch time (nil = no fork, 0 = already on osaka) VerkleTime *uint64 `json:"verkleTime,omitempty"` // Verkle switch time (nil = no fork, 0 = already on verkle) // TerminalTotalDifficulty is the amount of total difficulty reached by @@ -326,9 +383,23 @@ type ChainConfig struct { DepositContractAddress common.Address `json:"depositContractAddress,omitempty"` + // EnableVerkleAtGenesis is a flag that specifies whether the network uses + // the Verkle tree starting from the genesis block. If set to true, the + // genesis state will be committed using the Verkle tree, eliminating the + // need for any Verkle transition later. + // + // This is a temporary flag only for verkle devnet testing, where verkle is + // activated at genesis, and the configured activation date has already passed. + // + // In production networks (mainnet and public testnets), verkle activation + // always occurs after the genesis block, making this flag irrelevant in + // those cases. + EnableVerkleAtGenesis bool `json:"enableVerkleAtGenesis,omitempty"` + // Various consensus engines - Ethash *EthashConfig `json:"ethash,omitempty"` - Clique *CliqueConfig `json:"clique,omitempty"` + Ethash *EthashConfig `json:"ethash,omitempty"` + Clique *CliqueConfig `json:"clique,omitempty"` + BlobScheduleConfig *BlobScheduleConfig `json:"blobSchedule,omitempty"` } // EthashConfig is the consensus engine configs for proof-of-work based sealing. @@ -419,12 +490,30 @@ func (c *ChainConfig) Description() string { if c.PragueTime != nil { banner += fmt.Sprintf(" - Prague: @%-10v\n", *c.PragueTime) } + if c.OsakaTime != nil { + banner += fmt.Sprintf(" - Osaka: @%-10v\n", *c.OsakaTime) + } if c.VerkleTime != nil { banner += fmt.Sprintf(" - Verkle: @%-10v\n", *c.VerkleTime) } return banner } +// BlobConfig specifies the target and max blobs per block for the associated fork. +type BlobConfig struct { + Target int `json:"target"` + Max int `json:"max"` + UpdateFraction uint64 `json:"baseFeeUpdateFraction"` +} + +// BlobScheduleConfig determines target and max number of blobs allow per fork. +type BlobScheduleConfig struct { + Cancun *BlobConfig `json:"cancun,omitempty"` + Prague *BlobConfig `json:"prague,omitempty"` + Osaka *BlobConfig `json:"osaka,omitempty"` + Verkle *BlobConfig `json:"verkle,omitempty"` +} + // IsHomestead returns whether num is either equal to the homestead block or greater. func (c *ChainConfig) IsHomestead(num *big.Int) bool { return isBlockForked(c.HomesteadBlock, num) @@ -520,11 +609,30 @@ func (c *ChainConfig) IsPrague(num *big.Int, time uint64) bool { return c.IsLondon(num) && isTimestampForked(c.PragueTime, time) } +// IsOsaka returns whether time is either equal to the Osaka fork time or greater. +func (c *ChainConfig) IsOsaka(num *big.Int, time uint64) bool { + return c.IsLondon(num) && isTimestampForked(c.OsakaTime, time) +} + // IsVerkle returns whether time is either equal to the Verkle fork time or greater. func (c *ChainConfig) IsVerkle(num *big.Int, time uint64) bool { return c.IsLondon(num) && isTimestampForked(c.VerkleTime, time) } +// IsVerkleGenesis checks whether the verkle fork is activated at the genesis block. +// +// Verkle mode is considered enabled if the verkle fork time is configured, +// regardless of whether the local time has surpassed the fork activation time. +// This is a temporary workaround for verkle devnet testing, where verkle is +// activated at genesis, and the configured activation date has already passed. +// +// In production networks (mainnet and public testnets), verkle activation +// always occurs after the genesis block, making this function irrelevant in +// those cases. +func (c *ChainConfig) IsVerkleGenesis() bool { + return c.EnableVerkleAtGenesis +} + // IsEIP4762 returns whether eip 4762 has been activated at given block. func (c *ChainConfig) IsEIP4762(num *big.Int, time uint64) bool { return c.IsVerkle(num, time) @@ -584,6 +692,7 @@ func (c *ChainConfig) CheckConfigForkOrder() error { {name: "shanghaiTime", timestamp: c.ShanghaiTime}, {name: "cancunTime", timestamp: c.CancunTime, optional: true}, {name: "pragueTime", timestamp: c.PragueTime, optional: true}, + {name: "osakaTime", timestamp: c.OsakaTime, optional: true}, {name: "verkleTime", timestamp: c.VerkleTime, optional: true}, } { if lastFork.name != "" { @@ -620,6 +729,46 @@ func (c *ChainConfig) CheckConfigForkOrder() error { lastFork = cur } } + + // Check that all forks with blobs explicitly define the blob schedule configuration. + bsc := c.BlobScheduleConfig + if bsc == nil { + bsc = new(BlobScheduleConfig) + } + for _, cur := range []struct { + name string + timestamp *uint64 + config *BlobConfig + }{ + {name: "cancun", timestamp: c.CancunTime, config: bsc.Cancun}, + {name: "prague", timestamp: c.PragueTime, config: bsc.Prague}, + {name: "osaka", timestamp: c.OsakaTime, config: bsc.Osaka}, + } { + if cur.config != nil { + if err := cur.config.validate(); err != nil { + return fmt.Errorf("invalid chain configuration in blobSchedule for fork %q: %v", cur.name, err) + } + } + if cur.timestamp != nil { + // If the fork is configured, a blob schedule must be defined for it. + if cur.config == nil { + return fmt.Errorf("invalid chain configuration: missing entry for fork %q in blobSchedule", cur.name) + } + } + } + return nil +} + +func (bc *BlobConfig) validate() error { + if bc.Max < 0 { + return errors.New("max < 0") + } + if bc.Target < 0 { + return errors.New("target < 0") + } + if bc.UpdateFraction == 0 { + return errors.New("update fraction must be defined and non-zero") + } return nil } @@ -688,6 +837,9 @@ func (c *ChainConfig) checkCompatible(newcfg *ChainConfig, headNumber *big.Int, if isForkTimestampIncompatible(c.PragueTime, newcfg.PragueTime, headTimestamp) { return newTimestampCompatError("Prague fork timestamp", c.PragueTime, newcfg.PragueTime) } + if isForkTimestampIncompatible(c.OsakaTime, newcfg.OsakaTime, headTimestamp) { + return newTimestampCompatError("Osaka fork timestamp", c.OsakaTime, newcfg.OsakaTime) + } if isForkTimestampIncompatible(c.VerkleTime, newcfg.VerkleTime, headTimestamp) { return newTimestampCompatError("Verkle fork timestamp", c.VerkleTime, newcfg.VerkleTime) } @@ -710,6 +862,8 @@ func (c *ChainConfig) LatestFork(time uint64) forks.Fork { london := c.LondonBlock switch { + case c.IsOsaka(london, time): + return forks.Osaka case c.IsPrague(london, time): return forks.Prague case c.IsCancun(london, time): @@ -861,7 +1015,7 @@ type Rules struct { IsEIP2929, IsEIP4762 bool IsByzantium, IsConstantinople, IsPetersburg, IsIstanbul bool IsBerlin, IsLondon bool - IsMerge, IsShanghai, IsCancun, IsPrague bool + IsMerge, IsShanghai, IsCancun, IsPrague, IsOsaka bool IsVerkle bool } @@ -891,6 +1045,7 @@ func (c *ChainConfig) Rules(num *big.Int, isMerge bool, timestamp uint64) Rules IsShanghai: isMerge && c.IsShanghai(num, timestamp), IsCancun: isMerge && c.IsCancun(num, timestamp), IsPrague: isMerge && c.IsPrague(num, timestamp), + IsOsaka: isMerge && c.IsOsaka(num, timestamp), IsVerkle: isVerkle, IsEIP4762: isVerkle, } diff --git a/vendor/github.com/ethereum/go-ethereum/params/forks/forks.go b/vendor/github.com/ethereum/go-ethereum/params/forks/forks.go index 4f50ff5aed..2d44e13b04 100644 --- a/vendor/github.com/ethereum/go-ethereum/params/forks/forks.go +++ b/vendor/github.com/ethereum/go-ethereum/params/forks/forks.go @@ -39,4 +39,5 @@ const ( Shanghai Cancun Prague + Osaka ) diff --git a/vendor/github.com/ethereum/go-ethereum/params/protocol_params.go b/vendor/github.com/ethereum/go-ethereum/params/protocol_params.go index 90e7487cff..6b06dadaef 100644 --- a/vendor/github.com/ethereum/go-ethereum/params/protocol_params.go +++ b/vendor/github.com/ethereum/go-ethereum/params/protocol_params.go @@ -90,10 +90,13 @@ const ( SelfdestructRefundGas uint64 = 24000 // Refunded following a selfdestruct operation. MemoryGas uint64 = 3 // Times the address of the (highest referenced byte in memory + 1). NOTE: referencing happens on read, write and in instructions such as RETURN and CALL. - TxDataNonZeroGasFrontier uint64 = 68 // Per byte of data attached to a transaction that is not equal to zero. NOTE: Not payable on data of calls between transactions. - TxDataNonZeroGasEIP2028 uint64 = 16 // Per byte of non zero data attached to a transaction after EIP 2028 (part in Istanbul) - TxAccessListAddressGas uint64 = 2400 // Per address specified in EIP 2930 access list - TxAccessListStorageKeyGas uint64 = 1900 // Per storage key specified in EIP 2930 access list + TxDataNonZeroGasFrontier uint64 = 68 // Per byte of data attached to a transaction that is not equal to zero. NOTE: Not payable on data of calls between transactions. + TxDataNonZeroGasEIP2028 uint64 = 16 // Per byte of non zero data attached to a transaction after EIP 2028 (part in Istanbul) + TxTokenPerNonZeroByte uint64 = 4 // Token cost per non-zero byte as specified by EIP-7623. + TxCostFloorPerToken uint64 = 10 // Cost floor per byte of data as specified by EIP-7623. + TxAccessListAddressGas uint64 = 2400 // Per address specified in EIP 2930 access list + TxAccessListStorageKeyGas uint64 = 1900 // Per storage key specified in EIP 2930 access list + TxAuthTupleGas uint64 = 12500 // Per auth tuple code specified in EIP-7702 // These have been changed during the course of the chain CallGasFrontier uint64 = 40 // Once per CALL operation & message call transaction. @@ -151,14 +154,14 @@ const ( Bn256PairingPerPointGasByzantium uint64 = 80000 // Byzantium per-point price for an elliptic curve pairing check Bn256PairingPerPointGasIstanbul uint64 = 34000 // Per-point price for an elliptic curve pairing check - Bls12381G1AddGas uint64 = 500 // Price for BLS12-381 elliptic curve G1 point addition + Bls12381G1AddGas uint64 = 375 // Price for BLS12-381 elliptic curve G1 point addition Bls12381G1MulGas uint64 = 12000 // Price for BLS12-381 elliptic curve G1 point scalar multiplication - Bls12381G2AddGas uint64 = 800 // Price for BLS12-381 elliptic curve G2 point addition - Bls12381G2MulGas uint64 = 45000 // Price for BLS12-381 elliptic curve G2 point scalar multiplication - Bls12381PairingBaseGas uint64 = 65000 // Base gas price for BLS12-381 elliptic curve pairing check - Bls12381PairingPerPairGas uint64 = 43000 // Per-point pair gas price for BLS12-381 elliptic curve pairing check + Bls12381G2AddGas uint64 = 600 // Price for BLS12-381 elliptic curve G2 point addition + Bls12381G2MulGas uint64 = 22500 // Price for BLS12-381 elliptic curve G2 point scalar multiplication + Bls12381PairingBaseGas uint64 = 37700 // Base gas price for BLS12-381 elliptic curve pairing check + Bls12381PairingPerPairGas uint64 = 32600 // Per-point pair gas price for BLS12-381 elliptic curve pairing check Bls12381MapG1Gas uint64 = 5500 // Gas price for BLS12-381 mapping field element to G1 operation - Bls12381MapG2Gas uint64 = 75000 // Gas price for BLS12-381 mapping field element to G2 operation + Bls12381MapG2Gas uint64 = 23800 // Gas price for BLS12-381 mapping field element to G2 operation // The Refund Quotient is the cap on how much of the used gas can be refunded. Before EIP-3529, // up to half the consumed gas could be refunded. Redefined as 1/5th in EIP-3529 @@ -169,17 +172,16 @@ const ( BlobTxFieldElementsPerBlob = 4096 // Number of field elements stored in a single data blob BlobTxBlobGasPerBlob = 1 << 17 // Gas consumption of a single data blob (== blob byte size) BlobTxMinBlobGasprice = 1 // Minimum gas price for data blobs - BlobTxBlobGaspriceUpdateFraction = 3338477 // Controls the maximum rate of change for blob gas price BlobTxPointEvaluationPrecompileGas = 50000 // Gas price for the point evaluation precompile. - BlobTxTargetBlobGasPerBlock = 3 * BlobTxBlobGasPerBlob // Target consumable blob gas for data blobs per block (for 1559-like pricing) - MaxBlobGasPerBlock = 6 * BlobTxBlobGasPerBlob // Maximum consumable blob gas for data blobs per block - HistoryServeWindow = 8192 // Number of blocks to serve historical block hashes for, EIP-2935. ) -// Gas discount table for BLS12-381 G1 and G2 multi exponentiation operations -var Bls12381MultiExpDiscountTable = [128]uint64{1200, 888, 764, 641, 594, 547, 500, 453, 438, 423, 408, 394, 379, 364, 349, 334, 330, 326, 322, 318, 314, 310, 306, 302, 298, 294, 289, 285, 281, 277, 273, 269, 268, 266, 265, 263, 262, 260, 259, 257, 256, 254, 253, 251, 250, 248, 247, 245, 244, 242, 241, 239, 238, 236, 235, 233, 232, 231, 229, 228, 226, 225, 223, 222, 221, 220, 219, 219, 218, 217, 216, 216, 215, 214, 213, 213, 212, 211, 211, 210, 209, 208, 208, 207, 206, 205, 205, 204, 203, 202, 202, 201, 200, 199, 199, 198, 197, 196, 196, 195, 194, 193, 193, 192, 191, 191, 190, 189, 188, 188, 187, 186, 185, 185, 184, 183, 182, 182, 181, 180, 179, 179, 178, 177, 176, 176, 175, 174} +// Bls12381G1MultiExpDiscountTable is the gas discount table for BLS12-381 G1 multi exponentiation operation +var Bls12381G1MultiExpDiscountTable = [128]uint64{1000, 949, 848, 797, 764, 750, 738, 728, 719, 712, 705, 698, 692, 687, 682, 677, 673, 669, 665, 661, 658, 654, 651, 648, 645, 642, 640, 637, 635, 632, 630, 627, 625, 623, 621, 619, 617, 615, 613, 611, 609, 608, 606, 604, 603, 601, 599, 598, 596, 595, 593, 592, 591, 589, 588, 586, 585, 584, 582, 581, 580, 579, 577, 576, 575, 574, 573, 572, 570, 569, 568, 567, 566, 565, 564, 563, 562, 561, 560, 559, 558, 557, 556, 555, 554, 553, 552, 551, 550, 549, 548, 547, 547, 546, 545, 544, 543, 542, 541, 540, 540, 539, 538, 537, 536, 536, 535, 534, 533, 532, 532, 531, 530, 529, 528, 528, 527, 526, 525, 525, 524, 523, 522, 522, 521, 520, 520, 519} + +// Bls12381G2MultiExpDiscountTable is the gas discount table for BLS12-381 G2 multi exponentiation operation +var Bls12381G2MultiExpDiscountTable = [128]uint64{1000, 1000, 923, 884, 855, 832, 812, 796, 782, 770, 759, 749, 740, 732, 724, 717, 711, 704, 699, 693, 688, 683, 679, 674, 670, 666, 663, 659, 655, 652, 649, 646, 643, 640, 637, 634, 632, 629, 627, 624, 622, 620, 618, 615, 613, 611, 609, 607, 606, 604, 602, 600, 598, 597, 595, 593, 592, 590, 589, 587, 586, 584, 583, 582, 580, 579, 578, 576, 575, 574, 573, 571, 570, 569, 568, 567, 566, 565, 563, 562, 561, 560, 559, 558, 557, 556, 555, 554, 553, 552, 552, 551, 550, 549, 548, 547, 546, 545, 545, 544, 543, 542, 541, 541, 540, 539, 538, 537, 537, 536, 535, 535, 534, 533, 532, 532, 531, 530, 530, 529, 528, 528, 527, 526, 526, 525, 524, 524} // Difficulty parameters. var ( @@ -199,14 +201,14 @@ var ( BeaconRootsCode = common.FromHex("3373fffffffffffffffffffffffffffffffffffffffe14604d57602036146024575f5ffd5b5f35801560495762001fff810690815414603c575f5ffd5b62001fff01545f5260205ff35b5f5ffd5b62001fff42064281555f359062001fff015500") // EIP-2935 - Serve historical block hashes from state - HistoryStorageAddress = common.HexToAddress("0x0aae40965e6800cd9b1f4b05ff21581047e3f91e") - HistoryStorageCode = common.FromHex("3373fffffffffffffffffffffffffffffffffffffffe1460575767ffffffffffffffff5f3511605357600143035f3511604b575f35612000014311604b57611fff5f3516545f5260205ff35b5f5f5260205ff35b5f5ffd5b5f35611fff60014303165500") + HistoryStorageAddress = common.HexToAddress("0x0000F90827F1C53a10cb7A02335B175320002935") + HistoryStorageCode = common.FromHex("3373fffffffffffffffffffffffffffffffffffffffe14604657602036036042575f35600143038111604257611fff81430311604257611fff9006545f5260205ff35b5f5ffd5b5f35611fff60014303065500") // EIP-7002 - Execution layer triggerable withdrawals - WithdrawalQueueAddress = common.HexToAddress("0x09Fc772D0857550724b07B850a4323f39112aAaA") - WithdrawalQueueCode = common.FromHex("3373fffffffffffffffffffffffffffffffffffffffe1460c7573615156028575f545f5260205ff35b36603814156101f05760115f54807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff146101f057600182026001905f5b5f821115608057810190830284830290049160010191906065565b9093900434106101f057600154600101600155600354806003026004013381556001015f35815560010160203590553360601b5f5260385f601437604c5fa0600101600355005b6003546002548082038060101160db575060105b5f5b81811461017f5780604c02838201600302600401805490600101805490600101549160601b83528260140152807fffffffffffffffffffffffffffffffff0000000000000000000000000000000016826034015260401c906044018160381c81600701538160301c81600601538160281c81600501538160201c81600401538160181c81600301538160101c81600201538160081c81600101535360010160dd565b9101809214610191579060025561019c565b90505f6002555f6003555b5f54807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff14156101c957505f5b6001546002828201116101de5750505f6101e4565b01600290035b5f555f600155604c025ff35b5f5ffd") + WithdrawalQueueAddress = common.HexToAddress("0x00000961Ef480Eb55e80D19ad83579A64c007002") + WithdrawalQueueCode = common.FromHex("3373fffffffffffffffffffffffffffffffffffffffe1460cb5760115f54807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff146101f457600182026001905f5b5f82111560685781019083028483029004916001019190604d565b909390049250505036603814608857366101f457346101f4575f5260205ff35b34106101f457600154600101600155600354806003026004013381556001015f35815560010160203590553360601b5f5260385f601437604c5fa0600101600355005b6003546002548082038060101160df575060105b5f5b8181146101835782810160030260040181604c02815460601b8152601401816001015481526020019060020154807fffffffffffffffffffffffffffffffff00000000000000000000000000000000168252906010019060401c908160381c81600701538160301c81600601538160281c81600501538160201c81600401538160181c81600301538160101c81600201538160081c81600101535360010160e1565b910180921461019557906002556101a0565b90505f6002555f6003555b5f54807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff14156101cd57505f5b6001546002828201116101e25750505f6101e8565b01600290035b5f555f600155604c025ff35b5f5ffd") // EIP-7251 - Increase the MAX_EFFECTIVE_BALANCE - ConsolidationQueueAddress = common.HexToAddress("0x01aBEa29659e5e97C95107F20bb753cD3e09bBBb") - ConsolidationQueueCode = common.FromHex("3373fffffffffffffffffffffffffffffffffffffffe1460cf573615156028575f545f5260205ff35b366060141561019a5760115f54807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1461019a57600182026001905f5b5f821115608057810190830284830290049160010191906065565b90939004341061019a57600154600101600155600354806004026004013381556001015f358155600101602035815560010160403590553360601b5f5260605f60143760745fa0600101600355005b6003546002548082038060011160e3575060015b5f5b8181146101295780607402838201600402600401805490600101805490600101805490600101549260601b84529083601401528260340152906054015260010160e5565b910180921461013b5790600255610146565b90505f6002555f6003555b5f54807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff141561017357505f5b6001546001828201116101885750505f61018e565b01600190035b5f555f6001556074025ff35b5f5ffd") + ConsolidationQueueAddress = common.HexToAddress("0x0000BBdDc7CE488642fb579F8B00f3a590007251") + ConsolidationQueueCode = common.FromHex("3373fffffffffffffffffffffffffffffffffffffffe1460d35760115f54807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1461019a57600182026001905f5b5f82111560685781019083028483029004916001019190604d565b9093900492505050366060146088573661019a573461019a575f5260205ff35b341061019a57600154600101600155600354806004026004013381556001015f358155600101602035815560010160403590553360601b5f5260605f60143760745fa0600101600355005b6003546002548082038060021160e7575060025b5f5b8181146101295782810160040260040181607402815460601b815260140181600101548152602001816002015481526020019060030154905260010160e9565b910180921461013b5790600255610146565b90505f6002555f6003555b5f54807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff141561017357505f5b6001546001828201116101885750505f61018e565b01600190035b5f555f6001556074025ff35b5f5ffd") ) diff --git a/vendor/github.com/ethereum/go-ethereum/rpc/ipc_wasip1.go b/vendor/github.com/ethereum/go-ethereum/rpc/ipc_wasip1.go new file mode 100644 index 0000000000..2608e29222 --- /dev/null +++ b/vendor/github.com/ethereum/go-ethereum/rpc/ipc_wasip1.go @@ -0,0 +1,38 @@ +// Copyright 2018 The go-ethereum Authors +// This file is part of the go-ethereum library. +// +// The go-ethereum library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The go-ethereum library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see . + +//go:build wasip1 +// +build wasip1 + +package rpc + +import ( + "context" + "errors" + "net" +) + +var errNotSupported = errors.New("rpc: not supported") + +// ipcListen will create a named pipe on the given endpoint. +func ipcListen(endpoint string) (net.Listener, error) { + return nil, errNotSupported +} + +// newIPCConnection will connect to a named pipe with the given endpoint as name. +func newIPCConnection(ctx context.Context, endpoint string) (net.Conn, error) { + return nil, errNotSupported +} diff --git a/vendor/github.com/ethereum/go-ethereum/signer/core/apitypes/types.go b/vendor/github.com/ethereum/go-ethereum/signer/core/apitypes/types.go index 2ae182279a..b8b96bef92 100644 --- a/vendor/github.com/ethereum/go-ethereum/signer/core/apitypes/types.go +++ b/vendor/github.com/ethereum/go-ethereum/signer/core/apitypes/types.go @@ -501,7 +501,16 @@ func (typedData *TypedData) encodeArrayValue(encValue interface{}, encType strin for _, item := range arrayValue { if reflect.TypeOf(item).Kind() == reflect.Slice || reflect.TypeOf(item).Kind() == reflect.Array { - encodedData, err := typedData.encodeArrayValue(item, parsedType, depth+1) + var ( + encodedData hexutil.Bytes + err error + ) + if reflect.TypeOf(item).Elem().Kind() == reflect.Uint8 { + // the item type is bytes. encode the bytes array directly instead of recursing. + encodedData, err = typedData.EncodePrimitiveValue(parsedType, item, depth+1) + } else { + encodedData, err = typedData.encodeArrayValue(item, parsedType, depth+1) + } if err != nil { return nil, err } @@ -676,7 +685,7 @@ func (typedData *TypedData) EncodePrimitiveValue(encType string, encValue interf if err != nil { return nil, err } - return math.U256Bytes(b), nil + return math.U256Bytes(new(big.Int).Set(b)), nil } return nil, fmt.Errorf("unrecognized type '%s'", encType) } diff --git a/vendor/github.com/ethereum/go-verkle/README.md b/vendor/github.com/ethereum/go-verkle/README.md index 1946b93fe1..88c8ff201a 100644 --- a/vendor/github.com/ethereum/go-verkle/README.md +++ b/vendor/github.com/ethereum/go-verkle/README.md @@ -7,7 +7,6 @@ > A Go implementation of Verkle Tree datastructure defined in the [spec](https://github.com/crate-crypto/verkle-trie-ref/tree/master/verkle). - ## Test & Benchmarks To run the tests and benchmarks, run the following commands: diff --git a/vendor/github.com/ethereum/go-verkle/encoding.go b/vendor/github.com/ethereum/go-verkle/encoding.go index d5e27d17f6..c0c8c6be79 100644 --- a/vendor/github.com/ethereum/go-verkle/encoding.go +++ b/vendor/github.com/ethereum/go-verkle/encoding.go @@ -56,12 +56,11 @@ const ( leafC1CommitmentOffset = leafCommitmentOffset + banderwagon.UncompressedSize leafC2CommitmentOffset = leafC1CommitmentOffset + banderwagon.UncompressedSize leafChildrenOffset = leafC2CommitmentOffset + banderwagon.UncompressedSize - leafBalanceSize = 32 - leafNonceSize = 8 + leafBasicDataSize = 32 leafSlotSize = 32 leafValueIndexSize = 1 singleSlotLeafSize = nodeTypeSize + StemSize + 2*banderwagon.UncompressedSize + leafValueIndexSize + leafSlotSize - eoaLeafSize = nodeTypeSize + StemSize + 2*banderwagon.UncompressedSize + leafBalanceSize + leafNonceSize + eoaLeafSize = nodeTypeSize + StemSize + 2*banderwagon.UncompressedSize + leafBasicDataSize ) func bit(bitlist []byte, nr int) bool { @@ -138,14 +137,8 @@ func parseLeafNode(serialized []byte, depth byte) (VerkleNode, error) { func parseEoAccountNode(serialized []byte, depth byte) (VerkleNode, error) { var values [NodeWidth][]byte offset := leafStemOffset + StemSize + 2*banderwagon.UncompressedSize - values[0] = zero32[:] // 0 version - values[1] = serialized[offset : offset+leafBalanceSize] // balance - var nonce [32]byte - offset += leafBalanceSize - copy(nonce[:leafNonceSize], serialized[offset:offset+leafNonceSize]) - values[2] = nonce[:] // nonce - values[3] = EmptyCodeHash[:] - values[4] = zero32[:] // 0 code size + values[0] = serialized[offset : offset+leafBasicDataSize] // basic data + values[1] = EmptyCodeHash[:] ln := NewLeafNodeWithNoComms(serialized[leafStemOffset:leafStemOffset+StemSize], values[:]) ln.setDepth(depth) ln.c1 = new(Point) diff --git a/vendor/github.com/ethereum/go-verkle/proof_ipa.go b/vendor/github.com/ethereum/go-verkle/proof_ipa.go index c1f2081556..15d4e8a85f 100644 --- a/vendor/github.com/ethereum/go-verkle/proof_ipa.go +++ b/vendor/github.com/ethereum/go-verkle/proof_ipa.go @@ -53,6 +53,9 @@ type VerkleProof struct { } func (vp *VerkleProof) Copy() *VerkleProof { + if vp == nil { + return nil + } ret := &VerkleProof{ OtherStems: make([][StemSize]byte, len(vp.OtherStems)), DepthExtensionPresent: make([]byte, len(vp.DepthExtensionPresent)), @@ -73,6 +76,35 @@ func (vp *VerkleProof) Copy() *VerkleProof { return ret } +func (vp *VerkleProof) Equal(other *VerkleProof) error { + if len(vp.OtherStems) != len(other.OtherStems) { + return fmt.Errorf("different number of other stems: %d != %d", len(vp.OtherStems), len(other.OtherStems)) + } + for i := range vp.OtherStems { + if vp.OtherStems[i] != other.OtherStems[i] { + return fmt.Errorf("different other stem: %x != %x", vp.OtherStems[i], other.OtherStems[i]) + } + } + if len(vp.DepthExtensionPresent) != len(other.DepthExtensionPresent) { + return fmt.Errorf("different number of depth extension present: %d != %d", len(vp.DepthExtensionPresent), len(other.DepthExtensionPresent)) + } + if !bytes.Equal(vp.DepthExtensionPresent, other.DepthExtensionPresent) { + return fmt.Errorf("different depth extension present: %x != %x", vp.DepthExtensionPresent, other.DepthExtensionPresent) + } + if len(vp.CommitmentsByPath) != len(other.CommitmentsByPath) { + return fmt.Errorf("different number of commitments by path: %d != %d", len(vp.CommitmentsByPath), len(other.CommitmentsByPath)) + } + for i := range vp.CommitmentsByPath { + if vp.CommitmentsByPath[i] != other.CommitmentsByPath[i] { + return fmt.Errorf("different commitment by path: %x != %x", vp.CommitmentsByPath[i], other.CommitmentsByPath[i]) + } + } + if vp.D != other.D { + return fmt.Errorf("different D: %x != %x", vp.D, other.D) + } + return nil +} + type Proof struct { Multipoint *ipa.MultiProof // multipoint argument ExtStatus []byte // the extension status of each stem @@ -118,6 +150,40 @@ func (sd StateDiff) Copy() StateDiff { return ret } +func (sd StateDiff) Equal(other StateDiff) error { + if len(sd) != len(other) { + return fmt.Errorf("different number of stem state diffs: %d != %d", len(sd), len(other)) + } + for i := range sd { + if sd[i].Stem != other[i].Stem { + return fmt.Errorf("different stem: %x != %x", sd[i].Stem, other[i].Stem) + } + if len(sd[i].SuffixDiffs) != len(other[i].SuffixDiffs) { + return fmt.Errorf("different number of suffix state diffs: %d != %d", len(sd[i].SuffixDiffs), len(other[i].SuffixDiffs)) + } + for j := range sd[i].SuffixDiffs { + if sd[i].SuffixDiffs[j].Suffix != other[i].SuffixDiffs[j].Suffix { + return fmt.Errorf("different suffix: %x != %x", sd[i].SuffixDiffs[j].Suffix, other[i].SuffixDiffs[j].Suffix) + } + if sd[i].SuffixDiffs[j].CurrentValue != nil && other[i].SuffixDiffs[j].CurrentValue != nil { + if *sd[i].SuffixDiffs[j].CurrentValue != *other[i].SuffixDiffs[j].CurrentValue { + return fmt.Errorf("different current value: %x != %x", *sd[i].SuffixDiffs[j].CurrentValue, *other[i].SuffixDiffs[j].CurrentValue) + } + } else if sd[i].SuffixDiffs[j].CurrentValue != nil || other[i].SuffixDiffs[j].CurrentValue != nil { + return fmt.Errorf("different current value: %x != %x", sd[i].SuffixDiffs[j].CurrentValue, other[i].SuffixDiffs[j].CurrentValue) + } + if sd[i].SuffixDiffs[j].NewValue != nil && other[i].SuffixDiffs[j].NewValue != nil { + if *sd[i].SuffixDiffs[j].NewValue != *other[i].SuffixDiffs[j].NewValue { + return fmt.Errorf("different new value: %x != %x", *sd[i].SuffixDiffs[j].NewValue, *other[i].SuffixDiffs[j].NewValue) + } + } else if sd[i].SuffixDiffs[j].NewValue != nil || other[i].SuffixDiffs[j].NewValue != nil { + return fmt.Errorf("different new value: %x != %x", sd[i].SuffixDiffs[j].NewValue, other[i].SuffixDiffs[j].NewValue) + } + } + } + return nil +} + func GetCommitmentsForMultiproof(root VerkleNode, keys [][]byte, resolver NodeResolverFn) (*ProofElements, []byte, []Stem, error) { sort.Sort(keylist(keys)) return root.GetProofItems(keylist(keys), resolver) diff --git a/vendor/github.com/ethereum/go-verkle/tree.go b/vendor/github.com/ethereum/go-verkle/tree.go index e3a20f2207..b62e732c3a 100644 --- a/vendor/github.com/ethereum/go-verkle/tree.go +++ b/vendor/github.com/ethereum/go-verkle/tree.go @@ -1832,7 +1832,6 @@ func (n *InternalNode) serializeInternalWithUncompressedCommitment(pointsIdx map } var ( - zero24 [24]byte zero32 [32]byte EmptyCodeHash, _ = hex.DecodeString("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470") ) @@ -1863,19 +1862,10 @@ func (n *LeafNode) serializeLeafWithUncompressedCommitments(cBytes, c1Bytes, c2B switch i { case 0: // Version should be 0 - isEoA = v != nil && bytes.Equal(v, zero32[:]) - case 1: - // Balance should not be nil isEoA = v != nil - case 2: - // Nonce should have its last 24 bytes set to 0 - isEoA = v != nil && bytes.Equal(v[leafNonceSize:], zero24[:]) - case 3: + case 1: // Code hash should be the empty code hash isEoA = v != nil && bytes.Equal(v, EmptyCodeHash[:]) - case 4: - // Code size must be 0 - isEoA = v != nil && bytes.Equal(v, zero32[:]) default: // All other values must be nil isEoA = v == nil @@ -1891,7 +1881,11 @@ func (n *LeafNode) serializeLeafWithUncompressedCommitments(cBytes, c1Bytes, c2B result = buf[:] result[0] = singleSlotType copy(result[leafStemOffset:], n.stem[:StemSize]) - copy(result[leafStemOffset+StemSize:], c1Bytes[:]) + if lastIdx < 128 { + copy(result[leafStemOffset+StemSize:], c1Bytes[:]) + } else { + copy(result[leafStemOffset+StemSize:], c2Bytes[:]) + } copy(result[leafStemOffset+StemSize+banderwagon.UncompressedSize:], cBytes[:]) result[leafStemOffset+StemSize+2*banderwagon.UncompressedSize] = byte(lastIdx) copy(result[leafStemOffset+StemSize+2*banderwagon.UncompressedSize+leafValueIndexSize:], n.values[lastIdx][:]) @@ -1902,8 +1896,7 @@ func (n *LeafNode) serializeLeafWithUncompressedCommitments(cBytes, c1Bytes, c2B copy(result[leafStemOffset:], n.stem[:StemSize]) copy(result[leafStemOffset+StemSize:], c1Bytes[:]) copy(result[leafStemOffset+StemSize+banderwagon.UncompressedSize:], cBytes[:]) - copy(result[leafStemOffset+StemSize+2*banderwagon.UncompressedSize:], n.values[1]) // copy balance - copy(result[leafStemOffset+StemSize+2*banderwagon.UncompressedSize+leafBalanceSize:], n.values[2][:leafNonceSize]) // copy nonce + copy(result[leafStemOffset+StemSize+2*banderwagon.UncompressedSize:], n.values[0]) // copy basic data default: result = make([]byte, nodeTypeSize+StemSize+bitlistSize+3*banderwagon.UncompressedSize+len(children)) result[0] = leafType diff --git a/vendor/github.com/holiman/uint256/circle.yml b/vendor/github.com/holiman/uint256/circle.yml index 48243cb096..3b0b6d1c60 100644 --- a/vendor/github.com/holiman/uint256/circle.yml +++ b/vendor/github.com/holiman/uint256/circle.yml @@ -19,14 +19,14 @@ commands: jobs: - go122: + go123: docker: - - image: cimg/go:1.22 + - image: cimg/go:1.23 steps: - run: name: "Install tools" command: | - curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.58.0 + curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.61.0 - checkout - run: name: "Lint" @@ -82,6 +82,13 @@ jobs: name: "Test (PPC64 emulation)" command: qemu-ppc64-static uint256.test.ppc64 -test.v + go122: + docker: + - image: cimg/go:1.22 + steps: + - checkout + - test + go121: docker: - image: cimg/go:1.21 @@ -112,9 +119,10 @@ workflows: - go119 - go120 - go121 - - go122: + - go122 + - go123: requires: - - go121 + - go122 - bigendian: requires: - - go122 + - go123 diff --git a/vendor/github.com/holiman/uint256/conversion.go b/vendor/github.com/holiman/uint256/conversion.go index 50c5276736..640197c764 100644 --- a/vendor/github.com/holiman/uint256/conversion.go +++ b/vendor/github.com/holiman/uint256/conversion.go @@ -236,7 +236,7 @@ func (z *Int) UnmarshalText(input []byte) error { if len(input) >= 2 && input[0] == '0' && (input[1] == 'x' || input[1] == 'X') { return z.fromHex(string(input)) } - return z.fromDecimal(string(input)) + return z.SetFromDecimal(string(input)) } // SetFromBig converts a big.Int to Int and sets the value to z. @@ -712,7 +712,7 @@ func (z *Int) MarshalJSON() ([]byte, error) { func (z *Int) UnmarshalJSON(input []byte) error { if len(input) < 2 || input[0] != '"' || input[len(input)-1] != '"' { // if not quoted, it must be decimal - return z.fromDecimal(string(input)) + return z.SetFromDecimal(string(input)) } return z.UnmarshalText(input[1 : len(input)-1]) } diff --git a/vendor/github.com/holiman/uint256/decimal.go b/vendor/github.com/holiman/uint256/decimal.go index 0a268f3c8b..564ae12c86 100644 --- a/vendor/github.com/holiman/uint256/decimal.go +++ b/vendor/github.com/holiman/uint256/decimal.go @@ -177,6 +177,8 @@ var multipliers = [5]*Int{ // fromDecimal is a helper function to only ever be called via SetFromDecimal // this function takes a string and chunks it up, calling ParseUint on it up to 5 times // these chunks are then multiplied by the proper power of 10, then added together. +// Note: this method assumes that some basic validity-checks have already been performed +// on the input 'bs'. See SetFromDecimal. func (z *Int) fromDecimal(bs string) error { // first clear the input z.Clear() diff --git a/vendor/github.com/holiman/uint256/uint256.go b/vendor/github.com/holiman/uint256/uint256.go index 9033594a5a..043b8ed82a 100644 --- a/vendor/github.com/holiman/uint256/uint256.go +++ b/vendor/github.com/holiman/uint256/uint256.go @@ -144,18 +144,35 @@ func (z *Int) WriteToSlice(dest []byte) { } } +// PutUint256 writes all 32 bytes of z to the destination slice, including zero-bytes. +// If dest is larger than 32 bytes, z will fill the first parts, and leave +// the end untouched. +// Note: The dest slice must be at least 32 bytes large, otherwise this +// method will panic. The method WriteToSlice, which is slower, should be used +// if the destination slice is smaller or of unknown size. +func (z *Int) PutUint256(dest []byte) { + _ = dest[31] + binary.BigEndian.PutUint64(dest[0:8], z[3]) + binary.BigEndian.PutUint64(dest[8:16], z[2]) + binary.BigEndian.PutUint64(dest[16:24], z[1]) + binary.BigEndian.PutUint64(dest[24:32], z[0]) +} + // WriteToArray32 writes all 32 bytes of z to the destination array, including zero-bytes func (z *Int) WriteToArray32(dest *[32]byte) { - for i := 0; i < 32; i++ { - dest[31-i] = byte(z[i/8] >> uint64(8*(i%8))) - } + // The PutUint64()s are inlined and we get 4x (load, bswap, store) instructions. + binary.BigEndian.PutUint64(dest[0:8], z[3]) + binary.BigEndian.PutUint64(dest[8:16], z[2]) + binary.BigEndian.PutUint64(dest[16:24], z[1]) + binary.BigEndian.PutUint64(dest[24:32], z[0]) } // WriteToArray20 writes the last 20 bytes of z to the destination array, including zero-bytes func (z *Int) WriteToArray20(dest *[20]byte) { - for i := 0; i < 20; i++ { - dest[19-i] = byte(z[i/8] >> uint64(8*(i%8))) - } + // The PutUint*()s are inlined and we get 3x (load, bswap, store) instructions. + binary.BigEndian.PutUint32(dest[0:4], uint32(z[2])) + binary.BigEndian.PutUint64(dest[4:12], z[1]) + binary.BigEndian.PutUint64(dest[12:20], z[0]) } // Uint64 returns the lower 64-bits of z @@ -1182,12 +1199,18 @@ func (z *Int) Byte(n *Int) *Int { // Exp sets z = base**exponent mod 2**256, and returns z. func (z *Int) Exp(base, exponent *Int) *Int { - res := Int{1, 0, 0, 0} - multiplier := *base - expBitLen := exponent.BitLen() + var ( + res = Int{1, 0, 0, 0} + multiplier = *base + expBitLen = exponent.BitLen() + curBit = 0 + word = exponent[0] + even = base[0]&1 == 0 + ) + if even && expBitLen > 8 { + return z.Clear() + } - curBit := 0 - word := exponent[0] for ; curBit < expBitLen && curBit < 64; curBit++ { if word&1 == 1 { res.Mul(&res, &multiplier) @@ -1195,6 +1218,9 @@ func (z *Int) Exp(base, exponent *Int) *Int { multiplier.squared() word >>= 1 } + if even { // If the base was even, we are finished now + return z.Set(&res) + } word = exponent[1] for ; curBit < expBitLen && curBit < 128; curBit++ { diff --git a/vendor/github.com/supranational/blst/bindings/go/README.md b/vendor/github.com/supranational/blst/bindings/go/README.md index 961853ed69..7bd6599d8d 100644 --- a/vendor/github.com/supranational/blst/bindings/go/README.md +++ b/vendor/github.com/supranational/blst/bindings/go/README.md @@ -13,10 +13,19 @@ go test The generate.py script is used to generate both min-pk and min-sig variants of the binding from a common code base. It consumes the `*.tgo` files along with `blst_minpk_test.go` and produces `blst.go` and `blst_minsig_test.go`. The .tgo files can treated as if they were .go files, including the use of gofmt and goimports. The generate script will filter out extra imports while processing and automatically run goimports on the final blst.go file. -After running generate.py, `go build` and `go test` can be run as usual. Cgo will compile `cgo_server.c`, which includes the required C implementation files, and `cgo_assembly.S`, which includes appropriate pre-generated assembly code for the platform. To compile on Windows one has to have MinGW gcc on the `%PATH%`. +After running generate.py, `go build` and `go test` can be run as usual. Cgo will compile `cgo_server.c`, which includes the required C implementation files, and `cgo_assembly.S`, which includes appropriate pre-generated assembly code for the platform. + +#### Caveats If the test or target application crashes with an "illegal instruction" exception [after copying to an older system], rebuild with `CGO_CFLAGS` environment variable set to `-O2 -D__BLST_PORTABLE__`. Don't forget `-O2`! +On Windows the C compiler invoked by cgo, one denoted in `go env CC` output, has to target [MinGW](https://www.mingw-w64.org/). Verify with ` -dM -E -x c nul: | findstr "MINGW64"`. + +If you're cross-compiling, you have to set `CC` environment variable to the target C cross-compiler and `CGO_ENABLED` to 1. For example, to compile the test program for ARM: +``` +env GOARCH=arm CC=arm-linux-gnueabi-gcc CGO_ENABLED=1 go test -c +``` + ## Usage There are two primary modes of operation that can be chosen based on type definitions in the application. @@ -73,8 +82,3 @@ func main() { ``` See the tests for further examples of usage. - -If you're cross-compiling, you have to set `CC` environment variable to the target C cross-compiler and `CGO_ENABLED` to 1. For example, to compile the test program for ARM: -``` -env GOARCH=arm CC=arm-linux-gnueabi-gcc CGO_ENABLED=1 go test -c -``` diff --git a/vendor/github.com/supranational/blst/bindings/go/blst.go b/vendor/github.com/supranational/blst/bindings/go/blst.go index 77f2241934..6fe6b31841 100644 --- a/vendor/github.com/supranational/blst/bindings/go/blst.go +++ b/vendor/github.com/supranational/blst/bindings/go/blst.go @@ -159,6 +159,7 @@ import ( "runtime" "sync" "sync/atomic" + "unsafe" ) const BLST_SCALAR_BYTES = 256 / 8 @@ -168,15 +169,15 @@ const BLST_P1_SERIALIZE_BYTES = BLST_FP_BYTES * 2 const BLST_P2_COMPRESS_BYTES = BLST_FP_BYTES * 2 const BLST_P2_SERIALIZE_BYTES = BLST_FP_BYTES * 4 -type Scalar = C.blst_scalar -type Fp = C.blst_fp -type Fp2 = C.blst_fp2 +type Scalar struct{ cgo C.blst_scalar } +type Fp struct{ cgo C.blst_fp } +type Fp2 struct{ cgo C.blst_fp2 } type Fp6 = C.blst_fp6 -type Fp12 = C.blst_fp12 -type P1 = C.blst_p1 -type P2 = C.blst_p2 -type P1Affine = C.blst_p1_affine -type P2Affine = C.blst_p2_affine +type Fp12 struct{ cgo C.blst_fp12 } +type P1 struct{ cgo C.blst_p1 } +type P2 struct{ cgo C.blst_p2 } +type P1Affine struct{ cgo C.blst_p1_affine } +type P2Affine struct{ cgo C.blst_p2_affine } type Message = []byte type Pairing = []C.blst_pairing type SecretKey = Scalar @@ -205,11 +206,11 @@ func initMaxProcs() int { return maxProcs } -func SetMaxProcs(max int) { - if max <= 0 { - max = 1 +func SetMaxProcs(procs int) { + if procs <= 0 { + procs = 1 } - maxProcs = max + maxProcs = procs } func numThreads(maxThreads int) int { @@ -229,9 +230,9 @@ func numThreads(maxThreads int) int { } var cgo_pairingSizeOf = C.blst_pairing_sizeof() -var cgo_p1Generator = *C.blst_p1_generator() -var cgo_p2Generator = *C.blst_p2_generator() -var cgo_fp12One = *C.blst_fp12_one() +var cgo_p1Generator = P1{*C.blst_p1_generator()} +var cgo_p2Generator = P2{*C.blst_p2_generator()} +var cgo_fp12One = Fp12{*C.blst_fp12_one()} // Secret key func (sk *SecretKey) Zeroize() { @@ -248,7 +249,7 @@ func KeyGen(ikm []byte, optional ...[]byte) *SecretKey { if len(ikm) < 32 { return nil } - C.blst_keygen(&sk, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), + C.blst_keygen(&sk.cgo, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), ptrOrNil(info), C.size_t(len(info))) // Postponing secret key zeroing till garbage collection can be too // late to be effective, but every little bit helps... @@ -265,7 +266,7 @@ func KeyGenV3(ikm []byte, optional ...[]byte) *SecretKey { if len(optional) > 0 { info = optional[0] } - C.blst_keygen_v3(&sk, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), + C.blst_keygen_v3(&sk.cgo, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), ptrOrNil(info), C.size_t(len(info))) // Postponing secret key zeroing till garbage collection can be too // late to be effective, but every little bit helps... @@ -282,7 +283,7 @@ func KeyGenV45(ikm []byte, salt []byte, optional ...[]byte) *SecretKey { if len(optional) > 0 { info = optional[0] } - C.blst_keygen_v4_5(&sk, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), + C.blst_keygen_v4_5(&sk.cgo, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), (*C.byte)(&salt[0]), C.size_t(len(salt)), ptrOrNil(info), C.size_t(len(info))) // Postponing secret key zeroing till garbage collection can be too @@ -300,7 +301,7 @@ func KeyGenV5(ikm []byte, salt []byte, optional ...[]byte) *SecretKey { if len(optional) > 0 { info = optional[0] } - C.blst_keygen_v5(&sk, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), + C.blst_keygen_v5(&sk.cgo, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), (*C.byte)(&salt[0]), C.size_t(len(salt)), ptrOrNil(info), C.size_t(len(info))) // Postponing secret key zeroing till garbage collection can be too @@ -314,7 +315,7 @@ func DeriveMasterEip2333(ikm []byte) *SecretKey { return nil } var sk SecretKey - C.blst_derive_master_eip2333(&sk, (*C.byte)(&ikm[0]), C.size_t(len(ikm))) + C.blst_derive_master_eip2333(&sk.cgo, (*C.byte)(&ikm[0]), C.size_t(len(ikm))) // Postponing secret key zeroing till garbage collection can be too // late to be effective, but every little bit helps... runtime.SetFinalizer(&sk, func(sk *SecretKey) { sk.Zeroize() }) @@ -323,7 +324,7 @@ func DeriveMasterEip2333(ikm []byte) *SecretKey { func (master *SecretKey) DeriveChildEip2333(child_index uint32) *SecretKey { var sk SecretKey - C.blst_derive_child_eip2333(&sk, master, C.uint(child_index)) + C.blst_derive_child_eip2333(&sk.cgo, &master.cgo, C.uint(child_index)) // Postponing secret key zeroing till garbage collection can be too // late to be effective, but every little bit helps... runtime.SetFinalizer(&sk, func(sk *SecretKey) { sk.Zeroize() }) @@ -356,30 +357,38 @@ func PairingFinalVerify(ctx Pairing, optional ...*Fp12) bool { if len(optional) > 0 { gtsig = optional[0] } - return bool(C.blst_pairing_finalverify(&ctx[0], gtsig)) + return bool(C.blst_pairing_finalverify(&ctx[0], gtsig.asPtr())) } func PairingRawAggregate(ctx Pairing, q *P2Affine, p *P1Affine) { - C.blst_pairing_raw_aggregate(&ctx[0], q, p) + C.blst_pairing_raw_aggregate(&ctx[0], &q.cgo, &p.cgo) } func PairingAsFp12(ctx Pairing) *Fp12 { var pt Fp12 - C.go_pairing_as_fp12(&pt, &ctx[0]) + C.go_pairing_as_fp12(&pt.cgo, &ctx[0]) return &pt } +func (pt *Fp12) asPtr() *C.blst_fp12 { + if pt != nil { + return &pt.cgo + } + + return nil +} + func Fp12One() Fp12 { return cgo_fp12One } func Fp12FinalVerify(pt1 *Fp12, pt2 *Fp12) bool { - return bool(C.blst_fp12_finalverify(pt1, pt2)) + return bool(C.blst_fp12_finalverify(&pt1.cgo, &pt2.cgo)) } func Fp12MillerLoop(q *P2Affine, p *P1Affine) *Fp12 { var pt Fp12 - C.blst_miller_loop(&pt, q, p) + C.blst_miller_loop(&pt.cgo, &q.cgo, &p.cgo) return &pt } @@ -393,7 +402,7 @@ func Fp12MillerLoopN(qs []P2Affine, ps []P1Affine) *Fp12 { if nThreads == 1 || nElems == 1 { var pt Fp12 - C.go_miller_loop_n(&pt, &qs[0], &ps[0], C.size_t(nElems), false) + C.go_miller_loop_n(&pt.cgo, &qs[0].cgo, &ps[0].cgo, C.size_t(nElems), false) return &pt } @@ -423,7 +432,7 @@ func Fp12MillerLoopN(qs []P2Affine, ps []P1Affine) *Fp12 { if n > stride { n = stride } - C.go_miller_loop_n(&acc, &qs[work], &ps[work], C.size_t(n), + C.go_miller_loop_n(&acc.cgo, &qs[work].cgo, &ps[work].cgo, C.size_t(n), C.bool(!first)) first = false } @@ -437,25 +446,25 @@ func Fp12MillerLoopN(qs []P2Affine, ps []P1Affine) *Fp12 { } var pt Fp12 - C.go_fp12slice_mul(&pt, &ret[0], C.size_t(nThreads)) + C.go_fp12slice_mul(&pt.cgo, &ret[0].cgo, C.size_t(nThreads)) return &pt } func (pt *Fp12) MulAssign(p *Fp12) { - C.blst_fp12_mul(pt, pt, p) + C.blst_fp12_mul(&pt.cgo, &pt.cgo, &p.cgo) } func (pt *Fp12) FinalExp() { - C.blst_final_exp(pt, pt) + C.blst_final_exp(&pt.cgo, &pt.cgo) } func (pt *Fp12) InGroup() bool { - return bool(C.blst_fp12_in_group(pt)) + return bool(C.blst_fp12_in_group(&pt.cgo)) } func (pt *Fp12) ToBendian() []byte { var out [BLST_FP_BYTES * 12]byte - C.blst_bendian_from_fp12((*C.byte)(&out[0]), pt) + C.blst_bendian_from_fp12((*C.byte)(&out[0]), &pt.cgo) return out[:] } @@ -479,13 +488,21 @@ func ptrOrNil(bytes []byte) *C.byte { // PublicKey // +func (pt *P1Affine) asPtr() *C.blst_p1_affine { + if pt != nil { + return &pt.cgo + } + + return nil +} + func (pk *P1Affine) From(s *Scalar) *P1Affine { - C.blst_sk_to_pk2_in_g1(nil, pk, s) + C.blst_sk_to_pk2_in_g1(nil, &pk.cgo, &s.cgo) return pk } func (pk *P1Affine) KeyValidate() bool { - return bool(C.go_p1_affine_validate(pk, true)) + return bool(C.go_p1_affine_validate(&pk.cgo, true)) } // sigInfcheck, check for infinity, is a way to avoid going @@ -493,7 +510,7 @@ func (pk *P1Affine) KeyValidate() bool { // always cryptographically safe, but application might want // to guard against obviously bogus individual[!] signatures. func (sig *P2Affine) SigValidate(sigInfcheck bool) bool { - return bool(C.go_p2_affine_validate(sig, C.bool(sigInfcheck))) + return bool(C.go_p2_affine_validate(&sig.cgo, C.bool(sigInfcheck))) } // @@ -513,7 +530,7 @@ func (sig *P2Affine) Sign(sk *SecretKey, msg []byte, dst []byte, } else { q = EncodeToG2(msg, dst, augSingle) } - C.blst_sign_pk2_in_g1(nil, sig, q, sk) + C.blst_sign_pk2_in_g1(nil, &sig.cgo, &q.cgo, &sk.cgo) return sig } @@ -717,7 +734,7 @@ func coreAggregateVerifyPkInG1(sigFn sigGetterP2, sigGroupcheck bool, atomic.StoreInt32(&valid, 0) } if atomic.LoadInt32(&valid) > 0 { - C.blst_aggregated_in_g2(>sig, sig) + C.blst_aggregated_in_g2(>sig.cgo, &sig.cgo) } mutex.Unlock() @@ -765,7 +782,7 @@ func CoreVerifyPkInG1(pk *P1Affine, sig *P2Affine, hash_or_encode bool, return C.BLST_SUCCESS } - return int(C.blst_core_verify_pk_in_g1(pk, sig, C.bool(hash_or_encode), + return int(C.blst_core_verify_pk_in_g1(&pk.cgo, &sig.cgo, C.bool(hash_or_encode), ptrOrNil(msg), C.size_t(len(msg)), ptrOrNil(dst), C.size_t(len(dst)), ptrOrNil(aug), C.size_t(len(aug)))) @@ -959,19 +976,19 @@ func (agg *P2Aggregate) AddAggregate(other *P2Aggregate) { } else if agg.v == nil { agg.v = other.v } else { - C.blst_p2_add_or_double(agg.v, agg.v, other.v) + C.blst_p2_add_or_double(&agg.v.cgo, &agg.v.cgo, &other.v.cgo) } } func (agg *P2Aggregate) Add(elmt *P2Affine, groupcheck bool) bool { - if groupcheck && !bool(C.blst_p2_affine_in_g2(elmt)) { + if groupcheck && !bool(C.blst_p2_affine_in_g2(&elmt.cgo)) { return false } if agg.v == nil { agg.v = new(P2) - C.blst_p2_from_affine(agg.v, elmt) + C.blst_p2_from_affine(&agg.v.cgo, &elmt.cgo) } else { - C.blst_p2_add_or_double_affine(agg.v, agg.v, elmt) + C.blst_p2_add_or_double_affine(&agg.v.cgo, &agg.v.cgo, &elmt.cgo) } return true } @@ -1021,15 +1038,15 @@ func (agg *P2Aggregate) coreAggregate(getter aggGetterP2, groupcheck bool, atomic.StoreInt32(&valid, 0) break } - if groupcheck && !bool(C.blst_p2_affine_in_g2(curElmt)) { + if groupcheck && !bool(C.blst_p2_affine_in_g2(&curElmt.cgo)) { atomic.StoreInt32(&valid, 0) break } if first { - C.blst_p2_from_affine(&agg, curElmt) + C.blst_p2_from_affine(&agg.cgo, &curElmt.cgo) first = false } else { - C.blst_p2_add_or_double_affine(&agg, &agg, curElmt) + C.blst_p2_add_or_double_affine(&agg.cgo, &agg.cgo, &curElmt.cgo) } // application might have some async work to do runtime.Gosched() @@ -1060,7 +1077,7 @@ func (agg *P2Aggregate) coreAggregate(getter aggGetterP2, groupcheck bool, agg.v = msg.agg first = false } else { - C.blst_p2_add_or_double(agg.v, agg.v, msg.agg) + C.blst_p2_add_or_double(&agg.v.cgo, &agg.v.cgo, &msg.agg.cgo) } } } @@ -1079,13 +1096,21 @@ func (agg *P2Aggregate) coreAggregate(getter aggGetterP2, groupcheck bool, // PublicKey // +func (pt *P2Affine) asPtr() *C.blst_p2_affine { + if pt != nil { + return &pt.cgo + } + + return nil +} + func (pk *P2Affine) From(s *Scalar) *P2Affine { - C.blst_sk_to_pk2_in_g2(nil, pk, s) + C.blst_sk_to_pk2_in_g2(nil, &pk.cgo, &s.cgo) return pk } func (pk *P2Affine) KeyValidate() bool { - return bool(C.go_p2_affine_validate(pk, true)) + return bool(C.go_p2_affine_validate(&pk.cgo, true)) } // sigInfcheck, check for infinity, is a way to avoid going @@ -1093,7 +1118,7 @@ func (pk *P2Affine) KeyValidate() bool { // always cryptographically safe, but application might want // to guard against obviously bogus individual[!] signatures. func (sig *P1Affine) SigValidate(sigInfcheck bool) bool { - return bool(C.go_p1_affine_validate(sig, C.bool(sigInfcheck))) + return bool(C.go_p1_affine_validate(&sig.cgo, C.bool(sigInfcheck))) } // @@ -1113,7 +1138,7 @@ func (sig *P1Affine) Sign(sk *SecretKey, msg []byte, dst []byte, } else { q = EncodeToG1(msg, dst, augSingle) } - C.blst_sign_pk2_in_g2(nil, sig, q, sk) + C.blst_sign_pk2_in_g2(nil, &sig.cgo, &q.cgo, &sk.cgo) return sig } @@ -1317,7 +1342,7 @@ func coreAggregateVerifyPkInG2(sigFn sigGetterP1, sigGroupcheck bool, atomic.StoreInt32(&valid, 0) } if atomic.LoadInt32(&valid) > 0 { - C.blst_aggregated_in_g1(>sig, sig) + C.blst_aggregated_in_g1(>sig.cgo, &sig.cgo) } mutex.Unlock() @@ -1365,7 +1390,7 @@ func CoreVerifyPkInG2(pk *P2Affine, sig *P1Affine, hash_or_encode bool, return C.BLST_SUCCESS } - return int(C.blst_core_verify_pk_in_g2(pk, sig, C.bool(hash_or_encode), + return int(C.blst_core_verify_pk_in_g2(&pk.cgo, &sig.cgo, C.bool(hash_or_encode), ptrOrNil(msg), C.size_t(len(msg)), ptrOrNil(dst), C.size_t(len(dst)), ptrOrNil(aug), C.size_t(len(aug)))) @@ -1559,19 +1584,19 @@ func (agg *P1Aggregate) AddAggregate(other *P1Aggregate) { } else if agg.v == nil { agg.v = other.v } else { - C.blst_p1_add_or_double(agg.v, agg.v, other.v) + C.blst_p1_add_or_double(&agg.v.cgo, &agg.v.cgo, &other.v.cgo) } } func (agg *P1Aggregate) Add(elmt *P1Affine, groupcheck bool) bool { - if groupcheck && !bool(C.blst_p1_affine_in_g1(elmt)) { + if groupcheck && !bool(C.blst_p1_affine_in_g1(&elmt.cgo)) { return false } if agg.v == nil { agg.v = new(P1) - C.blst_p1_from_affine(agg.v, elmt) + C.blst_p1_from_affine(&agg.v.cgo, &elmt.cgo) } else { - C.blst_p1_add_or_double_affine(agg.v, agg.v, elmt) + C.blst_p1_add_or_double_affine(&agg.v.cgo, &agg.v.cgo, &elmt.cgo) } return true } @@ -1621,15 +1646,15 @@ func (agg *P1Aggregate) coreAggregate(getter aggGetterP1, groupcheck bool, atomic.StoreInt32(&valid, 0) break } - if groupcheck && !bool(C.blst_p1_affine_in_g1(curElmt)) { + if groupcheck && !bool(C.blst_p1_affine_in_g1(&curElmt.cgo)) { atomic.StoreInt32(&valid, 0) break } if first { - C.blst_p1_from_affine(&agg, curElmt) + C.blst_p1_from_affine(&agg.cgo, &curElmt.cgo) first = false } else { - C.blst_p1_add_or_double_affine(&agg, &agg, curElmt) + C.blst_p1_add_or_double_affine(&agg.cgo, &agg.cgo, &curElmt.cgo) } // application might have some async work to do runtime.Gosched() @@ -1660,7 +1685,7 @@ func (agg *P1Aggregate) coreAggregate(getter aggGetterP1, groupcheck bool, agg.v = msg.agg first = false } else { - C.blst_p1_add_or_double(agg.v, agg.v, msg.agg) + C.blst_p1_add_or_double(&agg.v.cgo, &agg.v.cgo, &msg.agg.cgo) } } } @@ -1679,8 +1704,8 @@ func PairingAggregatePkInG1(ctx Pairing, PK *P1Affine, pkValidate bool, } r := C.blst_pairing_chk_n_aggr_pk_in_g1(&ctx[0], - PK, C.bool(pkValidate), - sig, C.bool(sigGroupcheck), + PK.asPtr(), C.bool(pkValidate), + sig.asPtr(), C.bool(sigGroupcheck), ptrOrNil(msg), C.size_t(len(msg)), ptrOrNil(aug), C.size_t(len(aug))) @@ -1697,9 +1722,9 @@ func PairingMulNAggregatePkInG1(ctx Pairing, PK *P1Affine, pkValidate bool, } r := C.blst_pairing_chk_n_mul_n_aggr_pk_in_g1(&ctx[0], - PK, C.bool(pkValidate), - sig, C.bool(sigGroupcheck), - &rand.b[0], C.size_t(randBits), + PK.asPtr(), C.bool(pkValidate), + sig.asPtr(), C.bool(sigGroupcheck), + &rand.cgo.b[0], C.size_t(randBits), ptrOrNil(msg), C.size_t(len(msg)), ptrOrNil(aug), C.size_t(len(aug))) @@ -1713,7 +1738,7 @@ func PairingMulNAggregatePkInG1(ctx Pairing, PK *P1Affine, pkValidate bool, // P1 Serdes func (p1 *P1Affine) Serialize() []byte { var out [BLST_P1_SERIALIZE_BYTES]byte - C.blst_p1_affine_serialize((*C.byte)(&out[0]), p1) + C.blst_p1_affine_serialize((*C.byte)(&out[0]), &p1.cgo) return out[:] } @@ -1721,14 +1746,14 @@ func (p1 *P1Affine) Deserialize(in []byte) *P1Affine { if len(in) != BLST_P1_SERIALIZE_BYTES { return nil } - if C.blst_p1_deserialize(p1, (*C.byte)(&in[0])) != C.BLST_SUCCESS { + if C.blst_p1_deserialize(&p1.cgo, (*C.byte)(&in[0])) != C.BLST_SUCCESS { return nil } return p1 } func (p1 *P1Affine) Compress() []byte { var out [BLST_P1_COMPRESS_BYTES]byte - C.blst_p1_affine_compress((*C.byte)(&out[0]), p1) + C.blst_p1_affine_compress((*C.byte)(&out[0]), &p1.cgo) return out[:] } @@ -1736,14 +1761,14 @@ func (p1 *P1Affine) Uncompress(in []byte) *P1Affine { if len(in) != BLST_P1_COMPRESS_BYTES { return nil } - if C.blst_p1_uncompress(p1, (*C.byte)(&in[0])) != C.BLST_SUCCESS { + if C.blst_p1_uncompress(&p1.cgo, (*C.byte)(&in[0])) != C.BLST_SUCCESS { return nil } return p1 } func (p1 *P1Affine) InG1() bool { - return bool(C.blst_p1_affine_in_g1(p1)) + return bool(C.blst_p1_affine_in_g1(&p1.cgo)) } func (_ *P1Affine) BatchUncompress(in [][]byte) []*P1Affine { @@ -1800,12 +1825,12 @@ func (_ *P1Affine) BatchUncompress(in [][]byte) []*P1Affine { func (p1 *P1) Serialize() []byte { var out [BLST_P1_SERIALIZE_BYTES]byte - C.blst_p1_serialize((*C.byte)(&out[0]), p1) + C.blst_p1_serialize((*C.byte)(&out[0]), &p1.cgo) return out[:] } func (p1 *P1) Compress() []byte { var out [BLST_P1_COMPRESS_BYTES]byte - C.blst_p1_compress((*C.byte)(&out[0]), p1) + C.blst_p1_compress((*C.byte)(&out[0]), &p1.cgo) return out[:] } @@ -1817,7 +1842,7 @@ func (p1 *P1) MultAssign(scalarIf interface{}, optional ...int) *P1 { scalar = (*C.byte)(&val[0]) nbits = len(val) * 8 case *Scalar: - scalar = &val.b[0] + scalar = &val.cgo.b[0] nbits = 255 default: panic(fmt.Sprintf("unsupported type %T", val)) @@ -1825,7 +1850,7 @@ func (p1 *P1) MultAssign(scalarIf interface{}, optional ...int) *P1 { if len(optional) > 0 { nbits = optional[0] } - C.blst_p1_mult(p1, p1, scalar, C.size_t(nbits)) + C.blst_p1_mult(&p1.cgo, &p1.cgo, scalar, C.size_t(nbits)) return p1 } @@ -1837,9 +1862,9 @@ func (p1 *P1) Mult(scalarIf interface{}, optional ...int) *P1 { func (p1 *P1) AddAssign(pointIf interface{}) *P1 { switch val := pointIf.(type) { case *P1: - C.blst_p1_add_or_double(p1, p1, val) + C.blst_p1_add_or_double(&p1.cgo, &p1.cgo, &val.cgo) case *P1Affine: - C.blst_p1_add_or_double_affine(p1, p1, val) + C.blst_p1_add_or_double_affine(&p1.cgo, &p1.cgo, &val.cgo) default: panic(fmt.Sprintf("unsupported type %T", val)) } @@ -1852,19 +1877,19 @@ func (p1 *P1) Add(pointIf interface{}) *P1 { } func (p1 *P1) SubAssign(pointIf interface{}) *P1 { - var x *Fp + var x *C.blst_fp var affine C.bool switch val := pointIf.(type) { case *P1: - x = &val.x + x = &val.cgo.x affine = false case *P1Affine: - x = &val.x + x = &val.cgo.x affine = true default: panic(fmt.Sprintf("unsupported type %T", val)) } - C.go_p1_sub_assign(p1, x, affine) + C.go_p1_sub_assign(&p1.cgo, x, affine) return p1 } @@ -1882,15 +1907,15 @@ func P1Generator() *P1 { // group generator point" func (acc *P1) MultNAccumulate(pointIf interface{}, scalarIf interface{}, optional ...int) *P1 { - var x *Fp + var x *C.blst_fp var affine C.bool if pointIf != nil { switch val := pointIf.(type) { case *P1: - x = &val.x + x = &val.cgo.x affine = false case *P1Affine: - x = &val.x + x = &val.cgo.x affine = true default: panic(fmt.Sprintf("unsupported type %T", val)) @@ -1903,7 +1928,7 @@ func (acc *P1) MultNAccumulate(pointIf interface{}, scalarIf interface{}, scalar = (*C.byte)(&val[0]) nbits = len(val) * 8 case *Scalar: - scalar = &val.b[0] + scalar = &val.cgo.b[0] nbits = 255 default: panic(fmt.Sprintf("unsupported type %T", val)) @@ -1911,7 +1936,7 @@ func (acc *P1) MultNAccumulate(pointIf interface{}, scalarIf interface{}, if len(optional) > 0 { nbits = optional[0] } - C.go_p1_mult_n_acc(acc, x, affine, scalar, C.size_t(nbits)) + C.go_p1_mult_n_acc(&acc.cgo, x, affine, scalar, C.size_t(nbits)) return acc } @@ -1921,12 +1946,12 @@ func (acc *P1) MultNAccumulate(pointIf interface{}, scalarIf interface{}, func (p *P1) ToAffine() *P1Affine { var pa P1Affine - C.blst_p1_to_affine(&pa, p) + C.blst_p1_to_affine(&pa.cgo, &p.cgo) return &pa } func (p *P1) FromAffine(pa *P1Affine) { - C.blst_p1_from_affine(p, pa) + C.blst_p1_from_affine(&p.cgo, &pa.cgo) } // Hash @@ -1939,7 +1964,7 @@ func HashToG1(msg []byte, dst []byte, aug = optional[0] } - C.blst_hash_to_g1(&q, ptrOrNil(msg), C.size_t(len(msg)), + C.blst_hash_to_g1(&q.cgo, ptrOrNil(msg), C.size_t(len(msg)), ptrOrNil(dst), C.size_t(len(dst)), ptrOrNil(aug), C.size_t(len(aug))) return &q @@ -1954,7 +1979,7 @@ func EncodeToG1(msg []byte, dst []byte, aug = optional[0] } - C.blst_encode_to_g1(&q, ptrOrNil(msg), C.size_t(len(msg)), + C.blst_encode_to_g1(&q.cgo, ptrOrNil(msg), C.size_t(len(msg)), ptrOrNil(dst), C.size_t(len(dst)), ptrOrNil(aug), C.size_t(len(aug))) return &q @@ -1973,7 +1998,8 @@ func P1sToAffine(points []*P1, optional ...int) P1Affines { } ret := make([]P1Affine, npoints) _cgoCheckPointer := func(...interface{}) {} - C.blst_p1s_to_affine(&ret[0], &points[0], C.size_t(npoints)) + C.blst_p1s_to_affine(&ret[0].cgo, (**C.blst_p1)(unsafe.Pointer(&points[0])), + C.size_t(npoints)) return ret } @@ -1991,7 +2017,7 @@ func (points P1s) ToAffine(optional ...P1Affines) P1Affines { } if maxProcs < 2 || npoints < 768 { - C.go_p1slice_to_affine(&ret[0], &points[0], C.size_t(npoints)) + C.go_p1slice_to_affine(&ret[0].cgo, &points[0].cgo, C.size_t(npoints)) return ret } @@ -2009,7 +2035,7 @@ func (points P1s) ToAffine(optional ...P1Affines) P1Affines { } rem -= 1 go func(out *P1Affine, inp *P1, delta int) { - C.go_p1slice_to_affine(out, inp, C.size_t(delta)) + C.go_p1slice_to_affine(&out.cgo, &inp.cgo, C.size_t(delta)) wg.Done() }(&ret[x], &points[x], delta) } @@ -2031,7 +2057,8 @@ func P1AffinesAdd(points []*P1Affine, optional ...int) *P1 { } var ret P1 _cgoCheckPointer := func(...interface{}) {} - C.blst_p1s_add(&ret, &points[0], C.size_t(npoints)) + C.blst_p1s_add(&ret.cgo, (**C.blst_p1_affine)(unsafe.Pointer(&points[0])), + C.size_t(npoints)) return &ret } @@ -2039,7 +2066,7 @@ func (points P1Affines) Add() *P1 { npoints := len(points) if maxProcs < 2 || npoints < 768 { var ret P1 - C.go_p1slice_add(&ret, &points[0], C.size_t(npoints)) + C.go_p1slice_add(&ret.cgo, &points[0].cgo, C.size_t(npoints)) return &ret } @@ -2057,7 +2084,7 @@ func (points P1Affines) Add() *P1 { rem -= 1 go func(points *P1Affine, delta int) { var ret P1 - C.go_p1slice_add(&ret, points, C.size_t(delta)) + C.go_p1slice_add(&ret.cgo, &points.cgo, C.size_t(delta)) msgs <- ret }(&points[x], delta) } @@ -2065,7 +2092,7 @@ func (points P1Affines) Add() *P1 { ret := <-msgs for i := 1; i < nslices; i++ { msg := <-msgs - C.blst_p1_add_or_double(&ret, &ret, &msg) + C.blst_p1_add_or_double(&ret.cgo, &ret.cgo, &msg.cgo) } return &ret } @@ -2113,7 +2140,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { if nbits <= 248 { scalars = make([]*C.byte, npoints) for i := range scalars { - scalars[i] = &val[i].b[0] + scalars[i] = &val[i].cgo.b[0] } } case []*Scalar: @@ -2122,7 +2149,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { } scalars = make([]*C.byte, npoints) for i := range scalars { - scalars[i] = &val[i].b[0] + scalars[i] = &val[i].cgo.b[0] } default: panic(fmt.Sprintf("unsupported type %T", val)) @@ -2134,16 +2161,16 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { sz := int(C.blst_p1s_mult_pippenger_scratch_sizeof(C.size_t(npoints))) / 8 scratch := make([]uint64, sz) - pointsBySlice := [2]*P1Affine{nil, nil} - var p_points **P1Affine + pointsBySlice := [2]*C.blst_p1_affine{nil, nil} + var p_points **C.blst_p1_affine switch val := pointsIf.(type) { case []*P1Affine: - p_points = &val[0] + p_points = (**C.blst_p1_affine)(unsafe.Pointer(&val[0])) case []P1Affine: - pointsBySlice[0] = &val[0] + pointsBySlice[0] = &val[0].cgo p_points = &pointsBySlice[0] case P1Affines: - pointsBySlice[0] = &val[0] + pointsBySlice[0] = &val[0].cgo p_points = &pointsBySlice[0] } @@ -2157,7 +2184,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { p_scalars = &scalars[0] case []Scalar: if nbits > 248 { - scalarsBySlice[0] = &val[0].b[0] + scalarsBySlice[0] = &val[0].cgo.b[0] p_scalars = &scalarsBySlice[0] } else { p_scalars = &scalars[0] @@ -2168,7 +2195,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { var ret P1 _cgoCheckPointer := func(...interface{}) {} - C.blst_p1s_mult_pippenger(&ret, p_points, C.size_t(npoints), + C.blst_p1s_mult_pippenger(&ret.cgo, p_points, C.size_t(npoints), p_scalars, C.size_t(nbits), (*C.limb_t)(&scratch[0])) @@ -2215,7 +2242,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { scalar = scalars[workItem] case []Scalar: if nbits > 248 { - scalar = &val[workItem].b[0] + scalar = &val[workItem].cgo.b[0] } else { scalar = scalars[workItem] } @@ -2223,7 +2250,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { scalar = scalars[workItem] } - C.go_p1_mult_n_acc(&acc, &point.x, true, + C.go_p1_mult_n_acc(&acc.cgo, &point.cgo.x, true, scalar, C.size_t(nbits)) } @@ -2234,7 +2261,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { ret := <-msgs for tid := 1; tid < numThreads; tid++ { point := <-msgs - C.blst_p1_add_or_double(&ret, &ret, &point) + C.blst_p1_add_or_double(&ret.cgo, &ret.cgo, &point.cgo) } for i := range scalars { @@ -2288,7 +2315,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { for tid := 0; tid < numThreads; tid++ { go func() { scratch := make([]uint64, sz< 248 { - scalarsBySlice[0] = &val[x].b[0] + scalarsBySlice[0] = &val[x].cgo.b[0] p_scalars = &scalarsBySlice[0] } else { p_scalars = &scalars[x] @@ -2331,7 +2358,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { p_scalars = &scalars[x] } - C.blst_p1s_tile_pippenger(&grid[workItem].point, + C.blst_p1s_tile_pippenger(&grid[workItem].point.cgo, p_points, C.size_t(grid[workItem].dx), p_scalars, C.size_t(nbits), (*C.limb_t)(&scratch[0]), @@ -2357,14 +2384,14 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { rows[y/window] = true // mark the "row" for grid[row].y == y { // if it's current "row", process it for row < total && grid[row].y == y { - C.blst_p1_add_or_double(&ret, &ret, &grid[row].point) + C.blst_p1_add_or_double(&ret.cgo, &ret.cgo, &grid[row].point.cgo) row++ } if y == 0 { break // one can as well 'return &ret' here } for j := 0; j < window; j++ { - C.blst_p1_double(&ret, &ret) + C.blst_p1_double(&ret.cgo, &ret.cgo) } y -= window if !rows[y/window] { // see if next "row" was marked already @@ -2422,7 +2449,7 @@ func P1AffinesValidate(pointsIf interface{}) bool { panic(fmt.Sprintf("unsupported type %T", val)) } - if !C.go_p1_affine_validate(point, true) { + if !C.go_p1_affine_validate(&point.cgo, true) { return false } } @@ -2457,7 +2484,7 @@ func P1AffinesValidate(pointsIf interface{}) bool { panic(fmt.Sprintf("unsupported type %T", val)) } - if !C.go_p1_affine_validate(point, true) { + if !C.go_p1_affine_validate(&point.cgo, true) { atomic.StoreInt32(&valid, 0) break } @@ -2484,8 +2511,8 @@ func PairingAggregatePkInG2(ctx Pairing, PK *P2Affine, pkValidate bool, } r := C.blst_pairing_chk_n_aggr_pk_in_g2(&ctx[0], - PK, C.bool(pkValidate), - sig, C.bool(sigGroupcheck), + PK.asPtr(), C.bool(pkValidate), + sig.asPtr(), C.bool(sigGroupcheck), ptrOrNil(msg), C.size_t(len(msg)), ptrOrNil(aug), C.size_t(len(aug))) @@ -2502,9 +2529,9 @@ func PairingMulNAggregatePkInG2(ctx Pairing, PK *P2Affine, pkValidate bool, } r := C.blst_pairing_chk_n_mul_n_aggr_pk_in_g2(&ctx[0], - PK, C.bool(pkValidate), - sig, C.bool(sigGroupcheck), - &rand.b[0], C.size_t(randBits), + PK.asPtr(), C.bool(pkValidate), + sig.asPtr(), C.bool(sigGroupcheck), + &rand.cgo.b[0], C.size_t(randBits), ptrOrNil(msg), C.size_t(len(msg)), ptrOrNil(aug), C.size_t(len(aug))) @@ -2518,7 +2545,7 @@ func PairingMulNAggregatePkInG2(ctx Pairing, PK *P2Affine, pkValidate bool, // P2 Serdes func (p2 *P2Affine) Serialize() []byte { var out [BLST_P2_SERIALIZE_BYTES]byte - C.blst_p2_affine_serialize((*C.byte)(&out[0]), p2) + C.blst_p2_affine_serialize((*C.byte)(&out[0]), &p2.cgo) return out[:] } @@ -2526,14 +2553,14 @@ func (p2 *P2Affine) Deserialize(in []byte) *P2Affine { if len(in) != BLST_P2_SERIALIZE_BYTES { return nil } - if C.blst_p2_deserialize(p2, (*C.byte)(&in[0])) != C.BLST_SUCCESS { + if C.blst_p2_deserialize(&p2.cgo, (*C.byte)(&in[0])) != C.BLST_SUCCESS { return nil } return p2 } func (p2 *P2Affine) Compress() []byte { var out [BLST_P2_COMPRESS_BYTES]byte - C.blst_p2_affine_compress((*C.byte)(&out[0]), p2) + C.blst_p2_affine_compress((*C.byte)(&out[0]), &p2.cgo) return out[:] } @@ -2541,14 +2568,14 @@ func (p2 *P2Affine) Uncompress(in []byte) *P2Affine { if len(in) != BLST_P2_COMPRESS_BYTES { return nil } - if C.blst_p2_uncompress(p2, (*C.byte)(&in[0])) != C.BLST_SUCCESS { + if C.blst_p2_uncompress(&p2.cgo, (*C.byte)(&in[0])) != C.BLST_SUCCESS { return nil } return p2 } func (p2 *P2Affine) InG2() bool { - return bool(C.blst_p2_affine_in_g2(p2)) + return bool(C.blst_p2_affine_in_g2(&p2.cgo)) } func (_ *P2Affine) BatchUncompress(in [][]byte) []*P2Affine { @@ -2605,12 +2632,12 @@ func (_ *P2Affine) BatchUncompress(in [][]byte) []*P2Affine { func (p2 *P2) Serialize() []byte { var out [BLST_P2_SERIALIZE_BYTES]byte - C.blst_p2_serialize((*C.byte)(&out[0]), p2) + C.blst_p2_serialize((*C.byte)(&out[0]), &p2.cgo) return out[:] } func (p2 *P2) Compress() []byte { var out [BLST_P2_COMPRESS_BYTES]byte - C.blst_p2_compress((*C.byte)(&out[0]), p2) + C.blst_p2_compress((*C.byte)(&out[0]), &p2.cgo) return out[:] } @@ -2622,7 +2649,7 @@ func (p2 *P2) MultAssign(scalarIf interface{}, optional ...int) *P2 { scalar = (*C.byte)(&val[0]) nbits = len(val) * 8 case *Scalar: - scalar = &val.b[0] + scalar = &val.cgo.b[0] nbits = 255 default: panic(fmt.Sprintf("unsupported type %T", val)) @@ -2630,7 +2657,7 @@ func (p2 *P2) MultAssign(scalarIf interface{}, optional ...int) *P2 { if len(optional) > 0 { nbits = optional[0] } - C.blst_p2_mult(p2, p2, scalar, C.size_t(nbits)) + C.blst_p2_mult(&p2.cgo, &p2.cgo, scalar, C.size_t(nbits)) return p2 } @@ -2642,9 +2669,9 @@ func (p2 *P2) Mult(scalarIf interface{}, optional ...int) *P2 { func (p2 *P2) AddAssign(pointIf interface{}) *P2 { switch val := pointIf.(type) { case *P2: - C.blst_p2_add_or_double(p2, p2, val) + C.blst_p2_add_or_double(&p2.cgo, &p2.cgo, &val.cgo) case *P2Affine: - C.blst_p2_add_or_double_affine(p2, p2, val) + C.blst_p2_add_or_double_affine(&p2.cgo, &p2.cgo, &val.cgo) default: panic(fmt.Sprintf("unsupported type %T", val)) } @@ -2657,19 +2684,19 @@ func (p2 *P2) Add(pointIf interface{}) *P2 { } func (p2 *P2) SubAssign(pointIf interface{}) *P2 { - var x *Fp2 + var x *C.blst_fp2 var affine C.bool switch val := pointIf.(type) { case *P2: - x = &val.x + x = &val.cgo.x affine = false case *P2Affine: - x = &val.x + x = &val.cgo.x affine = true default: panic(fmt.Sprintf("unsupported type %T", val)) } - C.go_p2_sub_assign(p2, x, affine) + C.go_p2_sub_assign(&p2.cgo, x, affine) return p2 } @@ -2687,15 +2714,15 @@ func P2Generator() *P2 { // group generator point" func (acc *P2) MultNAccumulate(pointIf interface{}, scalarIf interface{}, optional ...int) *P2 { - var x *Fp2 + var x *C.blst_fp2 var affine C.bool if pointIf != nil { switch val := pointIf.(type) { case *P2: - x = &val.x + x = &val.cgo.x affine = false case *P2Affine: - x = &val.x + x = &val.cgo.x affine = true default: panic(fmt.Sprintf("unsupported type %T", val)) @@ -2708,7 +2735,7 @@ func (acc *P2) MultNAccumulate(pointIf interface{}, scalarIf interface{}, scalar = (*C.byte)(&val[0]) nbits = len(val) * 8 case *Scalar: - scalar = &val.b[0] + scalar = &val.cgo.b[0] nbits = 255 default: panic(fmt.Sprintf("unsupported type %T", val)) @@ -2716,7 +2743,7 @@ func (acc *P2) MultNAccumulate(pointIf interface{}, scalarIf interface{}, if len(optional) > 0 { nbits = optional[0] } - C.go_p2_mult_n_acc(acc, x, affine, scalar, C.size_t(nbits)) + C.go_p2_mult_n_acc(&acc.cgo, x, affine, scalar, C.size_t(nbits)) return acc } @@ -2726,12 +2753,12 @@ func (acc *P2) MultNAccumulate(pointIf interface{}, scalarIf interface{}, func (p *P2) ToAffine() *P2Affine { var pa P2Affine - C.blst_p2_to_affine(&pa, p) + C.blst_p2_to_affine(&pa.cgo, &p.cgo) return &pa } func (p *P2) FromAffine(pa *P2Affine) { - C.blst_p2_from_affine(p, pa) + C.blst_p2_from_affine(&p.cgo, &pa.cgo) } // Hash @@ -2744,7 +2771,7 @@ func HashToG2(msg []byte, dst []byte, aug = optional[0] } - C.blst_hash_to_g2(&q, ptrOrNil(msg), C.size_t(len(msg)), + C.blst_hash_to_g2(&q.cgo, ptrOrNil(msg), C.size_t(len(msg)), ptrOrNil(dst), C.size_t(len(dst)), ptrOrNil(aug), C.size_t(len(aug))) return &q @@ -2759,7 +2786,7 @@ func EncodeToG2(msg []byte, dst []byte, aug = optional[0] } - C.blst_encode_to_g2(&q, ptrOrNil(msg), C.size_t(len(msg)), + C.blst_encode_to_g2(&q.cgo, ptrOrNil(msg), C.size_t(len(msg)), ptrOrNil(dst), C.size_t(len(dst)), ptrOrNil(aug), C.size_t(len(aug))) return &q @@ -2778,7 +2805,8 @@ func P2sToAffine(points []*P2, optional ...int) P2Affines { } ret := make([]P2Affine, npoints) _cgoCheckPointer := func(...interface{}) {} - C.blst_p2s_to_affine(&ret[0], &points[0], C.size_t(npoints)) + C.blst_p2s_to_affine(&ret[0].cgo, (**C.blst_p2)(unsafe.Pointer(&points[0])), + C.size_t(npoints)) return ret } @@ -2796,7 +2824,7 @@ func (points P2s) ToAffine(optional ...P2Affines) P2Affines { } if maxProcs < 2 || npoints < 768 { - C.go_p2slice_to_affine(&ret[0], &points[0], C.size_t(npoints)) + C.go_p2slice_to_affine(&ret[0].cgo, &points[0].cgo, C.size_t(npoints)) return ret } @@ -2814,7 +2842,7 @@ func (points P2s) ToAffine(optional ...P2Affines) P2Affines { } rem -= 1 go func(out *P2Affine, inp *P2, delta int) { - C.go_p2slice_to_affine(out, inp, C.size_t(delta)) + C.go_p2slice_to_affine(&out.cgo, &inp.cgo, C.size_t(delta)) wg.Done() }(&ret[x], &points[x], delta) } @@ -2836,7 +2864,8 @@ func P2AffinesAdd(points []*P2Affine, optional ...int) *P2 { } var ret P2 _cgoCheckPointer := func(...interface{}) {} - C.blst_p2s_add(&ret, &points[0], C.size_t(npoints)) + C.blst_p2s_add(&ret.cgo, (**C.blst_p2_affine)(unsafe.Pointer(&points[0])), + C.size_t(npoints)) return &ret } @@ -2844,7 +2873,7 @@ func (points P2Affines) Add() *P2 { npoints := len(points) if maxProcs < 2 || npoints < 768 { var ret P2 - C.go_p2slice_add(&ret, &points[0], C.size_t(npoints)) + C.go_p2slice_add(&ret.cgo, &points[0].cgo, C.size_t(npoints)) return &ret } @@ -2862,7 +2891,7 @@ func (points P2Affines) Add() *P2 { rem -= 1 go func(points *P2Affine, delta int) { var ret P2 - C.go_p2slice_add(&ret, points, C.size_t(delta)) + C.go_p2slice_add(&ret.cgo, &points.cgo, C.size_t(delta)) msgs <- ret }(&points[x], delta) } @@ -2870,7 +2899,7 @@ func (points P2Affines) Add() *P2 { ret := <-msgs for i := 1; i < nslices; i++ { msg := <-msgs - C.blst_p2_add_or_double(&ret, &ret, &msg) + C.blst_p2_add_or_double(&ret.cgo, &ret.cgo, &msg.cgo) } return &ret } @@ -2918,7 +2947,7 @@ func P2AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P2 { if nbits <= 248 { scalars = make([]*C.byte, npoints) for i := range scalars { - scalars[i] = &val[i].b[0] + scalars[i] = &val[i].cgo.b[0] } } case []*Scalar: @@ -2927,7 +2956,7 @@ func P2AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P2 { } scalars = make([]*C.byte, npoints) for i := range scalars { - scalars[i] = &val[i].b[0] + scalars[i] = &val[i].cgo.b[0] } default: panic(fmt.Sprintf("unsupported type %T", val)) @@ -2939,16 +2968,16 @@ func P2AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P2 { sz := int(C.blst_p2s_mult_pippenger_scratch_sizeof(C.size_t(npoints))) / 8 scratch := make([]uint64, sz) - pointsBySlice := [2]*P2Affine{nil, nil} - var p_points **P2Affine + pointsBySlice := [2]*C.blst_p2_affine{nil, nil} + var p_points **C.blst_p2_affine switch val := pointsIf.(type) { case []*P2Affine: - p_points = &val[0] + p_points = (**C.blst_p2_affine)(unsafe.Pointer(&val[0])) case []P2Affine: - pointsBySlice[0] = &val[0] + pointsBySlice[0] = &val[0].cgo p_points = &pointsBySlice[0] case P2Affines: - pointsBySlice[0] = &val[0] + pointsBySlice[0] = &val[0].cgo p_points = &pointsBySlice[0] } @@ -2962,7 +2991,7 @@ func P2AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P2 { p_scalars = &scalars[0] case []Scalar: if nbits > 248 { - scalarsBySlice[0] = &val[0].b[0] + scalarsBySlice[0] = &val[0].cgo.b[0] p_scalars = &scalarsBySlice[0] } else { p_scalars = &scalars[0] @@ -2973,7 +3002,7 @@ func P2AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P2 { var ret P2 _cgoCheckPointer := func(...interface{}) {} - C.blst_p2s_mult_pippenger(&ret, p_points, C.size_t(npoints), + C.blst_p2s_mult_pippenger(&ret.cgo, p_points, C.size_t(npoints), p_scalars, C.size_t(nbits), (*C.limb_t)(&scratch[0])) @@ -3020,7 +3049,7 @@ func P2AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P2 { scalar = scalars[workItem] case []Scalar: if nbits > 248 { - scalar = &val[workItem].b[0] + scalar = &val[workItem].cgo.b[0] } else { scalar = scalars[workItem] } @@ -3028,7 +3057,7 @@ func P2AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P2 { scalar = scalars[workItem] } - C.go_p2_mult_n_acc(&acc, &point.x, true, + C.go_p2_mult_n_acc(&acc.cgo, &point.cgo.x, true, scalar, C.size_t(nbits)) } @@ -3039,7 +3068,7 @@ func P2AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P2 { ret := <-msgs for tid := 1; tid < numThreads; tid++ { point := <-msgs - C.blst_p2_add_or_double(&ret, &ret, &point) + C.blst_p2_add_or_double(&ret.cgo, &ret.cgo, &point.cgo) } for i := range scalars { @@ -3093,7 +3122,7 @@ func P2AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P2 { for tid := 0; tid < numThreads; tid++ { go func() { scratch := make([]uint64, sz< 248 { - scalarsBySlice[0] = &val[x].b[0] + scalarsBySlice[0] = &val[x].cgo.b[0] p_scalars = &scalarsBySlice[0] } else { p_scalars = &scalars[x] @@ -3136,7 +3165,7 @@ func P2AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P2 { p_scalars = &scalars[x] } - C.blst_p2s_tile_pippenger(&grid[workItem].point, + C.blst_p2s_tile_pippenger(&grid[workItem].point.cgo, p_points, C.size_t(grid[workItem].dx), p_scalars, C.size_t(nbits), (*C.limb_t)(&scratch[0]), @@ -3162,14 +3191,14 @@ func P2AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P2 { rows[y/window] = true // mark the "row" for grid[row].y == y { // if it's current "row", process it for row < total && grid[row].y == y { - C.blst_p2_add_or_double(&ret, &ret, &grid[row].point) + C.blst_p2_add_or_double(&ret.cgo, &ret.cgo, &grid[row].point.cgo) row++ } if y == 0 { break // one can as well 'return &ret' here } for j := 0; j < window; j++ { - C.blst_p2_double(&ret, &ret) + C.blst_p2_double(&ret.cgo, &ret.cgo) } y -= window if !rows[y/window] { // see if next "row" was marked already @@ -3227,7 +3256,7 @@ func P2AffinesValidate(pointsIf interface{}) bool { panic(fmt.Sprintf("unsupported type %T", val)) } - if !C.go_p2_affine_validate(point, true) { + if !C.go_p2_affine_validate(&point.cgo, true) { return false } } @@ -3262,7 +3291,7 @@ func P2AffinesValidate(pointsIf interface{}) bool { panic(fmt.Sprintf("unsupported type %T", val)) } - if !C.go_p2_affine_validate(point, true) { + if !C.go_p2_affine_validate(&point.cgo, true) { atomic.StoreInt32(&valid, 0) break } @@ -3281,10 +3310,10 @@ func (points P2Affines) Validate() bool { return P2AffinesValidate(points) } -func parseOpts(optional ...interface{}) ([]byte, [][]byte, bool, bool) { - var aug [][]byte // For aggregate verify - var augSingle []byte // For signing - useHash := true // hash (true), encode (false) +// aug [][]byte - augmentation bytes for signing (default: nil) +func parseOpts(optional ...interface{}) (augSingle []byte, aug [][]byte, + useHash bool, ok bool) { + useHash = true // hash (true), encode (false) for _, arg := range optional { switch v := arg.(type) { @@ -3305,35 +3334,35 @@ func parseOpts(optional ...interface{}) ([]byte, [][]byte, bool, bool) { // reason they should be used primarily for prototyping with a goal to // formulate interfaces that would process multiple scalars per cgo call. func (a *Scalar) MulAssign(b *Scalar) (*Scalar, bool) { - return a, bool(C.blst_sk_mul_n_check(a, a, b)) + return a, bool(C.blst_sk_mul_n_check(&a.cgo, &a.cgo, &b.cgo)) } func (a *Scalar) Mul(b *Scalar) (*Scalar, bool) { var ret Scalar - return &ret, bool(C.blst_sk_mul_n_check(&ret, a, b)) + return &ret, bool(C.blst_sk_mul_n_check(&ret.cgo, &a.cgo, &b.cgo)) } func (a *Scalar) AddAssign(b *Scalar) (*Scalar, bool) { - return a, bool(C.blst_sk_add_n_check(a, a, b)) + return a, bool(C.blst_sk_add_n_check(&a.cgo, &a.cgo, &b.cgo)) } func (a *Scalar) Add(b *Scalar) (*Scalar, bool) { var ret Scalar - return &ret, bool(C.blst_sk_add_n_check(&ret, a, b)) + return &ret, bool(C.blst_sk_add_n_check(&ret.cgo, &a.cgo, &b.cgo)) } func (a *Scalar) SubAssign(b *Scalar) (*Scalar, bool) { - return a, bool(C.blst_sk_sub_n_check(a, a, b)) + return a, bool(C.blst_sk_sub_n_check(&a.cgo, &a.cgo, &b.cgo)) } func (a *Scalar) Sub(b *Scalar) (*Scalar, bool) { var ret Scalar - return &ret, bool(C.blst_sk_sub_n_check(&ret, a, b)) + return &ret, bool(C.blst_sk_sub_n_check(&ret.cgo, &a.cgo, &b.cgo)) } func (a *Scalar) Inverse() *Scalar { var ret Scalar - C.blst_sk_inverse(&ret, a) + C.blst_sk_inverse(&ret.cgo, &a.cgo) return &ret } @@ -3344,20 +3373,20 @@ func (a *Scalar) Inverse() *Scalar { // Scalar serdes func (s *Scalar) Serialize() []byte { var out [BLST_SCALAR_BYTES]byte - C.blst_bendian_from_scalar((*C.byte)(&out[0]), s) + C.blst_bendian_from_scalar((*C.byte)(&out[0]), &s.cgo) return out[:] } func (s *Scalar) Deserialize(in []byte) *Scalar { if len(in) != BLST_SCALAR_BYTES || - !C.go_scalar_from_bendian(s, (*C.byte)(&in[0])) { + !C.go_scalar_from_bendian(&s.cgo, (*C.byte)(&in[0])) { return nil } return s } func (s *Scalar) Valid() bool { - return bool(C.blst_sk_check(s)) + return bool(C.blst_sk_check(&s.cgo)) } func (s *Scalar) HashTo(msg []byte, dst []byte) bool { @@ -3372,7 +3401,7 @@ func (s *Scalar) HashTo(msg []byte, dst []byte) bool { func HashToScalar(msg []byte, dst []byte) *Scalar { var ret Scalar - if C.go_hash_to_scalar(&ret, ptrOrNil(msg), C.size_t(len(msg)), + if C.go_hash_to_scalar(&ret.cgo, ptrOrNil(msg), C.size_t(len(msg)), ptrOrNil(dst), C.size_t(len(dst))) { return &ret } @@ -3386,20 +3415,20 @@ func HashToScalar(msg []byte, dst []byte) *Scalar { func (fr *Scalar) ToLEndian() []byte { var arr [BLST_SCALAR_BYTES]byte - C.blst_lendian_from_scalar((*C.byte)(&arr[0]), fr) + C.blst_lendian_from_scalar((*C.byte)(&arr[0]), &fr.cgo) return arr[:] } func (fp *Fp) ToLEndian() []byte { var arr [BLST_FP_BYTES]byte - C.blst_lendian_from_fp((*C.byte)(&arr[0]), fp) + C.blst_lendian_from_fp((*C.byte)(&arr[0]), &fp.cgo) return arr[:] } func (fr *Scalar) FromLEndian(arr []byte) *Scalar { nbytes := len(arr) if nbytes < BLST_SCALAR_BYTES || - !C.blst_scalar_from_le_bytes(fr, (*C.byte)(&arr[0]), C.size_t(nbytes)) { + !C.blst_scalar_from_le_bytes(&fr.cgo, (*C.byte)(&arr[0]), C.size_t(nbytes)) { return nil } return fr @@ -3409,7 +3438,7 @@ func (fp *Fp) FromLEndian(arr []byte) *Fp { if len(arr) != BLST_FP_BYTES { return nil } - C.blst_fp_from_lendian(fp, (*C.byte)(&arr[0])) + C.blst_fp_from_lendian(&fp.cgo, (*C.byte)(&arr[0])) return fp } @@ -3419,20 +3448,20 @@ func (fp *Fp) FromLEndian(arr []byte) *Fp { func (fr *Scalar) ToBEndian() []byte { var arr [BLST_SCALAR_BYTES]byte - C.blst_bendian_from_scalar((*C.byte)(&arr[0]), fr) + C.blst_bendian_from_scalar((*C.byte)(&arr[0]), &fr.cgo) return arr[:] } func (fp *Fp) ToBEndian() []byte { var arr [BLST_FP_BYTES]byte - C.blst_bendian_from_fp((*C.byte)(&arr[0]), fp) + C.blst_bendian_from_fp((*C.byte)(&arr[0]), &fp.cgo) return arr[:] } func (fr *Scalar) FromBEndian(arr []byte) *Scalar { nbytes := len(arr) if nbytes < BLST_SCALAR_BYTES || - !C.blst_scalar_from_be_bytes(fr, (*C.byte)(&arr[0]), C.size_t(nbytes)) { + !C.blst_scalar_from_be_bytes(&fr.cgo, (*C.byte)(&arr[0]), C.size_t(nbytes)) { return nil } return fr @@ -3442,7 +3471,7 @@ func (fp *Fp) FromBEndian(arr []byte) *Fp { if len(arr) != BLST_FP_BYTES { return nil } - C.blst_fp_from_bendian(fp, (*C.byte)(&arr[0])) + C.blst_fp_from_bendian(&fp.cgo, (*C.byte)(&arr[0])) return fp } @@ -3461,9 +3490,11 @@ func (s *Scalar) Print(name string) { func (p *P1Affine) Print(name string) { fmt.Printf("%s:\n", name) - arr := p.x.ToBEndian() + x := Fp{p.cgo.x} + arr := x.ToBEndian() PrintBytes(arr, " x") - arr = p.y.ToBEndian() + y := Fp{p.cgo.y} + arr = y.ToBEndian() PrintBytes(arr, " y") } @@ -3475,16 +3506,19 @@ func (p *P1) Print(name string) { func (f *Fp2) Print(name string) { fmt.Printf("%s:\n", name) - arr := f.fp[0].ToBEndian() - PrintBytes(arr, " 0") - arr = f.fp[1].ToBEndian() - PrintBytes(arr, " 1") + var arr [BLST_FP_BYTES]byte + C.blst_bendian_from_fp((*C.byte)(&arr[0]), &f.cgo.fp[0]) + PrintBytes(arr[:], " 0") + C.blst_bendian_from_fp((*C.byte)(&arr[0]), &f.cgo.fp[1]) + PrintBytes(arr[:], " 1") } func (p *P2Affine) Print(name string) { fmt.Printf("%s:\n", name) - p.x.Print(" x") - p.y.Print(" y") + x := Fp2{p.cgo.x} + x.Print(" x") + y := Fp2{p.cgo.y} + y.Print(" y") } func (p *P2) Print(name string) { @@ -3510,19 +3544,19 @@ func (e1 *Fp2) Equals(e2 *Fp2) bool { } func (e1 *P1Affine) Equals(e2 *P1Affine) bool { - return bool(C.blst_p1_affine_is_equal(e1, e2)) + return bool(C.blst_p1_affine_is_equal(&e1.cgo, &e2.cgo)) } func (e1 *P1) Equals(e2 *P1) bool { - return bool(C.blst_p1_is_equal(e1, e2)) + return bool(C.blst_p1_is_equal(&e1.cgo, &e2.cgo)) } func (e1 *P2Affine) Equals(e2 *P2Affine) bool { - return bool(C.blst_p2_affine_is_equal(e1, e2)) + return bool(C.blst_p2_affine_is_equal(&e1.cgo, &e2.cgo)) } func (e1 *P2) Equals(e2 *P2) bool { - return bool(C.blst_p2_is_equal(e1, e2)) + return bool(C.blst_p2_is_equal(&e1.cgo, &e2.cgo)) } // private thunk for testing diff --git a/vendor/github.com/supranational/blst/bindings/go/blst.tgo b/vendor/github.com/supranational/blst/bindings/go/blst.tgo index 947089c34f..bcfd735a09 100644 --- a/vendor/github.com/supranational/blst/bindings/go/blst.tgo +++ b/vendor/github.com/supranational/blst/bindings/go/blst.tgo @@ -158,15 +158,15 @@ const BLST_P1_SERIALIZE_BYTES = BLST_FP_BYTES * 2 const BLST_P2_COMPRESS_BYTES = BLST_FP_BYTES * 2 const BLST_P2_SERIALIZE_BYTES = BLST_FP_BYTES * 4 -type Scalar = C.blst_scalar -type Fp = C.blst_fp -type Fp2 = C.blst_fp2 +type Scalar struct{ cgo C.blst_scalar } +type Fp struct{ cgo C.blst_fp } +type Fp2 struct{ cgo C.blst_fp2 } type Fp6 = C.blst_fp6 -type Fp12 = C.blst_fp12 -type P1 = C.blst_p1 -type P2 = C.blst_p2 -type P1Affine = C.blst_p1_affine -type P2Affine = C.blst_p2_affine +type Fp12 struct{ cgo C.blst_fp12 } +type P1 struct{ cgo C.blst_p1 } +type P2 struct{ cgo C.blst_p2 } +type P1Affine struct{ cgo C.blst_p1_affine } +type P2Affine struct{ cgo C.blst_p2_affine } type Message = []byte type Pairing = []C.blst_pairing type SecretKey = Scalar @@ -195,11 +195,11 @@ func initMaxProcs() int { return maxProcs } -func SetMaxProcs(max int) { - if max <= 0 { - max = 1 +func SetMaxProcs(procs int) { + if procs <= 0 { + procs = 1 } - maxProcs = max + maxProcs = procs } func numThreads(maxThreads int) int { @@ -219,9 +219,9 @@ func numThreads(maxThreads int) int { } var cgo_pairingSizeOf = C.blst_pairing_sizeof() -var cgo_p1Generator = *C.blst_p1_generator() -var cgo_p2Generator = *C.blst_p2_generator() -var cgo_fp12One = *C.blst_fp12_one() +var cgo_p1Generator = P1{*C.blst_p1_generator()} +var cgo_p2Generator = P2{*C.blst_p2_generator()} +var cgo_fp12One = Fp12{*C.blst_fp12_one()} // // Secret key @@ -240,8 +240,8 @@ func KeyGen(ikm []byte, optional ...[]byte) *SecretKey { if len(ikm) < 32 { return nil } - C.blst_keygen(&sk, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), - ptrOrNil(info), C.size_t(len(info))) + C.blst_keygen(&sk.cgo, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), + ptrOrNil(info), C.size_t(len(info))) // Postponing secret key zeroing till garbage collection can be too // late to be effective, but every little bit helps... runtime.SetFinalizer(&sk, func(sk *SecretKey) { sk.Zeroize() }) @@ -257,8 +257,8 @@ func KeyGenV3(ikm []byte, optional ...[]byte) *SecretKey { if len(optional) > 0 { info = optional[0] } - C.blst_keygen_v3(&sk, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), - ptrOrNil(info), C.size_t(len(info))) + C.blst_keygen_v3(&sk.cgo, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), + ptrOrNil(info), C.size_t(len(info))) // Postponing secret key zeroing till garbage collection can be too // late to be effective, but every little bit helps... runtime.SetFinalizer(&sk, func(sk *SecretKey) { sk.Zeroize() }) @@ -274,9 +274,9 @@ func KeyGenV45(ikm []byte, salt []byte, optional ...[]byte) *SecretKey { if len(optional) > 0 { info = optional[0] } - C.blst_keygen_v4_5(&sk, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), - (*C.byte)(&salt[0]), C.size_t(len(salt)), - ptrOrNil(info), C.size_t(len(info))) + C.blst_keygen_v4_5(&sk.cgo, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), + (*C.byte)(&salt[0]), C.size_t(len(salt)), + ptrOrNil(info), C.size_t(len(info))) // Postponing secret key zeroing till garbage collection can be too // late to be effective, but every little bit helps... runtime.SetFinalizer(&sk, func(sk *SecretKey) { sk.Zeroize() }) @@ -292,9 +292,9 @@ func KeyGenV5(ikm []byte, salt []byte, optional ...[]byte) *SecretKey { if len(optional) > 0 { info = optional[0] } - C.blst_keygen_v5(&sk, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), - (*C.byte)(&salt[0]), C.size_t(len(salt)), - ptrOrNil(info), C.size_t(len(info))) + C.blst_keygen_v5(&sk.cgo, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), + (*C.byte)(&salt[0]), C.size_t(len(salt)), + ptrOrNil(info), C.size_t(len(info))) // Postponing secret key zeroing till garbage collection can be too // late to be effective, but every little bit helps... runtime.SetFinalizer(&sk, func(sk *SecretKey) { sk.Zeroize() }) @@ -306,7 +306,7 @@ func DeriveMasterEip2333(ikm []byte) *SecretKey { return nil } var sk SecretKey - C.blst_derive_master_eip2333(&sk, (*C.byte)(&ikm[0]), C.size_t(len(ikm))) + C.blst_derive_master_eip2333(&sk.cgo, (*C.byte)(&ikm[0]), C.size_t(len(ikm))) // Postponing secret key zeroing till garbage collection can be too // late to be effective, but every little bit helps... runtime.SetFinalizer(&sk, func(sk *SecretKey) { sk.Zeroize() }) @@ -315,7 +315,7 @@ func DeriveMasterEip2333(ikm []byte) *SecretKey { func (master *SecretKey) DeriveChildEip2333(child_index uint32) *SecretKey { var sk SecretKey - C.blst_derive_child_eip2333(&sk, master, C.uint(child_index)) + C.blst_derive_child_eip2333(&sk.cgo, &master.cgo, C.uint(child_index)) // Postponing secret key zeroing till garbage collection can be too // late to be effective, but every little bit helps... runtime.SetFinalizer(&sk, func(sk *SecretKey) { sk.Zeroize() }) @@ -350,30 +350,38 @@ func PairingFinalVerify(ctx Pairing, optional ...*Fp12) bool { if len(optional) > 0 { gtsig = optional[0] } - return bool(C.blst_pairing_finalverify(&ctx[0], gtsig)) + return bool(C.blst_pairing_finalverify(&ctx[0], gtsig.asPtr())) } func PairingRawAggregate(ctx Pairing, q *P2Affine, p *P1Affine) { - C.blst_pairing_raw_aggregate(&ctx[0], q, p) + C.blst_pairing_raw_aggregate(&ctx[0], &q.cgo, &p.cgo) } func PairingAsFp12(ctx Pairing) *Fp12 { var pt Fp12 - C.go_pairing_as_fp12(&pt, &ctx[0]) + C.go_pairing_as_fp12(&pt.cgo, &ctx[0]) return &pt } +func (pt *Fp12) asPtr() *C.blst_fp12 { + if (pt != nil) { + return &pt.cgo + } + + return nil +} + func Fp12One() Fp12 { return cgo_fp12One } func Fp12FinalVerify(pt1 *Fp12, pt2 *Fp12) bool { - return bool(C.blst_fp12_finalverify(pt1, pt2)) + return bool(C.blst_fp12_finalverify(&pt1.cgo, &pt2.cgo)) } func Fp12MillerLoop(q *P2Affine, p *P1Affine) *Fp12 { var pt Fp12 - C.blst_miller_loop(&pt, q, p) + C.blst_miller_loop(&pt.cgo, &q.cgo, &p.cgo) return &pt } @@ -387,7 +395,7 @@ func Fp12MillerLoopN(qs []P2Affine, ps []P1Affine) *Fp12 { if nThreads == 1 || nElems == 1 { var pt Fp12 - C.go_miller_loop_n(&pt, &qs[0], &ps[0], C.size_t(nElems), false) + C.go_miller_loop_n(&pt.cgo, &qs[0].cgo, &ps[0].cgo, C.size_t(nElems), false) return &pt } @@ -417,7 +425,7 @@ func Fp12MillerLoopN(qs []P2Affine, ps []P1Affine) *Fp12 { if n > stride { n = stride } - C.go_miller_loop_n(&acc, &qs[work], &ps[work], C.size_t(n), + C.go_miller_loop_n(&acc.cgo, &qs[work].cgo, &ps[work].cgo, C.size_t(n), C.bool(!first)) first = false } @@ -431,25 +439,25 @@ func Fp12MillerLoopN(qs []P2Affine, ps []P1Affine) *Fp12 { } var pt Fp12 - C.go_fp12slice_mul(&pt, &ret[0], C.size_t(nThreads)) + C.go_fp12slice_mul(&pt.cgo, &ret[0].cgo, C.size_t(nThreads)) return &pt } func (pt *Fp12) MulAssign(p *Fp12) { - C.blst_fp12_mul(pt, pt, p) + C.blst_fp12_mul(&pt.cgo, &pt.cgo, &p.cgo) } func (pt *Fp12) FinalExp() { - C.blst_final_exp(pt, pt) + C.blst_final_exp(&pt.cgo, &pt.cgo) } func (pt *Fp12) InGroup() bool { - return bool(C.blst_fp12_in_group(pt)) + return bool(C.blst_fp12_in_group(&pt.cgo)) } func (pt *Fp12) ToBendian() []byte { var out [BLST_FP_BYTES*12]byte - C.blst_bendian_from_fp12((*C.byte)(&out[0]), pt) + C.blst_bendian_from_fp12((*C.byte)(&out[0]), &pt.cgo) return out[:] } diff --git a/vendor/github.com/supranational/blst/bindings/go/blst_minpk.tgo b/vendor/github.com/supranational/blst/bindings/go/blst_minpk.tgo index 7d329bbc23..2615ae4a78 100644 --- a/vendor/github.com/supranational/blst/bindings/go/blst_minpk.tgo +++ b/vendor/github.com/supranational/blst/bindings/go/blst_minpk.tgo @@ -9,13 +9,21 @@ import ( // PublicKey // +func (pt *P1Affine) asPtr() *C.blst_p1_affine { + if (pt != nil) { + return &pt.cgo + } + + return nil +} + func (pk *P1Affine) From(s *Scalar) *P1Affine { - C.blst_sk_to_pk2_in_g1(nil, pk, s) + C.blst_sk_to_pk2_in_g1(nil, &pk.cgo, &s.cgo) return pk } func (pk *P1Affine) KeyValidate() bool { - return bool(C.go_p1_affine_validate(pk, true)) + return bool(C.go_p1_affine_validate(&pk.cgo, true)) } // sigInfcheck, check for infinity, is a way to avoid going @@ -23,7 +31,7 @@ func (pk *P1Affine) KeyValidate() bool { // always cryptographically safe, but application might want // to guard against obviously bogus individual[!] signatures. func (sig *P2Affine) SigValidate(sigInfcheck bool) bool { - return bool(C.go_p2_affine_validate(sig, C.bool(sigInfcheck))) + return bool(C.go_p2_affine_validate(&sig.cgo, C.bool(sigInfcheck))) } // @@ -43,7 +51,7 @@ func (sig *P2Affine) Sign(sk *SecretKey, msg []byte, dst []byte, } else { q = EncodeToG2(msg, dst, augSingle) } - C.blst_sign_pk2_in_g1(nil, sig, q, sk) + C.blst_sign_pk2_in_g1(nil, &sig.cgo, &q.cgo, &sk.cgo) return sig } @@ -247,7 +255,7 @@ func coreAggregateVerifyPkInG1(sigFn sigGetterP2, sigGroupcheck bool, atomic.StoreInt32(&valid, 0) } if atomic.LoadInt32(&valid) > 0 { - C.blst_aggregated_in_g2(>sig, sig) + C.blst_aggregated_in_g2(>sig.cgo, &sig.cgo) } mutex.Unlock() @@ -295,7 +303,7 @@ func CoreVerifyPkInG1(pk *P1Affine, sig *P2Affine, hash_or_encode bool, return C.BLST_SUCCESS } - return int(C.blst_core_verify_pk_in_g1(pk, sig, C.bool(hash_or_encode), + return int(C.blst_core_verify_pk_in_g1(&pk.cgo, &sig.cgo, C.bool(hash_or_encode), ptrOrNil(msg), C.size_t(len(msg)), ptrOrNil(dst), C.size_t(len(dst)), ptrOrNil(aug), C.size_t(len(aug)))) @@ -489,19 +497,19 @@ func (agg *P2Aggregate) AddAggregate(other *P2Aggregate) { } else if agg.v == nil { agg.v = other.v } else { - C.blst_p2_add_or_double(agg.v, agg.v, other.v) + C.blst_p2_add_or_double(&agg.v.cgo, &agg.v.cgo, &other.v.cgo) } } func (agg *P2Aggregate) Add(elmt *P2Affine, groupcheck bool) bool { - if groupcheck && !bool(C.blst_p2_affine_in_g2(elmt)) { + if groupcheck && !bool(C.blst_p2_affine_in_g2(&elmt.cgo)) { return false } if agg.v == nil { agg.v = new(P2) - C.blst_p2_from_affine(agg.v, elmt) + C.blst_p2_from_affine(&agg.v.cgo, &elmt.cgo) } else { - C.blst_p2_add_or_double_affine(agg.v, agg.v, elmt) + C.blst_p2_add_or_double_affine(&agg.v.cgo, &agg.v.cgo, &elmt.cgo) } return true } @@ -551,15 +559,15 @@ func (agg *P2Aggregate) coreAggregate(getter aggGetterP2, groupcheck bool, atomic.StoreInt32(&valid, 0) break } - if groupcheck && !bool(C.blst_p2_affine_in_g2(curElmt)) { + if groupcheck && !bool(C.blst_p2_affine_in_g2(&curElmt.cgo)) { atomic.StoreInt32(&valid, 0) break } if first { - C.blst_p2_from_affine(&agg, curElmt) + C.blst_p2_from_affine(&agg.cgo, &curElmt.cgo) first = false } else { - C.blst_p2_add_or_double_affine(&agg, &agg, curElmt) + C.blst_p2_add_or_double_affine(&agg.cgo, &agg.cgo, &curElmt.cgo) } // application might have some async work to do runtime.Gosched() @@ -590,7 +598,7 @@ func (agg *P2Aggregate) coreAggregate(getter aggGetterP2, groupcheck bool, agg.v = msg.agg first = false } else { - C.blst_p2_add_or_double(agg.v, agg.v, msg.agg) + C.blst_p2_add_or_double(&agg.v.cgo, &agg.v.cgo, &msg.agg.cgo) } } } diff --git a/vendor/github.com/supranational/blst/bindings/go/blst_misc.tgo b/vendor/github.com/supranational/blst/bindings/go/blst_misc.tgo index a6e5d90d9b..b629d1ee5a 100644 --- a/vendor/github.com/supranational/blst/bindings/go/blst_misc.tgo +++ b/vendor/github.com/supranational/blst/bindings/go/blst_misc.tgo @@ -1,12 +1,14 @@ import "fmt" +// // Parse out optional arguments for sign and verify. -// aug []byte - augmentation bytes (default: nil) -func parseOpts(optional ...interface{}) ([]byte, [][]byte, bool, bool) { - var aug [][]byte // For aggregate verify - var augSingle []byte // For signing - useHash := true // hash (true), encode (false) +// augSingle []byte - augmentation bytes for aggregate verify (default: nil) +// aug [][]byte - augmentation bytes for signing (default: nil) +// +func parseOpts(optional ...interface{}) (augSingle []byte, aug [][]byte, + useHash bool, ok bool) { + useHash = true // hash (true), encode (false) for _, arg := range optional { switch v := arg.(type) { @@ -29,35 +31,35 @@ func parseOpts(optional ...interface{}) ([]byte, [][]byte, bool, bool) { // formulate interfaces that would process multiple scalars per cgo call. // func (a *Scalar) MulAssign(b *Scalar) (*Scalar, bool) { - return a, bool(C.blst_sk_mul_n_check(a, a, b)) + return a, bool(C.blst_sk_mul_n_check(&a.cgo, &a.cgo, &b.cgo)) } func (a *Scalar) Mul(b *Scalar) (*Scalar, bool) { var ret Scalar - return &ret, bool(C.blst_sk_mul_n_check(&ret, a, b)) + return &ret, bool(C.blst_sk_mul_n_check(&ret.cgo, &a.cgo, &b.cgo)) } func (a *Scalar) AddAssign(b *Scalar) (*Scalar, bool) { - return a, bool(C.blst_sk_add_n_check(a, a, b)) + return a, bool(C.blst_sk_add_n_check(&a.cgo, &a.cgo, &b.cgo)) } func (a *Scalar) Add(b *Scalar) (*Scalar, bool) { var ret Scalar - return &ret, bool(C.blst_sk_add_n_check(&ret, a, b)) + return &ret, bool(C.blst_sk_add_n_check(&ret.cgo, &a.cgo, &b.cgo)) } func (a *Scalar) SubAssign(b *Scalar) (*Scalar, bool) { - return a, bool(C.blst_sk_sub_n_check(a, a, b)) + return a, bool(C.blst_sk_sub_n_check(&a.cgo, &a.cgo, &b.cgo)) } func (a *Scalar) Sub(b *Scalar) (*Scalar, bool) { var ret Scalar - return &ret, bool(C.blst_sk_sub_n_check(&ret, a, b)) + return &ret, bool(C.blst_sk_sub_n_check(&ret.cgo, &a.cgo, &b.cgo)) } func (a *Scalar) Inverse() *Scalar { var ret Scalar - C.blst_sk_inverse(&ret, a) + C.blst_sk_inverse(&ret.cgo, &a.cgo) return &ret } @@ -68,20 +70,20 @@ func (a *Scalar) Inverse() *Scalar { // Scalar serdes func (s *Scalar) Serialize() []byte { var out [BLST_SCALAR_BYTES]byte - C.blst_bendian_from_scalar((*C.byte)(&out[0]), s) + C.blst_bendian_from_scalar((*C.byte)(&out[0]), &s.cgo) return out[:] } func (s *Scalar) Deserialize(in []byte) *Scalar { if len(in) != BLST_SCALAR_BYTES || - !C.go_scalar_from_bendian(s, (*C.byte)(&in[0])) { + !C.go_scalar_from_bendian(&s.cgo, (*C.byte)(&in[0])) { return nil } return s } func (s *Scalar) Valid() bool { - return bool(C.blst_sk_check(s)) + return bool(C.blst_sk_check(&s.cgo)) } func (s *Scalar) HashTo(msg []byte, dst []byte) bool { @@ -96,8 +98,8 @@ func (s *Scalar) HashTo(msg []byte, dst []byte) bool { func HashToScalar(msg []byte, dst []byte) *Scalar { var ret Scalar - if C.go_hash_to_scalar(&ret, ptrOrNil(msg), C.size_t(len(msg)), - ptrOrNil(dst), C.size_t(len(dst))) { + if C.go_hash_to_scalar(&ret.cgo, ptrOrNil(msg), C.size_t(len(msg)), + ptrOrNil(dst), C.size_t(len(dst))) { return &ret } @@ -110,20 +112,20 @@ func HashToScalar(msg []byte, dst []byte) *Scalar { func (fr *Scalar) ToLEndian() []byte { var arr [BLST_SCALAR_BYTES]byte - C.blst_lendian_from_scalar((*C.byte)(&arr[0]), fr) + C.blst_lendian_from_scalar((*C.byte)(&arr[0]), &fr.cgo) return arr[:] } func (fp *Fp) ToLEndian() []byte { var arr [BLST_FP_BYTES]byte - C.blst_lendian_from_fp((*C.byte)(&arr[0]), fp) + C.blst_lendian_from_fp((*C.byte)(&arr[0]), &fp.cgo) return arr[:] } func (fr *Scalar) FromLEndian(arr []byte) *Scalar { nbytes := len(arr) if nbytes < BLST_SCALAR_BYTES || - !C.blst_scalar_from_le_bytes(fr, (*C.byte)(&arr[0]), C.size_t(nbytes)) { + !C.blst_scalar_from_le_bytes(&fr.cgo, (*C.byte)(&arr[0]), C.size_t(nbytes)) { return nil } return fr @@ -133,7 +135,7 @@ func (fp *Fp) FromLEndian(arr []byte) *Fp { if len(arr) != BLST_FP_BYTES { return nil } - C.blst_fp_from_lendian(fp, (*C.byte)(&arr[0])) + C.blst_fp_from_lendian(&fp.cgo, (*C.byte)(&arr[0])) return fp } @@ -143,20 +145,20 @@ func (fp *Fp) FromLEndian(arr []byte) *Fp { func (fr *Scalar) ToBEndian() []byte { var arr [BLST_SCALAR_BYTES]byte - C.blst_bendian_from_scalar((*C.byte)(&arr[0]), fr) + C.blst_bendian_from_scalar((*C.byte)(&arr[0]), &fr.cgo) return arr[:] } func (fp *Fp) ToBEndian() []byte { var arr [BLST_FP_BYTES]byte - C.blst_bendian_from_fp((*C.byte)(&arr[0]), fp) + C.blst_bendian_from_fp((*C.byte)(&arr[0]), &fp.cgo) return arr[:] } func (fr *Scalar) FromBEndian(arr []byte) *Scalar { nbytes := len(arr) if nbytes < BLST_SCALAR_BYTES || - !C.blst_scalar_from_be_bytes(fr, (*C.byte)(&arr[0]), C.size_t(nbytes)) { + !C.blst_scalar_from_be_bytes(&fr.cgo, (*C.byte)(&arr[0]), C.size_t(nbytes)) { return nil } return fr @@ -166,7 +168,7 @@ func (fp *Fp) FromBEndian(arr []byte) *Fp { if len(arr) != BLST_FP_BYTES { return nil } - C.blst_fp_from_bendian(fp, (*C.byte)(&arr[0])) + C.blst_fp_from_bendian(&fp.cgo, (*C.byte)(&arr[0])) return fp } @@ -185,9 +187,11 @@ func (s *Scalar) Print(name string) { func (p *P1Affine) Print(name string) { fmt.Printf("%s:\n", name) - arr := p.x.ToBEndian() + x := Fp{p.cgo.x} + arr := x.ToBEndian() PrintBytes(arr, " x") - arr = p.y.ToBEndian() + y := Fp{p.cgo.y} + arr = y.ToBEndian() PrintBytes(arr, " y") } @@ -199,16 +203,19 @@ func (p *P1) Print(name string) { func (f *Fp2) Print(name string) { fmt.Printf("%s:\n", name) - arr := f.fp[0].ToBEndian() - PrintBytes(arr, " 0") - arr = f.fp[1].ToBEndian() - PrintBytes(arr, " 1") + var arr [BLST_FP_BYTES]byte + C.blst_bendian_from_fp((*C.byte)(&arr[0]), &f.cgo.fp[0]) + PrintBytes(arr[:], " 0") + C.blst_bendian_from_fp((*C.byte)(&arr[0]), &f.cgo.fp[1]) + PrintBytes(arr[:], " 1") } func (p *P2Affine) Print(name string) { fmt.Printf("%s:\n", name) - p.x.Print(" x") - p.y.Print(" y") + x := Fp2{p.cgo.x} + x.Print(" x") + y := Fp2{p.cgo.y} + y.Print(" y") } func (p *P2) Print(name string) { @@ -234,19 +241,19 @@ func (e1 *Fp2) Equals(e2 *Fp2) bool { } func (e1 *P1Affine) Equals(e2 *P1Affine) bool { - return bool(C.blst_p1_affine_is_equal(e1, e2)) + return bool(C.blst_p1_affine_is_equal(&e1.cgo, &e2.cgo)) } func (e1 *P1) Equals(e2 *P1) bool { - return bool(C.blst_p1_is_equal(e1, e2)) + return bool(C.blst_p1_is_equal(&e1.cgo, &e2.cgo)) } func (e1 *P2Affine) Equals(e2 *P2Affine) bool { - return bool(C.blst_p2_affine_is_equal(e1, e2)) + return bool(C.blst_p2_affine_is_equal(&e1.cgo, &e2.cgo)) } func (e1 *P2) Equals(e2 *P2) bool { - return bool(C.blst_p2_is_equal(e1, e2)) + return bool(C.blst_p2_is_equal(&e1.cgo, &e2.cgo)) } // private thunk for testing diff --git a/vendor/github.com/supranational/blst/bindings/go/blst_px.tgo b/vendor/github.com/supranational/blst/bindings/go/blst_px.tgo index ebe2ac3c28..6873c500c9 100644 --- a/vendor/github.com/supranational/blst/bindings/go/blst_px.tgo +++ b/vendor/github.com/supranational/blst/bindings/go/blst_px.tgo @@ -7,8 +7,8 @@ func PairingAggregatePkInG1(ctx Pairing, PK *P1Affine, pkValidate bool, } r := C.blst_pairing_chk_n_aggr_pk_in_g1(&ctx[0], - PK, C.bool(pkValidate), - sig, C.bool(sigGroupcheck), + PK.asPtr(), C.bool(pkValidate), + sig.asPtr(), C.bool(sigGroupcheck), ptrOrNil(msg), C.size_t(len(msg)), ptrOrNil(aug), C.size_t(len(aug))) @@ -25,9 +25,9 @@ func PairingMulNAggregatePkInG1(ctx Pairing, PK *P1Affine, pkValidate bool, } r := C.blst_pairing_chk_n_mul_n_aggr_pk_in_g1(&ctx[0], - PK, C.bool(pkValidate), - sig, C.bool(sigGroupcheck), - &rand.b[0], C.size_t(randBits), + PK.asPtr(), C.bool(pkValidate), + sig.asPtr(), C.bool(sigGroupcheck), + &rand.cgo.b[0], C.size_t(randBits), ptrOrNil(msg), C.size_t(len(msg)), ptrOrNil(aug), C.size_t(len(aug))) @@ -41,7 +41,7 @@ func PairingMulNAggregatePkInG1(ctx Pairing, PK *P1Affine, pkValidate bool, // P1 Serdes func (p1 *P1Affine) Serialize() []byte { var out [BLST_P1_SERIALIZE_BYTES]byte - C.blst_p1_affine_serialize((*C.byte)(&out[0]), p1) + C.blst_p1_affine_serialize((*C.byte)(&out[0]), &p1.cgo) return out[:] } @@ -49,14 +49,14 @@ func (p1 *P1Affine) Deserialize(in []byte) *P1Affine { if len(in) != BLST_P1_SERIALIZE_BYTES { return nil } - if C.blst_p1_deserialize(p1, (*C.byte)(&in[0])) != C.BLST_SUCCESS { + if C.blst_p1_deserialize(&p1.cgo, (*C.byte)(&in[0])) != C.BLST_SUCCESS { return nil } return p1 } func (p1 *P1Affine) Compress() []byte { var out [BLST_P1_COMPRESS_BYTES]byte - C.blst_p1_affine_compress((*C.byte)(&out[0]), p1) + C.blst_p1_affine_compress((*C.byte)(&out[0]), &p1.cgo) return out[:] } @@ -64,14 +64,14 @@ func (p1 *P1Affine) Uncompress(in []byte) *P1Affine { if len(in) != BLST_P1_COMPRESS_BYTES { return nil } - if C.blst_p1_uncompress(p1, (*C.byte)(&in[0])) != C.BLST_SUCCESS { + if C.blst_p1_uncompress(&p1.cgo, (*C.byte)(&in[0])) != C.BLST_SUCCESS { return nil } return p1 } func (p1 *P1Affine) InG1() bool { - return bool(C.blst_p1_affine_in_g1(p1)) + return bool(C.blst_p1_affine_in_g1(&p1.cgo)) } func (_ *P1Affine) BatchUncompress(in [][]byte) []*P1Affine { @@ -128,12 +128,12 @@ func (_ *P1Affine) BatchUncompress(in [][]byte) []*P1Affine { func (p1 *P1) Serialize() []byte { var out [BLST_P1_SERIALIZE_BYTES]byte - C.blst_p1_serialize((*C.byte)(&out[0]), p1) + C.blst_p1_serialize((*C.byte)(&out[0]), &p1.cgo) return out[:] } func (p1 *P1) Compress() []byte { var out [BLST_P1_COMPRESS_BYTES]byte - C.blst_p1_compress((*C.byte)(&out[0]), p1) + C.blst_p1_compress((*C.byte)(&out[0]), &p1.cgo) return out[:] } @@ -145,7 +145,7 @@ func (p1 *P1) MultAssign(scalarIf interface{}, optional ...int) *P1 { scalar = (*C.byte)(&val[0]) nbits = len(val)*8 case *Scalar: - scalar = &val.b[0] + scalar = &val.cgo.b[0] nbits = 255 default: panic(fmt.Sprintf("unsupported type %T", val)) @@ -153,7 +153,7 @@ func (p1 *P1) MultAssign(scalarIf interface{}, optional ...int) *P1 { if len(optional) > 0 { nbits = optional[0] } - C.blst_p1_mult(p1, p1, scalar, C.size_t(nbits)) + C.blst_p1_mult(&p1.cgo, &p1.cgo, scalar, C.size_t(nbits)) return p1 } @@ -165,9 +165,9 @@ func (p1 *P1) Mult(scalarIf interface{}, optional ...int) *P1 { func (p1 *P1) AddAssign(pointIf interface{}) *P1 { switch val := pointIf.(type) { case *P1: - C.blst_p1_add_or_double(p1, p1, val) + C.blst_p1_add_or_double(&p1.cgo, &p1.cgo, &val.cgo) case *P1Affine: - C.blst_p1_add_or_double_affine(p1, p1, val) + C.blst_p1_add_or_double_affine(&p1.cgo, &p1.cgo, &val.cgo) default: panic(fmt.Sprintf("unsupported type %T", val)) } @@ -180,19 +180,19 @@ func (p1 *P1) Add(pointIf interface{}) *P1 { } func (p1 *P1) SubAssign(pointIf interface{}) *P1 { - var x *Fp + var x *C.blst_fp var affine C.bool switch val := pointIf.(type) { case *P1: - x = &val.x + x = &val.cgo.x affine = false case *P1Affine: - x = &val.x + x = &val.cgo.x affine = true default: panic(fmt.Sprintf("unsupported type %T", val)) } - C.go_p1_sub_assign(p1, x, affine) + C.go_p1_sub_assign(&p1.cgo, x, affine) return p1 } @@ -209,15 +209,15 @@ func P1Generator() *P1 { // group generator point" func (acc *P1) MultNAccumulate(pointIf interface{}, scalarIf interface{}, optional ...int) *P1 { - var x *Fp + var x *C.blst_fp var affine C.bool if pointIf != nil { switch val := pointIf.(type) { case *P1: - x = &val.x + x = &val.cgo.x affine = false case *P1Affine: - x = &val.x + x = &val.cgo.x affine = true default: panic(fmt.Sprintf("unsupported type %T", val)) @@ -230,7 +230,7 @@ func (acc *P1) MultNAccumulate(pointIf interface{}, scalarIf interface{}, scalar = (*C.byte)(&val[0]) nbits = len(val)*8 case *Scalar: - scalar = &val.b[0] + scalar = &val.cgo.b[0] nbits = 255 default: panic(fmt.Sprintf("unsupported type %T", val)) @@ -238,7 +238,7 @@ func (acc *P1) MultNAccumulate(pointIf interface{}, scalarIf interface{}, if len(optional) > 0 { nbits = optional[0] } - C.go_p1_mult_n_acc(acc, x, affine, scalar, C.size_t(nbits)) + C.go_p1_mult_n_acc(&acc.cgo, x, affine, scalar, C.size_t(nbits)) return acc } @@ -248,12 +248,12 @@ func (acc *P1) MultNAccumulate(pointIf interface{}, scalarIf interface{}, func (p *P1) ToAffine() *P1Affine { var pa P1Affine - C.blst_p1_to_affine(&pa, p) + C.blst_p1_to_affine(&pa.cgo, &p.cgo) return &pa } func (p *P1) FromAffine(pa *P1Affine) { - C.blst_p1_from_affine(p, pa) + C.blst_p1_from_affine(&p.cgo, &pa.cgo) } // @@ -268,9 +268,9 @@ func HashToG1(msg []byte, dst []byte, aug = optional[0] } - C.blst_hash_to_g1(&q, ptrOrNil(msg), C.size_t(len(msg)), - ptrOrNil(dst), C.size_t(len(dst)), - ptrOrNil(aug), C.size_t(len(aug))) + C.blst_hash_to_g1(&q.cgo, ptrOrNil(msg), C.size_t(len(msg)), + ptrOrNil(dst), C.size_t(len(dst)), + ptrOrNil(aug), C.size_t(len(aug))) return &q } @@ -283,9 +283,9 @@ func EncodeToG1(msg []byte, dst []byte, aug = optional[0] } - C.blst_encode_to_g1(&q, ptrOrNil(msg), C.size_t(len(msg)), - ptrOrNil(dst), C.size_t(len(dst)), - ptrOrNil(aug), C.size_t(len(aug))) + C.blst_encode_to_g1(&q.cgo, ptrOrNil(msg), C.size_t(len(msg)), + ptrOrNil(dst), C.size_t(len(dst)), + ptrOrNil(aug), C.size_t(len(aug))) return &q } @@ -302,7 +302,8 @@ func P1sToAffine(points []*P1, optional ...int) P1Affines { } ret := make([]P1Affine, npoints) _cgoCheckPointer := func(...interface{}) {} - C.blst_p1s_to_affine(&ret[0], &points[0], C.size_t(npoints)) + C.blst_p1s_to_affine(&ret[0].cgo, (**C.blst_p1)(unsafe.Pointer(&points[0])), + C.size_t(npoints)) return ret } @@ -320,7 +321,7 @@ func (points P1s) ToAffine(optional ...P1Affines) P1Affines { } if maxProcs < 2 || npoints < 768 { - C.go_p1slice_to_affine(&ret[0], &points[0], C.size_t(npoints)) + C.go_p1slice_to_affine(&ret[0].cgo, &points[0].cgo, C.size_t(npoints)) return ret } @@ -338,7 +339,7 @@ func (points P1s) ToAffine(optional ...P1Affines) P1Affines { } rem -= 1 go func(out *P1Affine, inp *P1, delta int) { - C.go_p1slice_to_affine(out, inp, C.size_t(delta)) + C.go_p1slice_to_affine(&out.cgo, &inp.cgo, C.size_t(delta)) wg.Done() }(&ret[x], &points[x], delta) } @@ -360,7 +361,8 @@ func P1AffinesAdd(points []*P1Affine, optional ...int) *P1 { } var ret P1 _cgoCheckPointer := func(...interface{}) {} - C.blst_p1s_add(&ret, &points[0], C.size_t(npoints)) + C.blst_p1s_add(&ret.cgo, (**C.blst_p1_affine)(unsafe.Pointer(&points[0])), + C.size_t(npoints)) return &ret } @@ -368,7 +370,7 @@ func (points P1Affines) Add() *P1 { npoints := len(points) if maxProcs < 2 || npoints < 768 { var ret P1 - C.go_p1slice_add(&ret, &points[0], C.size_t(npoints)) + C.go_p1slice_add(&ret.cgo, &points[0].cgo, C.size_t(npoints)) return &ret } @@ -386,7 +388,7 @@ func (points P1Affines) Add() *P1 { rem -= 1 go func(points *P1Affine, delta int) { var ret P1 - C.go_p1slice_add(&ret, points, C.size_t(delta)) + C.go_p1slice_add(&ret.cgo, &points.cgo, C.size_t(delta)) msgs <- ret }(&points[x], delta) } @@ -394,7 +396,7 @@ func (points P1Affines) Add() *P1 { ret := <- msgs for i := 1; i < nslices; i++ { msg := <- msgs - C.blst_p1_add_or_double(&ret, &ret, &msg) + C.blst_p1_add_or_double(&ret.cgo, &ret.cgo, &msg.cgo) } return &ret } @@ -442,7 +444,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { if nbits <= 248 { scalars = make([]*C.byte, npoints) for i := range scalars { - scalars[i] = &val[i].b[0] + scalars[i] = &val[i].cgo.b[0] } } case []*Scalar: @@ -451,7 +453,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { } scalars = make([]*C.byte, npoints) for i := range scalars { - scalars[i] = &val[i].b[0] + scalars[i] = &val[i].cgo.b[0] } default: panic(fmt.Sprintf("unsupported type %T",val)) @@ -463,16 +465,16 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { sz := int(C.blst_p1s_mult_pippenger_scratch_sizeof(C.size_t(npoints)))/8 scratch := make([]uint64, sz) - pointsBySlice := [2]*P1Affine{nil, nil} - var p_points **P1Affine + pointsBySlice := [2]*C.blst_p1_affine{nil, nil} + var p_points **C.blst_p1_affine switch val := pointsIf.(type) { case []*P1Affine: - p_points = &val[0] + p_points = (**C.blst_p1_affine)(unsafe.Pointer(&val[0])) case []P1Affine: - pointsBySlice[0] = &val[0] + pointsBySlice[0] = &val[0].cgo p_points = &pointsBySlice[0] case P1Affines: - pointsBySlice[0] = &val[0] + pointsBySlice[0] = &val[0].cgo p_points = &pointsBySlice[0] } @@ -486,7 +488,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { p_scalars = &scalars[0] case []Scalar: if nbits > 248 { - scalarsBySlice[0] = &val[0].b[0] + scalarsBySlice[0] = &val[0].cgo.b[0] p_scalars = &scalarsBySlice[0] } else { p_scalars = &scalars[0] @@ -497,9 +499,9 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { var ret P1 _cgoCheckPointer := func(...interface{}) {} - C.blst_p1s_mult_pippenger(&ret, p_points, C.size_t(npoints), - p_scalars, C.size_t(nbits), - (*C.limb_t)(&scratch[0])) + C.blst_p1s_mult_pippenger(&ret.cgo, p_points, C.size_t(npoints), + p_scalars, C.size_t(nbits), + (*C.limb_t)(&scratch[0])) for i := range(scalars) { scalars[i] = nil @@ -544,7 +546,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { scalar = scalars[workItem] case []Scalar: if nbits > 248 { - scalar = &val[workItem].b[0] + scalar = &val[workItem].cgo.b[0] } else { scalar = scalars[workItem] } @@ -552,8 +554,8 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { scalar = scalars[workItem] } - C.go_p1_mult_n_acc(&acc, &point.x, true, - scalar, C.size_t(nbits)) + C.go_p1_mult_n_acc(&acc.cgo, &point.cgo.x, true, + scalar, C.size_t(nbits)) } msgs <- acc @@ -563,7 +565,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { ret := <-msgs for tid := 1; tid < numThreads; tid++ { point := <- msgs - C.blst_p1_add_or_double(&ret, &ret, &point); + C.blst_p1_add_or_double(&ret.cgo, &ret.cgo, &point.cgo); } for i := range(scalars) { @@ -615,7 +617,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { for tid := 0; tid < numThreads; tid++ { go func() { scratch := make([]uint64, sz << uint(window-1)) - pointsBySlice := [2]*P1Affine{nil, nil} + pointsBySlice := [2]*C.blst_p1_affine{nil, nil} scalarsBySlice := [2]*C.byte{nil, nil} _cgoCheckPointer := func(...interface{}) {} @@ -628,15 +630,15 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { x := grid[workItem].x y := grid[workItem].y - var p_points **P1Affine + var p_points **C.blst_p1_affine switch val := pointsIf.(type) { case []*P1Affine: - p_points = &val[x] + p_points = (**C.blst_p1_affine)(unsafe.Pointer(&val[x])) case []P1Affine: - pointsBySlice[0] = &val[x] + pointsBySlice[0] = &val[x].cgo p_points = &pointsBySlice[0] case P1Affines: - pointsBySlice[0] = &val[x] + pointsBySlice[0] = &val[x].cgo p_points = &pointsBySlice[0] } @@ -649,7 +651,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { p_scalars = &scalars[x] case []Scalar: if nbits > 248 { - scalarsBySlice[0] = &val[x].b[0] + scalarsBySlice[0] = &val[x].cgo.b[0] p_scalars = &scalarsBySlice[0] } else { p_scalars = &scalars[x] @@ -658,7 +660,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { p_scalars = &scalars[x] } - C.blst_p1s_tile_pippenger(&grid[workItem].point, + C.blst_p1s_tile_pippenger(&grid[workItem].point.cgo, p_points, C.size_t(grid[workItem].dx), p_scalars, C.size_t(nbits), (*C.limb_t)(&scratch[0]), @@ -684,14 +686,14 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { rows[y/window] = true // mark the "row" for grid[row].y == y { // if it's current "row", process it for row < total && grid[row].y == y { - C.blst_p1_add_or_double(&ret, &ret, &grid[row].point) + C.blst_p1_add_or_double(&ret.cgo, &ret.cgo, &grid[row].point.cgo) row++ } if y == 0 { break // one can as well 'return &ret' here } for j := 0; j < window; j++ { - C.blst_p1_double(&ret, &ret) + C.blst_p1_double(&ret.cgo, &ret.cgo) } y -= window if !rows[y/window] { // see if next "row" was marked already @@ -749,7 +751,7 @@ func P1AffinesValidate(pointsIf interface{}) bool { panic(fmt.Sprintf("unsupported type %T", val)) } - if !C.go_p1_affine_validate(point, true) { + if !C.go_p1_affine_validate(&point.cgo, true) { return false } } @@ -784,7 +786,7 @@ func P1AffinesValidate(pointsIf interface{}) bool { panic(fmt.Sprintf("unsupported type %T", val)) } - if !C.go_p1_affine_validate(point, true) { + if !C.go_p1_affine_validate(&point.cgo, true) { atomic.StoreInt32(&valid, 0) break } diff --git a/vendor/github.com/supranational/blst/bindings/go/generate.py b/vendor/github.com/supranational/blst/bindings/go/generate.py index d40fad2109..0285119148 100644 --- a/vendor/github.com/supranational/blst/bindings/go/generate.py +++ b/vendor/github.com/supranational/blst/bindings/go/generate.py @@ -87,6 +87,7 @@ def remap(fout, fin, mapping, dont_touch, removeImports): mapping = [('P1', 'P2'), ('p1', 'p2'), ('Fp', 'Fp2'), + ('C.blst_fp', 'C.blst_fp2'), ('G1', 'G2'), ('g1', 'g2') ] diff --git a/vendor/golang.org/x/exp/LICENSE b/vendor/golang.org/x/exp/LICENSE deleted file mode 100644 index 2a7cf70da6..0000000000 --- a/vendor/golang.org/x/exp/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright 2009 The Go Authors. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google LLC nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/golang.org/x/exp/PATENTS b/vendor/golang.org/x/exp/PATENTS deleted file mode 100644 index 733099041f..0000000000 --- a/vendor/golang.org/x/exp/PATENTS +++ /dev/null @@ -1,22 +0,0 @@ -Additional IP Rights Grant (Patents) - -"This implementation" means the copyrightable works distributed by -Google as part of the Go project. - -Google hereby grants to You a perpetual, worldwide, non-exclusive, -no-charge, royalty-free, irrevocable (except as stated in this section) -patent license to make, have made, use, offer to sell, sell, import, -transfer and otherwise run, modify and propagate the contents of this -implementation of Go, where such license applies only to those patent -claims, both currently owned or controlled by Google and acquired in -the future, licensable by Google that are necessarily infringed by this -implementation of Go. This grant does not include claims that would be -infringed only as a consequence of further modification of this -implementation. If you or your agent or exclusive licensee institute or -order or agree to the institution of patent litigation against any -entity (including a cross-claim or counterclaim in a lawsuit) alleging -that this implementation of Go or any code incorporated within this -implementation of Go constitutes direct or contributory patent -infringement, or inducement of patent infringement, then any patent -rights granted to you under this License for this implementation of Go -shall terminate as of the date such litigation is filed. diff --git a/vendor/golang.org/x/exp/maps/maps.go b/vendor/golang.org/x/exp/maps/maps.go deleted file mode 100644 index ecc0dabb74..0000000000 --- a/vendor/golang.org/x/exp/maps/maps.go +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2021 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 maps defines various functions useful with maps of any type. -package maps - -// Keys returns the keys of the map m. -// The keys will be in an indeterminate order. -func Keys[M ~map[K]V, K comparable, V any](m M) []K { - r := make([]K, 0, len(m)) - for k := range m { - r = append(r, k) - } - return r -} - -// Values returns the values of the map m. -// The values will be in an indeterminate order. -func Values[M ~map[K]V, K comparable, V any](m M) []V { - r := make([]V, 0, len(m)) - for _, v := range m { - r = append(r, v) - } - return r -} - -// Equal reports whether two maps contain the same key/value pairs. -// Values are compared using ==. -func Equal[M1, M2 ~map[K]V, K, V comparable](m1 M1, m2 M2) bool { - if len(m1) != len(m2) { - return false - } - for k, v1 := range m1 { - if v2, ok := m2[k]; !ok || v1 != v2 { - return false - } - } - return true -} - -// EqualFunc is like Equal, but compares values using eq. -// Keys are still compared with ==. -func EqualFunc[M1 ~map[K]V1, M2 ~map[K]V2, K comparable, V1, V2 any](m1 M1, m2 M2, eq func(V1, V2) bool) bool { - if len(m1) != len(m2) { - return false - } - for k, v1 := range m1 { - if v2, ok := m2[k]; !ok || !eq(v1, v2) { - return false - } - } - return true -} - -// Clear removes all entries from m, leaving it empty. -func Clear[M ~map[K]V, K comparable, V any](m M) { - for k := range m { - delete(m, k) - } -} - -// Clone returns a copy of m. This is a shallow clone: -// the new keys and values are set using ordinary assignment. -func Clone[M ~map[K]V, K comparable, V any](m M) M { - // Preserve nil in case it matters. - if m == nil { - return nil - } - r := make(M, len(m)) - for k, v := range m { - r[k] = v - } - return r -} - -// Copy copies all key/value pairs in src adding them to dst. -// When a key in src is already present in dst, -// the value in dst will be overwritten by the value associated -// with the key in src. -func Copy[M1 ~map[K]V, M2 ~map[K]V, K comparable, V any](dst M1, src M2) { - for k, v := range src { - dst[k] = v - } -} - -// DeleteFunc deletes any key/value pairs from m for which del returns true. -func DeleteFunc[M ~map[K]V, K comparable, V any](m M, del func(K, V) bool) { - for k, v := range m { - if del(k, v) { - delete(m, k) - } - } -} diff --git a/vendor/golang.org/x/mod/LICENSE b/vendor/golang.org/x/mod/LICENSE index 6a66aea5ea..2a7cf70da6 100644 --- a/vendor/golang.org/x/mod/LICENSE +++ b/vendor/golang.org/x/mod/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2009 The Go Authors. All rights reserved. +Copyright 2009 The Go Authors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are @@ -10,7 +10,7 @@ notice, this list of conditions and the following disclaimer. copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - * Neither the name of Google Inc. nor the names of its + * Neither the name of Google LLC nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. diff --git a/vendor/golang.org/x/sync/LICENSE b/vendor/golang.org/x/sync/LICENSE index 6a66aea5ea..2a7cf70da6 100644 --- a/vendor/golang.org/x/sync/LICENSE +++ b/vendor/golang.org/x/sync/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2009 The Go Authors. All rights reserved. +Copyright 2009 The Go Authors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are @@ -10,7 +10,7 @@ notice, this list of conditions and the following disclaimer. copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - * Neither the name of Google Inc. nor the names of its + * Neither the name of Google LLC nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. diff --git a/vendor/golang.org/x/tools/LICENSE b/vendor/golang.org/x/tools/LICENSE index 6a66aea5ea..2a7cf70da6 100644 --- a/vendor/golang.org/x/tools/LICENSE +++ b/vendor/golang.org/x/tools/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2009 The Go Authors. All rights reserved. +Copyright 2009 The Go Authors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are @@ -10,7 +10,7 @@ notice, this list of conditions and the following disclaimer. copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - * Neither the name of Google Inc. nor the names of its + * Neither the name of Google LLC nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. diff --git a/vendor/golang.org/x/tools/go/gcexportdata/gcexportdata.go b/vendor/golang.org/x/tools/go/gcexportdata/gcexportdata.go index 137cc8df1d..65fe2628e9 100644 --- a/vendor/golang.org/x/tools/go/gcexportdata/gcexportdata.go +++ b/vendor/golang.org/x/tools/go/gcexportdata/gcexportdata.go @@ -2,22 +2,64 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// Package gcexportdata provides functions for locating, reading, and -// writing export data files containing type information produced by the -// gc compiler. This package supports go1.7 export data format and all -// later versions. -// -// Although it might seem convenient for this package to live alongside -// go/types in the standard library, this would cause version skew -// problems for developer tools that use it, since they must be able to -// consume the outputs of the gc compiler both before and after a Go -// update such as from Go 1.7 to Go 1.8. Because this package lives in -// golang.org/x/tools, sites can update their version of this repo some -// time before the Go 1.8 release and rebuild and redeploy their -// developer tools, which will then be able to consume both Go 1.7 and -// Go 1.8 export data files, so they will work before and after the -// Go update. (See discussion at https://golang.org/issue/15651.) -package gcexportdata // import "golang.org/x/tools/go/gcexportdata" +// Package gcexportdata provides functions for reading and writing +// export data, which is a serialized description of the API of a Go +// package including the names, kinds, types, and locations of all +// exported declarations. +// +// The standard Go compiler (cmd/compile) writes an export data file +// for each package it compiles, which it later reads when compiling +// packages that import the earlier one. The compiler must thus +// contain logic to both write and read export data. +// (See the "Export" section in the cmd/compile/README file.) +// +// The [Read] function in this package can read files produced by the +// compiler, producing [go/types] data structures. As a matter of +// policy, Read supports export data files produced by only the last +// two Go releases plus tip; see https://go.dev/issue/68898. The +// export data files produced by the compiler contain additional +// details related to generics, inlining, and other optimizations that +// cannot be decoded by the [Read] function. +// +// In files written by the compiler, the export data is not at the +// start of the file. Before calling Read, use [NewReader] to locate +// the desired portion of the file. +// +// The [Write] function in this package encodes the exported API of a +// Go package ([types.Package]) as a file. Such files can be later +// decoded by Read, but cannot be consumed by the compiler. +// +// # Future changes +// +// Although Read supports the formats written by both Write and the +// compiler, the two are quite different, and there is an open +// proposal (https://go.dev/issue/69491) to separate these APIs. +// +// Under that proposal, this package would ultimately provide only the +// Read operation for compiler export data, which must be defined in +// this module (golang.org/x/tools), not in the standard library, to +// avoid version skew for developer tools that need to read compiler +// export data both before and after a Go release, such as from Go +// 1.23 to Go 1.24. Because this package lives in the tools module, +// clients can update their version of the module some time before the +// Go 1.24 release and rebuild and redeploy their tools, which will +// then be able to consume both Go 1.23 and Go 1.24 export data files, +// so they will work before and after the Go update. (See discussion +// at https://go.dev/issue/15651.) +// +// The operations to import and export [go/types] data structures +// would be defined in the go/types package as Import and Export. +// [Write] would (eventually) delegate to Export, +// and [Read], when it detects a file produced by Export, +// would delegate to Import. +// +// # Deprecations +// +// The [NewImporter] and [Find] functions are deprecated and should +// not be used in new code. The [WriteBundle] and [ReadBundle] +// functions are experimental, and there is an open proposal to +// deprecate them (https://go.dev/issue/69573). +package gcexportdata import ( "bufio" @@ -64,24 +106,18 @@ func Find(importPath, srcDir string) (filename, path string) { // additional trailing data beyond the end of the export data. func NewReader(r io.Reader) (io.Reader, error) { buf := bufio.NewReader(r) - _, size, err := gcimporter.FindExportData(buf) + size, err := gcimporter.FindExportData(buf) if err != nil { return nil, err } - if size >= 0 { - // We were given an archive and found the __.PKGDEF in it. - // This tells us the size of the export data, and we don't - // need to return the entire file. - return &io.LimitedReader{ - R: buf, - N: size, - }, nil - } else { - // We were given an object file. As such, we don't know how large - // the export data is and must return the entire file. - return buf, nil - } + // We were given an archive and found the __.PKGDEF in it. + // This tells us the size of the export data, and we don't + // need to return the entire file. + return &io.LimitedReader{ + R: buf, + N: size, + }, nil } // readAll works the same way as io.ReadAll, but avoids allocations and copies @@ -100,6 +136,11 @@ func readAll(r io.Reader) ([]byte, error) { // Read reads export data from in, decodes it, and returns type // information for the package. // +// Read is capable of reading export data produced by [Write] at the +// same source code version, or by the last two Go releases (plus tip) +// of the standard Go compiler. Reading files from older compilers may +// produce an error. +// // The package path (effectively its linker symbol prefix) is // specified by path, since unlike the package name, this information // may not be recorded in the export data. @@ -128,14 +169,26 @@ func Read(in io.Reader, fset *token.FileSet, imports map[string]*types.Package, // (from "version"). Select appropriate importer. if len(data) > 0 { switch data[0] { - case 'v', 'c', 'd': // binary, till go1.10 + case 'v', 'c', 'd': + // binary, produced by cmd/compile till go1.10 return nil, fmt.Errorf("binary (%c) import format is no longer supported", data[0]) - case 'i': // indexed, till go1.19 + case 'i': + // indexed, produced by cmd/compile till go1.19, + // and also by [Write]. + // + // If proposal #69491 is accepted, go/types + // serialization will be implemented by + // types.Export, to which Write would eventually + // delegate (explicitly dropping any pretence at + // inter-version Write-Read compatibility). + // This [Read] function would delegate to types.Import + // when it detects that the file was produced by Export. _, pkg, err := gcimporter.IImportData(fset, imports, data[1:], path) return pkg, err - case 'u': // unified, from go1.20 + case 'u': + // unified, produced by cmd/compile since go1.20 _, pkg, err := gcimporter.UImportData(fset, imports, data[1:], path) return pkg, err diff --git a/vendor/golang.org/x/tools/go/packages/doc.go b/vendor/golang.org/x/tools/go/packages/doc.go index 3531ac8f5f..f1931d10ee 100644 --- a/vendor/golang.org/x/tools/go/packages/doc.go +++ b/vendor/golang.org/x/tools/go/packages/doc.go @@ -64,7 +64,7 @@ graph using the Imports fields. The Load function can be configured by passing a pointer to a Config as the first argument. A nil Config is equivalent to the zero Config, which -causes Load to run in LoadFiles mode, collecting minimal information. +causes Load to run in [LoadFiles] mode, collecting minimal information. See the documentation for type Config for details. As noted earlier, the Config.Mode controls the amount of detail @@ -72,14 +72,14 @@ reported about the loaded packages. See the documentation for type LoadMode for details. Most tools should pass their command-line arguments (after any flags) -uninterpreted to [Load], so that it can interpret them +uninterpreted to Load, so that it can interpret them according to the conventions of the underlying build system. See the Example function for typical usage. # The driver protocol -[Load] may be used to load Go packages even in Go projects that use +Load may be used to load Go packages even in Go projects that use alternative build systems, by installing an appropriate "driver" program for the build system and specifying its location in the GOPACKAGESDRIVER environment variable. @@ -97,6 +97,15 @@ JSON-encoded [DriverRequest] message providing additional information is written to the driver's standard input. The driver must write a JSON-encoded [DriverResponse] message to its standard output. (This message differs from the JSON schema produced by 'go list'.) + +The value of the PWD environment variable seen by the driver process +is the preferred name of its working directory. (The working directory +may have other aliases due to symbolic links; see the comment on the +Dir field of [exec.Cmd] for related information.) +When the driver process emits in its response the name of a file +that is a descendant of this directory, it must use an absolute path +that has the value of PWD as a prefix, to ensure that the returned +filenames satisfy the original query. */ package packages // import "golang.org/x/tools/go/packages" diff --git a/vendor/golang.org/x/tools/go/packages/external.go b/vendor/golang.org/x/tools/go/packages/external.go index c2b4b711b5..91bd62e83b 100644 --- a/vendor/golang.org/x/tools/go/packages/external.go +++ b/vendor/golang.org/x/tools/go/packages/external.go @@ -13,6 +13,7 @@ import ( "fmt" "os" "os/exec" + "slices" "strings" ) @@ -79,10 +80,10 @@ type DriverResponse struct { // driver is the type for functions that query the build system for the // packages named by the patterns. -type driver func(cfg *Config, patterns ...string) (*DriverResponse, error) +type driver func(cfg *Config, patterns []string) (*DriverResponse, error) // findExternalDriver returns the file path of a tool that supplies -// the build system package structure, or "" if not found." +// the build system package structure, or "" if not found. // If GOPACKAGESDRIVER is set in the environment findExternalTool returns its // value, otherwise it searches for a binary named gopackagesdriver on the PATH. func findExternalDriver(cfg *Config) driver { @@ -103,7 +104,7 @@ func findExternalDriver(cfg *Config) driver { return nil } } - return func(cfg *Config, words ...string) (*DriverResponse, error) { + return func(cfg *Config, patterns []string) (*DriverResponse, error) { req, err := json.Marshal(DriverRequest{ Mode: cfg.Mode, Env: cfg.Env, @@ -117,7 +118,7 @@ func findExternalDriver(cfg *Config) driver { buf := new(bytes.Buffer) stderr := new(bytes.Buffer) - cmd := exec.CommandContext(cfg.Context, tool, words...) + cmd := exec.CommandContext(cfg.Context, tool, patterns...) cmd.Dir = cfg.Dir // The cwd gets resolved to the real path. On Darwin, where // /tmp is a symlink, this breaks anything that expects the @@ -131,7 +132,7 @@ func findExternalDriver(cfg *Config) driver { // command. // // (See similar trick in Invocation.run in ../../internal/gocommand/invoke.go) - cmd.Env = append(slicesClip(cfg.Env), "PWD="+cfg.Dir) + cmd.Env = append(slices.Clip(cfg.Env), "PWD="+cfg.Dir) cmd.Stdin = bytes.NewReader(req) cmd.Stdout = buf cmd.Stderr = stderr @@ -150,7 +151,3 @@ func findExternalDriver(cfg *Config) driver { return &response, nil } } - -// slicesClip removes unused capacity from the slice, returning s[:len(s):len(s)]. -// TODO(adonovan): use go1.21 slices.Clip. -func slicesClip[S ~[]E, E any](s S) S { return s[:len(s):len(s)] } diff --git a/vendor/golang.org/x/tools/go/packages/golist.go b/vendor/golang.org/x/tools/go/packages/golist.go index 1a3a5b44f5..0458b4f9c4 100644 --- a/vendor/golang.org/x/tools/go/packages/golist.go +++ b/vendor/golang.org/x/tools/go/packages/golist.go @@ -80,6 +80,12 @@ type golistState struct { cfg *Config ctx context.Context + runner *gocommand.Runner + + // overlay is the JSON file that encodes the Config.Overlay + // mapping, used by 'go list -overlay=...'. + overlay string + envOnce sync.Once goEnvError error goEnv map[string]string @@ -127,7 +133,10 @@ func (state *golistState) mustGetEnv() map[string]string { // goListDriver uses the go list command to interpret the patterns and produce // the build system package structure. // See driver for more details. -func goListDriver(cfg *Config, patterns ...string) (_ *DriverResponse, err error) { +// +// overlay is the JSON file that encodes the cfg.Overlay +// mapping, used by 'go list -overlay=...' +func goListDriver(cfg *Config, runner *gocommand.Runner, overlay string, patterns []string) (_ *DriverResponse, err error) { // Make sure that any asynchronous go commands are killed when we return. parentCtx := cfg.Context if parentCtx == nil { @@ -142,13 +151,15 @@ func goListDriver(cfg *Config, patterns ...string) (_ *DriverResponse, err error cfg: cfg, ctx: ctx, vendorDirs: map[string]bool{}, + overlay: overlay, + runner: runner, } // Fill in response.Sizes asynchronously if necessary. - if cfg.Mode&NeedTypesSizes != 0 || cfg.Mode&NeedTypes != 0 { + if cfg.Mode&NeedTypesSizes != 0 || cfg.Mode&(NeedTypes|NeedTypesInfo) != 0 { errCh := make(chan error) go func() { - compiler, arch, err := getSizesForArgs(ctx, state.cfgInvocation(), cfg.gocmdRunner) + compiler, arch, err := getSizesForArgs(ctx, state.cfgInvocation(), runner) response.dr.Compiler = compiler response.dr.Arch = arch errCh <- err @@ -311,6 +322,7 @@ type jsonPackage struct { ImportPath string Dir string Name string + Target string Export string GoFiles []string CompiledGoFiles []string @@ -494,13 +506,15 @@ func (state *golistState) createDriverResponse(words ...string) (*DriverResponse pkg := &Package{ Name: p.Name, ID: p.ImportPath, + Dir: p.Dir, + Target: p.Target, GoFiles: absJoin(p.Dir, p.GoFiles, p.CgoFiles), CompiledGoFiles: absJoin(p.Dir, p.CompiledGoFiles), OtherFiles: absJoin(p.Dir, otherFiles(p)...), EmbedFiles: absJoin(p.Dir, p.EmbedFiles), EmbedPatterns: absJoin(p.Dir, p.EmbedPatterns), IgnoredFiles: absJoin(p.Dir, p.IgnoredGoFiles, p.IgnoredOtherFiles), - forTest: p.ForTest, + ForTest: p.ForTest, depsErrors: p.DepsErrors, Module: p.Module, } @@ -681,7 +695,7 @@ func (state *golistState) shouldAddFilenameFromError(p *jsonPackage) bool { // getGoVersion returns the effective minor version of the go command. func (state *golistState) getGoVersion() (int, error) { state.goVersionOnce.Do(func() { - state.goVersion, state.goVersionError = gocommand.GoVersion(state.ctx, state.cfgInvocation(), state.cfg.gocmdRunner) + state.goVersion, state.goVersionError = gocommand.GoVersion(state.ctx, state.cfgInvocation(), state.runner) }) return state.goVersion, state.goVersionError } @@ -751,7 +765,7 @@ func jsonFlag(cfg *Config, goVersion int) string { } } addFields("Name", "ImportPath", "Error") // These fields are always needed - if cfg.Mode&NeedFiles != 0 || cfg.Mode&NeedTypes != 0 { + if cfg.Mode&NeedFiles != 0 || cfg.Mode&(NeedTypes|NeedTypesInfo) != 0 { addFields("Dir", "GoFiles", "IgnoredGoFiles", "IgnoredOtherFiles", "CFiles", "CgoFiles", "CXXFiles", "MFiles", "HFiles", "FFiles", "SFiles", "SwigFiles", "SwigCXXFiles", "SysoFiles") @@ -759,7 +773,7 @@ func jsonFlag(cfg *Config, goVersion int) string { addFields("TestGoFiles", "XTestGoFiles") } } - if cfg.Mode&NeedTypes != 0 { + if cfg.Mode&(NeedTypes|NeedTypesInfo) != 0 { // CompiledGoFiles seems to be required for the test case TestCgoNoSyntax, // even when -compiled isn't passed in. // TODO(#52435): Should we make the test ask for -compiled, or automatically @@ -784,7 +798,7 @@ func jsonFlag(cfg *Config, goVersion int) string { // Request Dir in the unlikely case Export is not absolute. addFields("Dir", "Export") } - if cfg.Mode&needInternalForTest != 0 { + if cfg.Mode&NeedForTest != 0 { addFields("ForTest") } if cfg.Mode&needInternalDepsErrors != 0 { @@ -799,6 +813,9 @@ func jsonFlag(cfg *Config, goVersion int) string { if cfg.Mode&NeedEmbedPatterns != 0 { addFields("EmbedPatterns") } + if cfg.Mode&NeedTarget != 0 { + addFields("Target") + } return "-json=" + strings.Join(fields, ",") } @@ -840,7 +857,7 @@ func (state *golistState) cfgInvocation() gocommand.Invocation { Env: cfg.Env, Logf: cfg.Logf, WorkingDir: cfg.Dir, - Overlay: cfg.goListOverlayFile, + Overlay: state.overlay, } } @@ -851,11 +868,8 @@ func (state *golistState) invokeGo(verb string, args ...string) (*bytes.Buffer, inv := state.cfgInvocation() inv.Verb = verb inv.Args = args - gocmdRunner := cfg.gocmdRunner - if gocmdRunner == nil { - gocmdRunner = &gocommand.Runner{} - } - stdout, stderr, friendlyErr, err := gocmdRunner.RunRaw(cfg.Context, inv) + + stdout, stderr, friendlyErr, err := state.runner.RunRaw(cfg.Context, inv) if err != nil { // Check for 'go' executable not being found. if ee, ok := err.(*exec.Error); ok && ee.Err == exec.ErrNotFound { @@ -879,6 +893,12 @@ func (state *golistState) invokeGo(verb string, args ...string) (*bytes.Buffer, return nil, friendlyErr } + // Return an error if 'go list' failed due to missing tools in + // $GOROOT/pkg/tool/$GOOS_$GOARCH (#69606). + if len(stderr.String()) > 0 && strings.Contains(stderr.String(), `go: no such tool`) { + return nil, friendlyErr + } + // Is there an error running the C compiler in cgo? This will be reported in the "Error" field // and should be suppressed by go list -e. // diff --git a/vendor/golang.org/x/tools/go/packages/loadmode_string.go b/vendor/golang.org/x/tools/go/packages/loadmode_string.go index 5c080d21b5..69eec9f44d 100644 --- a/vendor/golang.org/x/tools/go/packages/loadmode_string.go +++ b/vendor/golang.org/x/tools/go/packages/loadmode_string.go @@ -9,49 +9,48 @@ import ( "strings" ) -var allModes = []LoadMode{ - NeedName, - NeedFiles, - NeedCompiledGoFiles, - NeedImports, - NeedDeps, - NeedExportFile, - NeedTypes, - NeedSyntax, - NeedTypesInfo, - NeedTypesSizes, +var modes = [...]struct { + mode LoadMode + name string +}{ + {NeedName, "NeedName"}, + {NeedFiles, "NeedFiles"}, + {NeedCompiledGoFiles, "NeedCompiledGoFiles"}, + {NeedImports, "NeedImports"}, + {NeedDeps, "NeedDeps"}, + {NeedExportFile, "NeedExportFile"}, + {NeedTypes, "NeedTypes"}, + {NeedSyntax, "NeedSyntax"}, + {NeedTypesInfo, "NeedTypesInfo"}, + {NeedTypesSizes, "NeedTypesSizes"}, + {NeedForTest, "NeedForTest"}, + {NeedModule, "NeedModule"}, + {NeedEmbedFiles, "NeedEmbedFiles"}, + {NeedEmbedPatterns, "NeedEmbedPatterns"}, + {NeedTarget, "NeedTarget"}, } -var modeStrings = []string{ - "NeedName", - "NeedFiles", - "NeedCompiledGoFiles", - "NeedImports", - "NeedDeps", - "NeedExportFile", - "NeedTypes", - "NeedSyntax", - "NeedTypesInfo", - "NeedTypesSizes", -} - -func (mod LoadMode) String() string { - m := mod - if m == 0 { +func (mode LoadMode) String() string { + if mode == 0 { return "LoadMode(0)" } var out []string - for i, x := range allModes { - if x > m { - break + // named bits + for _, item := range modes { + if (mode & item.mode) != 0 { + mode ^= item.mode + out = append(out, item.name) } - if (m & x) != 0 { - out = append(out, modeStrings[i]) - m = m ^ x + } + // unnamed residue + if mode != 0 { + if out == nil { + return fmt.Sprintf("LoadMode(%#x)", int(mode)) } + out = append(out, fmt.Sprintf("%#x", int(mode))) } - if m != 0 { - out = append(out, "Unknown") + if len(out) == 1 { + return out[0] } - return fmt.Sprintf("LoadMode(%s)", strings.Join(out, "|")) + return "(" + strings.Join(out, "|") + ")" } diff --git a/vendor/golang.org/x/tools/go/packages/packages.go b/vendor/golang.org/x/tools/go/packages/packages.go index 34306ddd39..0147d9080a 100644 --- a/vendor/golang.org/x/tools/go/packages/packages.go +++ b/vendor/golang.org/x/tools/go/packages/packages.go @@ -16,13 +16,13 @@ import ( "go/scanner" "go/token" "go/types" - "io" "log" "os" "path/filepath" "runtime" "strings" "sync" + "sync/atomic" "time" "golang.org/x/sync/errgroup" @@ -31,7 +31,6 @@ import ( "golang.org/x/tools/internal/gocommand" "golang.org/x/tools/internal/packagesinternal" "golang.org/x/tools/internal/typesinternal" - "golang.org/x/tools/internal/versions" ) // A LoadMode controls the amount of detail to return when loading. @@ -44,20 +43,33 @@ import ( // ID and Errors (if present) will always be filled. // [Load] may return more information than requested. // +// The Mode flag is a union of several bits named NeedName, +// NeedFiles, and so on, each of which determines whether +// a given field of Package (Name, Files, etc) should be +// populated. +// +// For convenience, we provide named constants for the most +// common combinations of Need flags: +// +// [LoadFiles] lists of files in each package +// [LoadImports] ... plus imports +// [LoadTypes] ... plus type information +// [LoadSyntax] ... plus type-annotated syntax +// [LoadAllSyntax] ... for all dependencies +// // Unfortunately there are a number of open bugs related to // interactions among the LoadMode bits: -// - https://github.com/golang/go/issues/48226 -// - https://github.com/golang/go/issues/56633 -// - https://github.com/golang/go/issues/56677 -// - https://github.com/golang/go/issues/58726 -// - https://github.com/golang/go/issues/63517 +// - https://github.com/golang/go/issues/56633 +// - https://github.com/golang/go/issues/56677 +// - https://github.com/golang/go/issues/58726 +// - https://github.com/golang/go/issues/63517 type LoadMode int const ( // NeedName adds Name and PkgPath. NeedName LoadMode = 1 << iota - // NeedFiles adds GoFiles and OtherFiles. + // NeedFiles adds Dir, GoFiles, OtherFiles, and IgnoredFiles NeedFiles // NeedCompiledGoFiles adds CompiledGoFiles. @@ -76,10 +88,10 @@ const ( // NeedTypes adds Types, Fset, and IllTyped. NeedTypes - // NeedSyntax adds Syntax. + // NeedSyntax adds Syntax and Fset. NeedSyntax - // NeedTypesInfo adds TypesInfo. + // NeedTypesInfo adds TypesInfo and Fset. NeedTypesInfo // NeedTypesSizes adds TypesSizes. @@ -88,9 +100,10 @@ const ( // needInternalDepsErrors adds the internal deps errors field for use by gopls. needInternalDepsErrors - // needInternalForTest adds the internal forTest field. + // NeedForTest adds ForTest. + // // Tests must also be set on the context for this field to be populated. - needInternalForTest + NeedForTest // typecheckCgo enables full support for type checking cgo. Requires Go 1.15+. // Modifies CompiledGoFiles and Types, and has no effect on its own. @@ -104,27 +117,27 @@ const ( // NeedEmbedPatterns adds EmbedPatterns. NeedEmbedPatterns + + // NeedTarget adds Target. + NeedTarget + + // Be sure to update loadmode_string.go when adding new items! ) const ( - // Deprecated: LoadFiles exists for historical compatibility - // and should not be used. Please directly specify the needed fields using the Need values. + // LoadFiles loads the name and file names for the initial packages. LoadFiles = NeedName | NeedFiles | NeedCompiledGoFiles - // Deprecated: LoadImports exists for historical compatibility - // and should not be used. Please directly specify the needed fields using the Need values. + // LoadImports loads the name, file names, and import mapping for the initial packages. LoadImports = LoadFiles | NeedImports - // Deprecated: LoadTypes exists for historical compatibility - // and should not be used. Please directly specify the needed fields using the Need values. + // LoadTypes loads exported type information for the initial packages. LoadTypes = LoadImports | NeedTypes | NeedTypesSizes - // Deprecated: LoadSyntax exists for historical compatibility - // and should not be used. Please directly specify the needed fields using the Need values. + // LoadSyntax loads typed syntax for the initial packages. LoadSyntax = LoadTypes | NeedSyntax | NeedTypesInfo - // Deprecated: LoadAllSyntax exists for historical compatibility - // and should not be used. Please directly specify the needed fields using the Need values. + // LoadAllSyntax loads typed syntax for the initial packages and all dependencies. LoadAllSyntax = LoadSyntax | NeedDeps // Deprecated: NeedExportsFile is a historical misspelling of NeedExportFile. @@ -134,13 +147,7 @@ const ( // A Config specifies details about how packages should be loaded. // The zero value is a valid configuration. // -// Calls to Load do not modify this struct. -// -// TODO(adonovan): #67702: this is currently false: in fact, -// calls to [Load] do not modify the public fields of this struct, but -// may modify hidden fields, so concurrent calls to [Load] must not -// use the same Config. But perhaps we should reestablish the -// documented invariant. +// Calls to [Load] do not modify this struct. type Config struct { // Mode controls the level of information returned for each package. Mode LoadMode @@ -171,19 +178,10 @@ type Config struct { // Env []string - // gocmdRunner guards go command calls from concurrency errors. - gocmdRunner *gocommand.Runner - // BuildFlags is a list of command-line flags to be passed through to // the build system's query tool. BuildFlags []string - // modFile will be used for -modfile in go command invocations. - modFile string - - // modFlag will be used for -modfile in go command invocations. - modFlag string - // Fset provides source position information for syntax trees and types. // If Fset is nil, Load will use a new fileset, but preserve Fset's value. Fset *token.FileSet @@ -230,21 +228,24 @@ type Config struct { // drivers may vary in their level of support for overlays. Overlay map[string][]byte - // goListOverlayFile is the JSON file that encodes the Overlay - // mapping, used by 'go list -overlay=...' - goListOverlayFile string + // -- Hidden configuration fields only for use in x/tools -- + + // modFile will be used for -modfile in go command invocations. + modFile string + + // modFlag will be used for -modfile in go command invocations. + modFlag string } // Load loads and returns the Go packages named by the given patterns. // -// Config specifies loading options; -// nil behaves the same as an empty Config. +// The cfg parameter specifies loading options; nil behaves the same as an empty [Config]. // // The [Config.Mode] field is a set of bits that determine what kinds // of information should be computed and returned. Modes that require // more information tend to be slower. See [LoadMode] for details // and important caveats. Its zero value is equivalent to -// NeedName | NeedFiles | NeedCompiledGoFiles. +// [NeedName] | [NeedFiles] | [NeedCompiledGoFiles]. // // Each call to Load returns a new set of [Package] instances. // The Packages and their Imports form a directed acyclic graph. @@ -261,7 +262,7 @@ type Config struct { // Errors associated with a particular package are recorded in the // corresponding Package's Errors list, and do not cause Load to // return an error. Clients may need to handle such errors before -// proceeding with further analysis. The PrintErrors function is +// proceeding with further analysis. The [PrintErrors] function is // provided for convenient display of all errors. func Load(cfg *Config, patterns ...string) ([]*Package, error) { ld := newLoader(cfg) @@ -324,21 +325,24 @@ func defaultDriver(cfg *Config, patterns ...string) (*DriverResponse, bool, erro } else if !response.NotHandled { return response, true, nil } - // (fall through) + // not handled: fall through } // go list fallback - // + // Write overlays once, as there are many calls // to 'go list' (one per chunk plus others too). - overlay, cleanupOverlay, err := gocommand.WriteOverlays(cfg.Overlay) + overlayFile, cleanupOverlay, err := gocommand.WriteOverlays(cfg.Overlay) if err != nil { return nil, false, err } defer cleanupOverlay() - cfg.goListOverlayFile = overlay - response, err := callDriverOnChunks(goListDriver, cfg, chunks) + var runner gocommand.Runner // (shared across many 'go list' calls) + driver := func(cfg *Config, patterns []string) (*DriverResponse, error) { + return goListDriver(cfg, &runner, overlayFile, patterns) + } + response, err := callDriverOnChunks(driver, cfg, chunks) if err != nil { return nil, false, err } @@ -376,16 +380,14 @@ func splitIntoChunks(patterns []string, argMax int) ([][]string, error) { func callDriverOnChunks(driver driver, cfg *Config, chunks [][]string) (*DriverResponse, error) { if len(chunks) == 0 { - return driver(cfg) + return driver(cfg, nil) } responses := make([]*DriverResponse, len(chunks)) errNotHandled := errors.New("driver returned NotHandled") var g errgroup.Group for i, chunk := range chunks { - i := i - chunk := chunk g.Go(func() (err error) { - responses[i], err = driver(cfg, chunk...) + responses[i], err = driver(cfg, chunk) if responses[i] != nil && responses[i].NotHandled { err = errNotHandled } @@ -435,6 +437,12 @@ type Package struct { // PkgPath is the package path as used by the go/types package. PkgPath string + // Dir is the directory associated with the package, if it exists. + // + // For packages listed by the go command, this is the directory containing + // the package files. + Dir string + // Errors contains any errors encountered querying the metadata // of the package, or while parsing or type-checking its files. Errors []Error @@ -474,6 +482,10 @@ type Package struct { // information for the package as provided by the build system. ExportFile string + // Target is the absolute install path of the .a file, for libraries, + // and of the executable file, for binaries. + Target string + // Imports maps import paths appearing in the package's Go source files // to corresponding loaded Packages. Imports map[string]*Package @@ -522,8 +534,8 @@ type Package struct { // -- internal -- - // forTest is the package under test, if any. - forTest string + // ForTest is the package under test, if any. + ForTest string // depsErrors is the DepsErrors field from the go list response, if any. depsErrors []*packagesinternal.PackageError @@ -552,9 +564,6 @@ type ModuleError struct { } func init() { - packagesinternal.GetForTest = func(p interface{}) string { - return p.(*Package).forTest - } packagesinternal.GetDepsErrors = func(p interface{}) []*packagesinternal.PackageError { return p.(*Package).depsErrors } @@ -566,7 +575,6 @@ func init() { } packagesinternal.TypecheckCgo = int(typecheckCgo) packagesinternal.DepsErrors = int(needInternalDepsErrors) - packagesinternal.ForTest = int(needInternalForTest) } // An Error describes a problem with a package's metadata, syntax, or types. @@ -682,18 +690,19 @@ func (p *Package) String() string { return p.ID } // loaderPackage augments Package with state used during the loading phase type loaderPackage struct { *Package - importErrors map[string]error // maps each bad import to its error - loadOnce sync.Once - color uint8 // for cycle detection - needsrc bool // load from source (Mode >= LoadTypes) - needtypes bool // type information is either requested or depended on - initial bool // package was matched by a pattern - goVersion int // minor version number of go command on PATH + importErrors map[string]error // maps each bad import to its error + preds []*loaderPackage // packages that import this one + unfinishedSuccs atomic.Int32 // number of direct imports not yet loaded + color uint8 // for cycle detection + needsrc bool // load from source (Mode >= LoadTypes) + needtypes bool // type information is either requested or depended on + initial bool // package was matched by a pattern + goVersion int // minor version number of go command on PATH } // loader holds the working state of a single call to load. type loader struct { - pkgs map[string]*loaderPackage + pkgs map[string]*loaderPackage // keyed by Package.ID Config sizes types.Sizes // non-nil if needed by mode parseCache map[string]*parseValue @@ -739,9 +748,6 @@ func newLoader(cfg *Config) *loader { if ld.Config.Env == nil { ld.Config.Env = os.Environ() } - if ld.Config.gocmdRunner == nil { - ld.Config.gocmdRunner = &gocommand.Runner{} - } if ld.Context == nil { ld.Context = context.Background() } @@ -755,7 +761,7 @@ func newLoader(cfg *Config) *loader { ld.requestedMode = ld.Mode ld.Mode = impliedLoadMode(ld.Mode) - if ld.Mode&NeedTypes != 0 || ld.Mode&NeedSyntax != 0 { + if ld.Mode&(NeedSyntax|NeedTypes|NeedTypesInfo) != 0 { if ld.Fset == nil { ld.Fset = token.NewFileSet() } @@ -764,6 +770,7 @@ func newLoader(cfg *Config) *loader { // because we load source if export data is missing. if ld.ParseFile == nil { ld.ParseFile = func(fset *token.FileSet, filename string, src []byte) (*ast.File, error) { + // We implicitly promise to keep doing ast.Object resolution. :( const mode = parser.AllErrors | parser.ParseComments return parser.ParseFile(fset, filename, src, mode) } @@ -795,7 +802,7 @@ func (ld *loader) refine(response *DriverResponse) ([]*Package, error) { exportDataInvalid := len(ld.Overlay) > 0 || pkg.ExportFile == "" && pkg.PkgPath != "unsafe" // This package needs type information if the caller requested types and the package is // either a root, or it's a non-root and the user requested dependencies ... - needtypes := (ld.Mode&NeedTypes|NeedTypesInfo != 0 && (rootIndex >= 0 || ld.Mode&NeedDeps != 0)) + needtypes := (ld.Mode&(NeedTypes|NeedTypesInfo) != 0 && (rootIndex >= 0 || ld.Mode&NeedDeps != 0)) // This package needs source if the call requested source (or types info, which implies source) // and the package is either a root, or itas a non- root and the user requested dependencies... needsrc := ((ld.Mode&(NeedSyntax|NeedTypesInfo) != 0 && (rootIndex >= 0 || ld.Mode&NeedDeps != 0)) || @@ -820,9 +827,10 @@ func (ld *loader) refine(response *DriverResponse) ([]*Package, error) { } } - if ld.Mode&NeedImports != 0 { - // Materialize the import graph. - + // Materialize the import graph if it is needed (NeedImports), + // or if we'll be using loadPackages (Need{Syntax|Types|TypesInfo}). + var leaves []*loaderPackage // packages with no unfinished successors + if ld.Mode&(NeedImports|NeedSyntax|NeedTypes|NeedTypesInfo) != 0 { const ( white = 0 // new grey = 1 // in progress @@ -841,63 +849,76 @@ func (ld *loader) refine(response *DriverResponse) ([]*Package, error) { // dependency on a package that does. These are the only packages // for which we load source code. var stack []*loaderPackage - var visit func(lpkg *loaderPackage) bool - visit = func(lpkg *loaderPackage) bool { - switch lpkg.color { - case black: - return lpkg.needsrc - case grey: + var visit func(from, lpkg *loaderPackage) bool + visit = func(from, lpkg *loaderPackage) bool { + if lpkg.color == grey { panic("internal error: grey node") } - lpkg.color = grey - stack = append(stack, lpkg) // push - stubs := lpkg.Imports // the structure form has only stubs with the ID in the Imports - lpkg.Imports = make(map[string]*Package, len(stubs)) - for importPath, ipkg := range stubs { - var importErr error - imp := ld.pkgs[ipkg.ID] - if imp == nil { - // (includes package "C" when DisableCgo) - importErr = fmt.Errorf("missing package: %q", ipkg.ID) - } else if imp.color == grey { - importErr = fmt.Errorf("import cycle: %s", stack) + if lpkg.color == white { + lpkg.color = grey + stack = append(stack, lpkg) // push + stubs := lpkg.Imports // the structure form has only stubs with the ID in the Imports + lpkg.Imports = make(map[string]*Package, len(stubs)) + for importPath, ipkg := range stubs { + var importErr error + imp := ld.pkgs[ipkg.ID] + if imp == nil { + // (includes package "C" when DisableCgo) + importErr = fmt.Errorf("missing package: %q", ipkg.ID) + } else if imp.color == grey { + importErr = fmt.Errorf("import cycle: %s", stack) + } + if importErr != nil { + if lpkg.importErrors == nil { + lpkg.importErrors = make(map[string]error) + } + lpkg.importErrors[importPath] = importErr + continue + } + + if visit(lpkg, imp) { + lpkg.needsrc = true + } + lpkg.Imports[importPath] = imp.Package } - if importErr != nil { - if lpkg.importErrors == nil { - lpkg.importErrors = make(map[string]error) + + // -- postorder -- + + // Complete type information is required for the + // immediate dependencies of each source package. + if lpkg.needsrc && ld.Mode&NeedTypes != 0 { + for _, ipkg := range lpkg.Imports { + ld.pkgs[ipkg.ID].needtypes = true } - lpkg.importErrors[importPath] = importErr - continue } - if visit(imp) { - lpkg.needsrc = true + // NeedTypeSizes causes TypeSizes to be set even + // on packages for which types aren't needed. + if ld.Mode&NeedTypesSizes != 0 { + lpkg.TypesSizes = ld.sizes } - lpkg.Imports[importPath] = imp.Package - } - // Complete type information is required for the - // immediate dependencies of each source package. - if lpkg.needsrc && ld.Mode&NeedTypes != 0 { - for _, ipkg := range lpkg.Imports { - ld.pkgs[ipkg.ID].needtypes = true + // Add packages with no imports directly to the queue of leaves. + if len(lpkg.Imports) == 0 { + leaves = append(leaves, lpkg) } + + stack = stack[:len(stack)-1] // pop + lpkg.color = black } - // NeedTypeSizes causes TypeSizes to be set even - // on packages for which types aren't needed. - if ld.Mode&NeedTypesSizes != 0 { - lpkg.TypesSizes = ld.sizes + // Add edge from predecessor. + if from != nil { + from.unfinishedSuccs.Add(+1) // incref + lpkg.preds = append(lpkg.preds, from) } - stack = stack[:len(stack)-1] // pop - lpkg.color = black return lpkg.needsrc } // For each initial package, create its import DAG. for _, lpkg := range initial { - visit(lpkg) + visit(nil, lpkg) } } else { @@ -910,16 +931,45 @@ func (ld *loader) refine(response *DriverResponse) ([]*Package, error) { // Load type data and syntax if needed, starting at // the initial packages (roots of the import DAG). - if ld.Mode&NeedTypes != 0 || ld.Mode&NeedSyntax != 0 { - var wg sync.WaitGroup - for _, lpkg := range initial { - wg.Add(1) - go func(lpkg *loaderPackage) { - ld.loadRecursive(lpkg) - wg.Done() - }(lpkg) + if ld.Mode&(NeedSyntax|NeedTypes|NeedTypesInfo) != 0 { + + // We avoid using g.SetLimit to limit concurrency as + // it makes g.Go stop accepting work, which prevents + // workers from enqeuing, and thus finishing, and thus + // allowing the group to make progress: deadlock. + // + // Instead we use the ioLimit and cpuLimit semaphores. + g, _ := errgroup.WithContext(ld.Context) + + // enqueues adds a package to the type-checking queue. + // It must have no unfinished successors. + var enqueue func(*loaderPackage) + enqueue = func(lpkg *loaderPackage) { + g.Go(func() error { + // Parse and type-check. + ld.loadPackage(lpkg) + + // Notify each waiting predecessor, + // and enqueue it when it becomes a leaf. + for _, pred := range lpkg.preds { + if pred.unfinishedSuccs.Add(-1) == 0 { // decref + enqueue(pred) + } + } + + return nil + }) + } + + // Load leaves first, adding new packages + // to the queue as they become leaves. + for _, leaf := range leaves { + enqueue(leaf) + } + + if err := g.Wait(); err != nil { + return nil, err // cancelled } - wg.Wait() } // If the context is done, return its error and @@ -961,12 +1011,14 @@ func (ld *loader) refine(response *DriverResponse) ([]*Package, error) { } if ld.requestedMode&NeedTypes == 0 { ld.pkgs[i].Types = nil - ld.pkgs[i].Fset = nil ld.pkgs[i].IllTyped = false } if ld.requestedMode&NeedSyntax == 0 { ld.pkgs[i].Syntax = nil } + if ld.requestedMode&(NeedSyntax|NeedTypes|NeedTypesInfo) == 0 { + ld.pkgs[i].Fset = nil + } if ld.requestedMode&NeedTypesInfo == 0 { ld.pkgs[i].TypesInfo = nil } @@ -981,31 +1033,10 @@ func (ld *loader) refine(response *DriverResponse) ([]*Package, error) { return result, nil } -// loadRecursive loads the specified package and its dependencies, -// recursively, in parallel, in topological order. -// It is atomic and idempotent. -// Precondition: ld.Mode&NeedTypes. -func (ld *loader) loadRecursive(lpkg *loaderPackage) { - lpkg.loadOnce.Do(func() { - // Load the direct dependencies, in parallel. - var wg sync.WaitGroup - for _, ipkg := range lpkg.Imports { - imp := ld.pkgs[ipkg.ID] - wg.Add(1) - go func(imp *loaderPackage) { - ld.loadRecursive(imp) - wg.Done() - }(imp) - } - wg.Wait() - ld.loadPackage(lpkg) - }) -} - -// loadPackage loads the specified package. +// loadPackage loads/parses/typechecks the specified package. // It must be called only once per Package, // after immediate dependencies are loaded. -// Precondition: ld.Mode & NeedTypes. +// Precondition: ld.Mode&(NeedSyntax|NeedTypes|NeedTypesInfo) != 0. func (ld *loader) loadPackage(lpkg *loaderPackage) { if lpkg.PkgPath == "unsafe" { // Fill in the blanks to avoid surprises. @@ -1041,6 +1072,10 @@ func (ld *loader) loadPackage(lpkg *loaderPackage) { if !lpkg.needtypes && !lpkg.needsrc { return } + + // TODO(adonovan): this condition looks wrong: + // I think it should be lpkg.needtypes && !lpg.needsrc, + // so that NeedSyntax without NeedTypes can be satisfied by export data. if !lpkg.needsrc { if err := ld.loadFromExportData(lpkg); err != nil { lpkg.Errors = append(lpkg.Errors, Error{ @@ -1146,7 +1181,7 @@ func (ld *loader) loadPackage(lpkg *loaderPackage) { } lpkg.Syntax = files - if ld.Config.Mode&NeedTypes == 0 { + if ld.Config.Mode&(NeedTypes|NeedTypesInfo) == 0 { return } @@ -1157,16 +1192,20 @@ func (ld *loader) loadPackage(lpkg *loaderPackage) { return } - lpkg.TypesInfo = &types.Info{ - Types: make(map[ast.Expr]types.TypeAndValue), - Defs: make(map[*ast.Ident]types.Object), - Uses: make(map[*ast.Ident]types.Object), - Implicits: make(map[ast.Node]types.Object), - Instances: make(map[*ast.Ident]types.Instance), - Scopes: make(map[ast.Node]*types.Scope), - Selections: make(map[*ast.SelectorExpr]*types.Selection), + // Populate TypesInfo only if needed, as it + // causes the type checker to work much harder. + if ld.Config.Mode&NeedTypesInfo != 0 { + lpkg.TypesInfo = &types.Info{ + Types: make(map[ast.Expr]types.TypeAndValue), + Defs: make(map[*ast.Ident]types.Object), + Uses: make(map[*ast.Ident]types.Object), + Implicits: make(map[ast.Node]types.Object), + Instances: make(map[*ast.Ident]types.Instance), + Scopes: make(map[ast.Node]*types.Scope), + Selections: make(map[*ast.SelectorExpr]*types.Selection), + FileVersions: make(map[*ast.File]string), + } } - versions.InitFileVersions(lpkg.TypesInfo) lpkg.TypesSizes = ld.sizes importer := importerFunc(func(path string) (*types.Package, error) { @@ -1219,6 +1258,10 @@ func (ld *loader) loadPackage(lpkg *loaderPackage) { } } + // Type-checking is CPU intensive. + cpuLimit <- unit{} // acquire a token + defer func() { <-cpuLimit }() // release a token + typErr := types.NewChecker(tc, ld.Fset, lpkg.Types, lpkg.TypesInfo).Files(lpkg.Syntax) lpkg.importErrors = nil // no longer needed @@ -1283,8 +1326,11 @@ type importerFunc func(path string) (*types.Package, error) func (f importerFunc) Import(path string) (*types.Package, error) { return f(path) } // We use a counting semaphore to limit -// the number of parallel I/O calls per process. -var ioLimit = make(chan bool, 20) +// the number of parallel I/O calls or CPU threads per process. +var ( + ioLimit = make(chan unit, 20) + cpuLimit = make(chan unit, runtime.GOMAXPROCS(0)) +) func (ld *loader) parseFile(filename string) (*ast.File, error) { ld.parseCacheMu.Lock() @@ -1301,20 +1347,28 @@ func (ld *loader) parseFile(filename string) (*ast.File, error) { var src []byte for f, contents := range ld.Config.Overlay { + // TODO(adonovan): Inefficient for large overlays. + // Do an exact name-based map lookup + // (for nonexistent files) followed by a + // FileID-based map lookup (for existing ones). if sameFile(f, filename) { src = contents + break } } var err error if src == nil { - ioLimit <- true // wait + ioLimit <- unit{} // acquire a token src, err = os.ReadFile(filename) - <-ioLimit // signal + <-ioLimit // release a token } if err != nil { v.err = err } else { + // Parsing is CPU intensive. + cpuLimit <- unit{} // acquire a token v.f, v.err = ld.ParseFile(ld.Fset, filename, src) + <-cpuLimit // release a token } close(v.ready) @@ -1329,18 +1383,21 @@ func (ld *loader) parseFile(filename string) (*ast.File, error) { // Because files are scanned in parallel, the token.Pos // positions of the resulting ast.Files are not ordered. func (ld *loader) parseFiles(filenames []string) ([]*ast.File, []error) { - var wg sync.WaitGroup - n := len(filenames) - parsed := make([]*ast.File, n) - errors := make([]error, n) - for i, file := range filenames { - wg.Add(1) - go func(i int, filename string) { + var ( + n = len(filenames) + parsed = make([]*ast.File, n) + errors = make([]error, n) + ) + var g errgroup.Group + for i, filename := range filenames { + // This creates goroutines unnecessarily in the + // cache-hit case, but that case is uncommon. + g.Go(func() error { parsed[i], errors[i] = ld.parseFile(filename) - wg.Done() - }(i, file) + return nil + }) } - wg.Wait() + g.Wait() // Eliminate nils, preserving order. var o int @@ -1499,6 +1556,10 @@ func impliedLoadMode(loadMode LoadMode) LoadMode { // All these things require knowing the import graph. loadMode |= NeedImports } + if loadMode&NeedTypes != 0 { + // Types require the GoVersion from Module. + loadMode |= NeedModule + } return loadMode } @@ -1507,4 +1568,4 @@ func usesExportData(cfg *Config) bool { return cfg.Mode&NeedExportFile != 0 || cfg.Mode&NeedTypes != 0 && cfg.Mode&NeedDeps == 0 } -var _ interface{} = io.Discard // assert build toolchain is go1.16 or later +type unit struct{} diff --git a/vendor/golang.org/x/tools/go/packages/visit.go b/vendor/golang.org/x/tools/go/packages/visit.go index a1dcc40b72..df14ffd94d 100644 --- a/vendor/golang.org/x/tools/go/packages/visit.go +++ b/vendor/golang.org/x/tools/go/packages/visit.go @@ -49,11 +49,20 @@ func Visit(pkgs []*Package, pre func(*Package) bool, post func(*Package)) { // PrintErrors returns the number of errors printed. func PrintErrors(pkgs []*Package) int { var n int + errModules := make(map[*Module]bool) Visit(pkgs, nil, func(pkg *Package) { for _, err := range pkg.Errors { fmt.Fprintln(os.Stderr, err) n++ } + + // Print pkg.Module.Error once if present. + mod := pkg.Module + if mod != nil && mod.Error != nil && !errModules[mod] { + errModules[mod] = true + fmt.Fprintln(os.Stderr, mod.Error.Err) + n++ + } }) return n } diff --git a/vendor/golang.org/x/tools/go/types/objectpath/objectpath.go b/vendor/golang.org/x/tools/go/types/objectpath/objectpath.go index d648c3d071..16ed3c1780 100644 --- a/vendor/golang.org/x/tools/go/types/objectpath/objectpath.go +++ b/vendor/golang.org/x/tools/go/types/objectpath/objectpath.go @@ -51,7 +51,7 @@ type Path string // // PO package->object Package.Scope.Lookup // OT object->type Object.Type -// TT type->type Type.{Elem,Key,{,{,Recv}Type}Params,Results,Underlying} [EKPRUTrC] +// TT type->type Type.{Elem,Key,{,{,Recv}Type}Params,Results,Underlying,Rhs} [EKPRUTrCa] // TO type->object Type.{At,Field,Method,Obj} [AFMO] // // All valid paths start with a package and end at an object @@ -63,7 +63,7 @@ type Path string // - The only PO operator is Package.Scope.Lookup, which requires an identifier. // - The only OT operator is Object.Type, // which we encode as '.' because dot cannot appear in an identifier. -// - The TT operators are encoded as [EKPRUTrC]; +// - The TT operators are encoded as [EKPRUTrCa]; // two of these ({,Recv}TypeParams) require an integer operand, // which is encoded as a string of decimal digits. // - The TO operators are encoded as [AFMO]; @@ -106,6 +106,7 @@ const ( opTypeParam = 'T' // .TypeParams.At(i) (Named, Signature) opRecvTypeParam = 'r' // .RecvTypeParams.At(i) (Signature) opConstraint = 'C' // .Constraint() (TypeParam) + opRhs = 'a' // .Rhs() (Alias) // type->object operators opAt = 'A' // .At(i) (Tuple) @@ -227,7 +228,7 @@ func (enc *Encoder) For(obj types.Object) (Path, error) { // Reject obviously non-viable cases. switch obj := obj.(type) { case *types.TypeName: - if _, ok := aliases.Unalias(obj.Type()).(*types.TypeParam); !ok { + if _, ok := types.Unalias(obj.Type()).(*types.TypeParam); !ok { // With the exception of type parameters, only package-level type names // have a path. return "", fmt.Errorf("no path for %v", obj) @@ -279,21 +280,26 @@ func (enc *Encoder) For(obj types.Object) (Path, error) { path = append(path, opType) T := o.Type() - - if tname.IsAlias() { - // type alias - if r := find(obj, T, path, nil); r != nil { + if alias, ok := T.(*types.Alias); ok { + if r := findTypeParam(obj, aliases.TypeParams(alias), path, opTypeParam); r != nil { return Path(r), nil } - } else { - if named, _ := T.(*types.Named); named != nil { - if r := findTypeParam(obj, named.TypeParams(), path, opTypeParam, nil); r != nil { - // generic named type - return Path(r), nil - } + if r := find(obj, aliases.Rhs(alias), append(path, opRhs)); r != nil { + return Path(r), nil + } + + } else if tname.IsAlias() { + // legacy alias + if r := find(obj, T, path); r != nil { + return Path(r), nil } + + } else if named, ok := T.(*types.Named); ok { // defined (named) type - if r := find(obj, T.Underlying(), append(path, opUnderlying), nil); r != nil { + if r := findTypeParam(obj, named.TypeParams(), path, opTypeParam); r != nil { + return Path(r), nil + } + if r := find(obj, named.Underlying(), append(path, opUnderlying)); r != nil { return Path(r), nil } } @@ -306,7 +312,7 @@ func (enc *Encoder) For(obj types.Object) (Path, error) { if _, ok := o.(*types.TypeName); !ok { if o.Exported() { // exported non-type (const, var, func) - if r := find(obj, o.Type(), append(path, opType), nil); r != nil { + if r := find(obj, o.Type(), append(path, opType)); r != nil { return Path(r), nil } } @@ -314,7 +320,7 @@ func (enc *Encoder) For(obj types.Object) (Path, error) { } // Inspect declared methods of defined types. - if T, ok := aliases.Unalias(o.Type()).(*types.Named); ok { + if T, ok := types.Unalias(o.Type()).(*types.Named); ok { path = append(path, opType) // The method index here is always with respect // to the underlying go/types data structures, @@ -326,7 +332,7 @@ func (enc *Encoder) For(obj types.Object) (Path, error) { if m == obj { return Path(path2), nil // found declared method } - if r := find(obj, m.Type(), append(path2, opType), nil); r != nil { + if r := find(obj, m.Type(), append(path2, opType)); r != nil { return Path(r), nil } } @@ -441,46 +447,64 @@ func (enc *Encoder) concreteMethod(meth *types.Func) (Path, bool) { // // The seen map is used to short circuit cycles through type parameters. If // nil, it will be allocated as necessary. -func find(obj types.Object, T types.Type, path []byte, seen map[*types.TypeName]bool) []byte { +// +// The seenMethods map is used internally to short circuit cycles through +// interface methods, such as occur in the following example: +// +// type I interface { f() interface{I} } +// +// See golang/go#68046 for details. +func find(obj types.Object, T types.Type, path []byte) []byte { + return (&finder{obj: obj}).find(T, path) +} + +// finder closes over search state for a call to find. +type finder struct { + obj types.Object // the sought object + seenTParamNames map[*types.TypeName]bool // for cycle breaking through type parameters + seenMethods map[*types.Func]bool // for cycle breaking through recursive interfaces +} + +func (f *finder) find(T types.Type, path []byte) []byte { switch T := T.(type) { - case *aliases.Alias: - return find(obj, aliases.Unalias(T), path, seen) + case *types.Alias: + return f.find(types.Unalias(T), path) case *types.Basic, *types.Named: // Named types belonging to pkg were handled already, // so T must belong to another package. No path. return nil case *types.Pointer: - return find(obj, T.Elem(), append(path, opElem), seen) + return f.find(T.Elem(), append(path, opElem)) case *types.Slice: - return find(obj, T.Elem(), append(path, opElem), seen) + return f.find(T.Elem(), append(path, opElem)) case *types.Array: - return find(obj, T.Elem(), append(path, opElem), seen) + return f.find(T.Elem(), append(path, opElem)) case *types.Chan: - return find(obj, T.Elem(), append(path, opElem), seen) + return f.find(T.Elem(), append(path, opElem)) case *types.Map: - if r := find(obj, T.Key(), append(path, opKey), seen); r != nil { + if r := f.find(T.Key(), append(path, opKey)); r != nil { return r } - return find(obj, T.Elem(), append(path, opElem), seen) + return f.find(T.Elem(), append(path, opElem)) case *types.Signature: - if r := findTypeParam(obj, T.RecvTypeParams(), path, opRecvTypeParam, nil); r != nil { + if r := f.findTypeParam(T.RecvTypeParams(), path, opRecvTypeParam); r != nil { return r } - if r := findTypeParam(obj, T.TypeParams(), path, opTypeParam, seen); r != nil { + if r := f.findTypeParam(T.TypeParams(), path, opTypeParam); r != nil { return r } - if r := find(obj, T.Params(), append(path, opParams), seen); r != nil { + if r := f.find(T.Params(), append(path, opParams)); r != nil { return r } - return find(obj, T.Results(), append(path, opResults), seen) + return f.find(T.Results(), append(path, opResults)) case *types.Struct: for i := 0; i < T.NumFields(); i++ { fld := T.Field(i) path2 := appendOpArg(path, opField, i) - if fld == obj { + if fld == f.obj { return path2 // found field var } - if r := find(obj, fld.Type(), append(path2, opType), seen); r != nil { + if r := f.find(fld.Type(), append(path2, opType)); r != nil { return r } } @@ -489,10 +513,10 @@ func find(obj types.Object, T types.Type, path []byte, seen map[*types.TypeName] for i := 0; i < T.Len(); i++ { v := T.At(i) path2 := appendOpArg(path, opAt, i) - if v == obj { + if v == f.obj { return path2 // found param/result var } - if r := find(obj, v.Type(), append(path2, opType), seen); r != nil { + if r := f.find(v.Type(), append(path2, opType)); r != nil { return r } } @@ -500,28 +524,35 @@ func find(obj types.Object, T types.Type, path []byte, seen map[*types.TypeName] case *types.Interface: for i := 0; i < T.NumMethods(); i++ { m := T.Method(i) + if f.seenMethods[m] { + return nil + } path2 := appendOpArg(path, opMethod, i) - if m == obj { + if m == f.obj { return path2 // found interface method } - if r := find(obj, m.Type(), append(path2, opType), seen); r != nil { + if f.seenMethods == nil { + f.seenMethods = make(map[*types.Func]bool) + } + f.seenMethods[m] = true + if r := f.find(m.Type(), append(path2, opType)); r != nil { return r } } return nil case *types.TypeParam: name := T.Obj() - if name == obj { - return append(path, opObj) - } - if seen[name] { + if f.seenTParamNames[name] { return nil } - if seen == nil { - seen = make(map[*types.TypeName]bool) + if name == f.obj { + return append(path, opObj) + } + if f.seenTParamNames == nil { + f.seenTParamNames = make(map[*types.TypeName]bool) } - seen[name] = true - if r := find(obj, T.Constraint(), append(path, opConstraint), seen); r != nil { + f.seenTParamNames[name] = true + if r := f.find(T.Constraint(), append(path, opConstraint)); r != nil { return r } return nil @@ -529,11 +560,15 @@ func find(obj types.Object, T types.Type, path []byte, seen map[*types.TypeName] panic(T) } -func findTypeParam(obj types.Object, list *types.TypeParamList, path []byte, op byte, seen map[*types.TypeName]bool) []byte { +func findTypeParam(obj types.Object, list *types.TypeParamList, path []byte, op byte) []byte { + return (&finder{obj: obj}).findTypeParam(list, path, op) +} + +func (f *finder) findTypeParam(list *types.TypeParamList, path []byte, op byte) []byte { for i := 0; i < list.Len(); i++ { tparam := list.At(i) path2 := appendOpArg(path, op, i) - if r := find(obj, tparam, path2, seen); r != nil { + if r := f.find(tparam, path2); r != nil { return r } } @@ -620,7 +655,7 @@ func Object(pkg *types.Package, p Path) (types.Object, error) { // Inv: t != nil, obj == nil - t = aliases.Unalias(t) + t = types.Unalias(t) switch code { case opElem: hasElem, ok := t.(hasElem) // Pointer, Slice, Array, Chan, Map @@ -657,6 +692,16 @@ func Object(pkg *types.Package, p Path) (types.Object, error) { } t = named.Underlying() + case opRhs: + if alias, ok := t.(*types.Alias); ok { + t = aliases.Rhs(alias) + } else if false && aliases.Enabled() { + // The Enabled check is too expensive, so for now we + // simply assume that aliases are not enabled. + // TODO(adonovan): replace with "if true {" when go1.24 is assured. + return nil, fmt.Errorf("cannot apply %q to %s (got %T, want alias)", code, t, t) + } + case opTypeParam: hasTypeParams, ok := t.(hasTypeParams) // Named, Signature if !ok { diff --git a/vendor/golang.org/x/tools/go/types/typeutil/callee.go b/vendor/golang.org/x/tools/go/types/typeutil/callee.go new file mode 100644 index 0000000000..754380351e --- /dev/null +++ b/vendor/golang.org/x/tools/go/types/typeutil/callee.go @@ -0,0 +1,68 @@ +// Copyright 2018 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 typeutil + +import ( + "go/ast" + "go/types" + + "golang.org/x/tools/internal/typeparams" +) + +// Callee returns the named target of a function call, if any: +// a function, method, builtin, or variable. +// +// Functions and methods may potentially have type parameters. +func Callee(info *types.Info, call *ast.CallExpr) types.Object { + fun := ast.Unparen(call.Fun) + + // Look through type instantiation if necessary. + isInstance := false + switch fun.(type) { + case *ast.IndexExpr, *ast.IndexListExpr: + // When extracting the callee from an *IndexExpr, we need to check that + // it is a *types.Func and not a *types.Var. + // Example: Don't match a slice m within the expression `m[0]()`. + isInstance = true + fun, _, _, _ = typeparams.UnpackIndexExpr(fun) + } + + var obj types.Object + switch fun := fun.(type) { + case *ast.Ident: + obj = info.Uses[fun] // type, var, builtin, or declared func + case *ast.SelectorExpr: + if sel, ok := info.Selections[fun]; ok { + obj = sel.Obj() // method or field + } else { + obj = info.Uses[fun.Sel] // qualified identifier? + } + } + if _, ok := obj.(*types.TypeName); ok { + return nil // T(x) is a conversion, not a call + } + // A Func is required to match instantiations. + if _, ok := obj.(*types.Func); isInstance && !ok { + return nil // Was not a Func. + } + return obj +} + +// StaticCallee returns the target (function or method) of a static function +// call, if any. It returns nil for calls to builtins. +// +// Note: for calls of instantiated functions and methods, StaticCallee returns +// the corresponding generic function or method on the generic type. +func StaticCallee(info *types.Info, call *ast.CallExpr) *types.Func { + if f, ok := Callee(info, call).(*types.Func); ok && !interfaceMethod(f) { + return f + } + return nil +} + +func interfaceMethod(f *types.Func) bool { + recv := f.Type().(*types.Signature).Recv() + return recv != nil && types.IsInterface(recv.Type()) +} diff --git a/vendor/golang.org/x/tools/go/types/typeutil/imports.go b/vendor/golang.org/x/tools/go/types/typeutil/imports.go new file mode 100644 index 0000000000..b81ce0c330 --- /dev/null +++ b/vendor/golang.org/x/tools/go/types/typeutil/imports.go @@ -0,0 +1,30 @@ +// Copyright 2014 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 typeutil + +import "go/types" + +// Dependencies returns all dependencies of the specified packages. +// +// Dependent packages appear in topological order: if package P imports +// package Q, Q appears earlier than P in the result. +// The algorithm follows import statements in the order they +// appear in the source code, so the result is a total order. +func Dependencies(pkgs ...*types.Package) []*types.Package { + var result []*types.Package + seen := make(map[*types.Package]bool) + var visit func(pkgs []*types.Package) + visit = func(pkgs []*types.Package) { + for _, p := range pkgs { + if !seen[p] { + seen[p] = true + visit(p.Imports()) + result = append(result, p) + } + } + } + visit(pkgs) + return result +} diff --git a/vendor/golang.org/x/tools/go/types/typeutil/map.go b/vendor/golang.org/x/tools/go/types/typeutil/map.go new file mode 100644 index 0000000000..93b3090c68 --- /dev/null +++ b/vendor/golang.org/x/tools/go/types/typeutil/map.go @@ -0,0 +1,467 @@ +// Copyright 2014 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 typeutil defines various utilities for types, such as [Map], +// a hash table that maps [types.Type] to any value. +package typeutil + +import ( + "bytes" + "fmt" + "go/types" + "hash/maphash" + "unsafe" + + "golang.org/x/tools/internal/typeparams" +) + +// Map is a hash-table-based mapping from types (types.Type) to +// arbitrary values. The concrete types that implement +// the Type interface are pointers. Since they are not canonicalized, +// == cannot be used to check for equivalence, and thus we cannot +// simply use a Go map. +// +// Just as with map[K]V, a nil *Map is a valid empty map. +// +// Read-only map operations ([Map.At], [Map.Len], and so on) may +// safely be called concurrently. +// +// TODO(adonovan): deprecate in favor of https://go.dev/issues/69420 +// and 69559, if the latter proposals for a generic hash-map type and +// a types.Hash function are accepted. +type Map struct { + table map[uint32][]entry // maps hash to bucket; entry.key==nil means unused + length int // number of map entries +} + +// entry is an entry (key/value association) in a hash bucket. +type entry struct { + key types.Type + value any +} + +// SetHasher has no effect. +// +// It is a relic of an optimization that is no longer profitable. Do +// not use [Hasher], [MakeHasher], or [SetHasher] in new code. +func (m *Map) SetHasher(Hasher) {} + +// Delete removes the entry with the given key, if any. +// It returns true if the entry was found. +func (m *Map) Delete(key types.Type) bool { + if m != nil && m.table != nil { + hash := hash(key) + bucket := m.table[hash] + for i, e := range bucket { + if e.key != nil && types.Identical(key, e.key) { + // We can't compact the bucket as it + // would disturb iterators. + bucket[i] = entry{} + m.length-- + return true + } + } + } + return false +} + +// At returns the map entry for the given key. +// The result is nil if the entry is not present. +func (m *Map) At(key types.Type) any { + if m != nil && m.table != nil { + for _, e := range m.table[hash(key)] { + if e.key != nil && types.Identical(key, e.key) { + return e.value + } + } + } + return nil +} + +// Set sets the map entry for key to val, +// and returns the previous entry, if any. +func (m *Map) Set(key types.Type, value any) (prev any) { + if m.table != nil { + hash := hash(key) + bucket := m.table[hash] + var hole *entry + for i, e := range bucket { + if e.key == nil { + hole = &bucket[i] + } else if types.Identical(key, e.key) { + prev = e.value + bucket[i].value = value + return + } + } + + if hole != nil { + *hole = entry{key, value} // overwrite deleted entry + } else { + m.table[hash] = append(bucket, entry{key, value}) + } + } else { + hash := hash(key) + m.table = map[uint32][]entry{hash: {entry{key, value}}} + } + + m.length++ + return +} + +// Len returns the number of map entries. +func (m *Map) Len() int { + if m != nil { + return m.length + } + return 0 +} + +// Iterate calls function f on each entry in the map in unspecified order. +// +// If f should mutate the map, Iterate provides the same guarantees as +// Go maps: if f deletes a map entry that Iterate has not yet reached, +// f will not be invoked for it, but if f inserts a map entry that +// Iterate has not yet reached, whether or not f will be invoked for +// it is unspecified. +func (m *Map) Iterate(f func(key types.Type, value any)) { + if m != nil { + for _, bucket := range m.table { + for _, e := range bucket { + if e.key != nil { + f(e.key, e.value) + } + } + } + } +} + +// Keys returns a new slice containing the set of map keys. +// The order is unspecified. +func (m *Map) Keys() []types.Type { + keys := make([]types.Type, 0, m.Len()) + m.Iterate(func(key types.Type, _ any) { + keys = append(keys, key) + }) + return keys +} + +func (m *Map) toString(values bool) string { + if m == nil { + return "{}" + } + var buf bytes.Buffer + fmt.Fprint(&buf, "{") + sep := "" + m.Iterate(func(key types.Type, value any) { + fmt.Fprint(&buf, sep) + sep = ", " + fmt.Fprint(&buf, key) + if values { + fmt.Fprintf(&buf, ": %q", value) + } + }) + fmt.Fprint(&buf, "}") + return buf.String() +} + +// String returns a string representation of the map's entries. +// Values are printed using fmt.Sprintf("%v", v). +// Order is unspecified. +func (m *Map) String() string { + return m.toString(true) +} + +// KeysString returns a string representation of the map's key set. +// Order is unspecified. +func (m *Map) KeysString() string { + return m.toString(false) +} + +// -- Hasher -- + +// hash returns the hash of type t. +// TODO(adonovan): replace by types.Hash when Go proposal #69420 is accepted. +func hash(t types.Type) uint32 { + return theHasher.Hash(t) +} + +// A Hasher provides a [Hasher.Hash] method to map a type to its hash value. +// Hashers are stateless, and all are equivalent. +type Hasher struct{} + +var theHasher Hasher + +// MakeHasher returns Hasher{}. +// Hashers are stateless; all are equivalent. +func MakeHasher() Hasher { return theHasher } + +// Hash computes a hash value for the given type t such that +// Identical(t, t') => Hash(t) == Hash(t'). +func (h Hasher) Hash(t types.Type) uint32 { + return hasher{inGenericSig: false}.hash(t) +} + +// hasher holds the state of a single Hash traversal: whether we are +// inside the signature of a generic function; this is used to +// optimize [hasher.hashTypeParam]. +type hasher struct{ inGenericSig bool } + +// hashString computes the Fowler–Noll–Vo hash of s. +func hashString(s string) uint32 { + var h uint32 + for i := 0; i < len(s); i++ { + h ^= uint32(s[i]) + h *= 16777619 + } + return h +} + +// hash computes the hash of t. +func (h hasher) hash(t types.Type) uint32 { + // See Identical for rationale. + switch t := t.(type) { + case *types.Basic: + return uint32(t.Kind()) + + case *types.Alias: + return h.hash(types.Unalias(t)) + + case *types.Array: + return 9043 + 2*uint32(t.Len()) + 3*h.hash(t.Elem()) + + case *types.Slice: + return 9049 + 2*h.hash(t.Elem()) + + case *types.Struct: + var hash uint32 = 9059 + for i, n := 0, t.NumFields(); i < n; i++ { + f := t.Field(i) + if f.Anonymous() { + hash += 8861 + } + hash += hashString(t.Tag(i)) + hash += hashString(f.Name()) // (ignore f.Pkg) + hash += h.hash(f.Type()) + } + return hash + + case *types.Pointer: + return 9067 + 2*h.hash(t.Elem()) + + case *types.Signature: + var hash uint32 = 9091 + if t.Variadic() { + hash *= 8863 + } + + tparams := t.TypeParams() + for i := range tparams.Len() { + h.inGenericSig = true + tparam := tparams.At(i) + hash += 7 * h.hash(tparam.Constraint()) + } + + return hash + 3*h.hashTuple(t.Params()) + 5*h.hashTuple(t.Results()) + + case *types.Union: + return h.hashUnion(t) + + case *types.Interface: + // Interfaces are identical if they have the same set of methods, with + // identical names and types, and they have the same set of type + // restrictions. See go/types.identical for more details. + var hash uint32 = 9103 + + // Hash methods. + for i, n := 0, t.NumMethods(); i < n; i++ { + // Method order is not significant. + // Ignore m.Pkg(). + m := t.Method(i) + // Use shallow hash on method signature to + // avoid anonymous interface cycles. + hash += 3*hashString(m.Name()) + 5*h.shallowHash(m.Type()) + } + + // Hash type restrictions. + terms, err := typeparams.InterfaceTermSet(t) + // if err != nil t has invalid type restrictions. + if err == nil { + hash += h.hashTermSet(terms) + } + + return hash + + case *types.Map: + return 9109 + 2*h.hash(t.Key()) + 3*h.hash(t.Elem()) + + case *types.Chan: + return 9127 + 2*uint32(t.Dir()) + 3*h.hash(t.Elem()) + + case *types.Named: + hash := h.hashTypeName(t.Obj()) + targs := t.TypeArgs() + for i := 0; i < targs.Len(); i++ { + targ := targs.At(i) + hash += 2 * h.hash(targ) + } + return hash + + case *types.TypeParam: + return h.hashTypeParam(t) + + case *types.Tuple: + return h.hashTuple(t) + } + + panic(fmt.Sprintf("%T: %v", t, t)) +} + +func (h hasher) hashTuple(tuple *types.Tuple) uint32 { + // See go/types.identicalTypes for rationale. + n := tuple.Len() + hash := 9137 + 2*uint32(n) + for i := range n { + hash += 3 * h.hash(tuple.At(i).Type()) + } + return hash +} + +func (h hasher) hashUnion(t *types.Union) uint32 { + // Hash type restrictions. + terms, err := typeparams.UnionTermSet(t) + // if err != nil t has invalid type restrictions. Fall back on a non-zero + // hash. + if err != nil { + return 9151 + } + return h.hashTermSet(terms) +} + +func (h hasher) hashTermSet(terms []*types.Term) uint32 { + hash := 9157 + 2*uint32(len(terms)) + for _, term := range terms { + // term order is not significant. + termHash := h.hash(term.Type()) + if term.Tilde() { + termHash *= 9161 + } + hash += 3 * termHash + } + return hash +} + +// hashTypeParam returns the hash of a type parameter. +func (h hasher) hashTypeParam(t *types.TypeParam) uint32 { + // Within the signature of a generic function, TypeParams are + // identical if they have the same index and constraint, so we + // hash them based on index. + // + // When we are outside a generic function, free TypeParams are + // identical iff they are the same object, so we can use a + // more discriminating hash consistent with object identity. + // This optimization saves [Map] about 4% when hashing all the + // types.Info.Types in the forward closure of net/http. + if !h.inGenericSig { + // Optimization: outside a generic function signature, + // use a more discrimating hash consistent with object identity. + return h.hashTypeName(t.Obj()) + } + return 9173 + 3*uint32(t.Index()) +} + +var theSeed = maphash.MakeSeed() + +// hashTypeName hashes the pointer of tname. +func (hasher) hashTypeName(tname *types.TypeName) uint32 { + // Since types.Identical uses == to compare TypeNames, + // the Hash function uses maphash.Comparable. + // TODO(adonovan): or will, when it becomes available in go1.24. + // In the meantime we use the pointer's numeric value. + // + // hash := maphash.Comparable(theSeed, tname) + // + // (Another approach would be to hash the name and package + // path, and whether or not it is a package-level typename. It + // is rare for a package to define multiple local types with + // the same name.) + hash := uintptr(unsafe.Pointer(tname)) + return uint32(hash ^ (hash >> 32)) +} + +// shallowHash computes a hash of t without looking at any of its +// element Types, to avoid potential anonymous cycles in the types of +// interface methods. +// +// When an unnamed non-empty interface type appears anywhere among the +// arguments or results of an interface method, there is a potential +// for endless recursion. Consider: +// +// type X interface { m() []*interface { X } } +// +// The problem is that the Methods of the interface in m's result type +// include m itself; there is no mention of the named type X that +// might help us break the cycle. +// (See comment in go/types.identical, case *Interface, for more.) +func (h hasher) shallowHash(t types.Type) uint32 { + // t is the type of an interface method (Signature), + // its params or results (Tuples), or their immediate + // elements (mostly Slice, Pointer, Basic, Named), + // so there's no need to optimize anything else. + switch t := t.(type) { + case *types.Alias: + return h.shallowHash(types.Unalias(t)) + + case *types.Signature: + var hash uint32 = 604171 + if t.Variadic() { + hash *= 971767 + } + // The Signature/Tuple recursion is always finite + // and invariably shallow. + return hash + 1062599*h.shallowHash(t.Params()) + 1282529*h.shallowHash(t.Results()) + + case *types.Tuple: + n := t.Len() + hash := 9137 + 2*uint32(n) + for i := range n { + hash += 53471161 * h.shallowHash(t.At(i).Type()) + } + return hash + + case *types.Basic: + return 45212177 * uint32(t.Kind()) + + case *types.Array: + return 1524181 + 2*uint32(t.Len()) + + case *types.Slice: + return 2690201 + + case *types.Struct: + return 3326489 + + case *types.Pointer: + return 4393139 + + case *types.Union: + return 562448657 + + case *types.Interface: + return 2124679 // no recursion here + + case *types.Map: + return 9109 + + case *types.Chan: + return 9127 + + case *types.Named: + return h.hashTypeName(t.Obj()) + + case *types.TypeParam: + return h.hashTypeParam(t) + } + panic(fmt.Sprintf("shallowHash: %T: %v", t, t)) +} diff --git a/vendor/golang.org/x/tools/go/types/typeutil/methodsetcache.go b/vendor/golang.org/x/tools/go/types/typeutil/methodsetcache.go new file mode 100644 index 0000000000..f7666028fe --- /dev/null +++ b/vendor/golang.org/x/tools/go/types/typeutil/methodsetcache.go @@ -0,0 +1,71 @@ +// Copyright 2014 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. + +// This file implements a cache of method sets. + +package typeutil + +import ( + "go/types" + "sync" +) + +// A MethodSetCache records the method set of each type T for which +// MethodSet(T) is called so that repeat queries are fast. +// The zero value is a ready-to-use cache instance. +type MethodSetCache struct { + mu sync.Mutex + named map[*types.Named]struct{ value, pointer *types.MethodSet } // method sets for named N and *N + others map[types.Type]*types.MethodSet // all other types +} + +// MethodSet returns the method set of type T. It is thread-safe. +// +// If cache is nil, this function is equivalent to types.NewMethodSet(T). +// Utility functions can thus expose an optional *MethodSetCache +// parameter to clients that care about performance. +func (cache *MethodSetCache) MethodSet(T types.Type) *types.MethodSet { + if cache == nil { + return types.NewMethodSet(T) + } + cache.mu.Lock() + defer cache.mu.Unlock() + + switch T := types.Unalias(T).(type) { + case *types.Named: + return cache.lookupNamed(T).value + + case *types.Pointer: + if N, ok := types.Unalias(T.Elem()).(*types.Named); ok { + return cache.lookupNamed(N).pointer + } + } + + // all other types + // (The map uses pointer equivalence, not type identity.) + mset := cache.others[T] + if mset == nil { + mset = types.NewMethodSet(T) + if cache.others == nil { + cache.others = make(map[types.Type]*types.MethodSet) + } + cache.others[T] = mset + } + return mset +} + +func (cache *MethodSetCache) lookupNamed(named *types.Named) struct{ value, pointer *types.MethodSet } { + if cache.named == nil { + cache.named = make(map[*types.Named]struct{ value, pointer *types.MethodSet }) + } + // Avoid recomputing mset(*T) for each distinct Pointer + // instance whose underlying type is a named type. + msets, ok := cache.named[named] + if !ok { + msets.value = types.NewMethodSet(named) + msets.pointer = types.NewMethodSet(types.NewPointer(named)) + cache.named[named] = msets + } + return msets +} diff --git a/vendor/golang.org/x/tools/go/types/typeutil/ui.go b/vendor/golang.org/x/tools/go/types/typeutil/ui.go new file mode 100644 index 0000000000..9dda6a25df --- /dev/null +++ b/vendor/golang.org/x/tools/go/types/typeutil/ui.go @@ -0,0 +1,53 @@ +// Copyright 2014 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 typeutil + +// This file defines utilities for user interfaces that display types. + +import ( + "go/types" +) + +// IntuitiveMethodSet returns the intuitive method set of a type T, +// which is the set of methods you can call on an addressable value of +// that type. +// +// The result always contains MethodSet(T), and is exactly MethodSet(T) +// for interface types and for pointer-to-concrete types. +// For all other concrete types T, the result additionally +// contains each method belonging to *T if there is no identically +// named method on T itself. +// +// This corresponds to user intuition about method sets; +// this function is intended only for user interfaces. +// +// The order of the result is as for types.MethodSet(T). +func IntuitiveMethodSet(T types.Type, msets *MethodSetCache) []*types.Selection { + isPointerToConcrete := func(T types.Type) bool { + ptr, ok := types.Unalias(T).(*types.Pointer) + return ok && !types.IsInterface(ptr.Elem()) + } + + var result []*types.Selection + mset := msets.MethodSet(T) + if types.IsInterface(T) || isPointerToConcrete(T) { + for i, n := 0, mset.Len(); i < n; i++ { + result = append(result, mset.At(i)) + } + } else { + // T is some other concrete type. + // Report methods of T and *T, preferring those of T. + pmset := msets.MethodSet(types.NewPointer(T)) + for i, n := 0, pmset.Len(); i < n; i++ { + meth := pmset.At(i) + if m := mset.Lookup(meth.Obj().Pkg(), meth.Obj().Name()); m != nil { + meth = m + } + result = append(result, meth) + } + + } + return result +} diff --git a/vendor/golang.org/x/tools/internal/aliases/aliases.go b/vendor/golang.org/x/tools/internal/aliases/aliases.go index c24c2eee45..b9425f5a20 100644 --- a/vendor/golang.org/x/tools/internal/aliases/aliases.go +++ b/vendor/golang.org/x/tools/internal/aliases/aliases.go @@ -22,11 +22,17 @@ import ( // GODEBUG=gotypesalias=... by invoking the type checker. The Enabled // function is expensive and should be called once per task (e.g. // package import), not once per call to NewAlias. -func NewAlias(enabled bool, pos token.Pos, pkg *types.Package, name string, rhs types.Type) *types.TypeName { +// +// Precondition: enabled || len(tparams)==0. +// If materialized aliases are disabled, there must not be any type parameters. +func NewAlias(enabled bool, pos token.Pos, pkg *types.Package, name string, rhs types.Type, tparams []*types.TypeParam) *types.TypeName { if enabled { tname := types.NewTypeName(pos, pkg, name, nil) - newAlias(tname, rhs) + SetTypeParams(types.NewAlias(tname, rhs), tparams) return tname } + if len(tparams) > 0 { + panic("cannot create an alias with type parameters when gotypesalias is not enabled") + } return types.NewTypeName(pos, pkg, name, rhs) } diff --git a/vendor/golang.org/x/tools/internal/aliases/aliases_go121.go b/vendor/golang.org/x/tools/internal/aliases/aliases_go121.go deleted file mode 100644 index c027b9f315..0000000000 --- a/vendor/golang.org/x/tools/internal/aliases/aliases_go121.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2024 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. - -//go:build !go1.22 -// +build !go1.22 - -package aliases - -import ( - "go/types" -) - -// Alias is a placeholder for a go/types.Alias for <=1.21. -// It will never be created by go/types. -type Alias struct{} - -func (*Alias) String() string { panic("unreachable") } -func (*Alias) Underlying() types.Type { panic("unreachable") } -func (*Alias) Obj() *types.TypeName { panic("unreachable") } -func Rhs(alias *Alias) types.Type { panic("unreachable") } - -// Unalias returns the type t for go <=1.21. -func Unalias(t types.Type) types.Type { return t } - -func newAlias(name *types.TypeName, rhs types.Type) *Alias { panic("unreachable") } - -// Enabled reports whether [NewAlias] should create [types.Alias] types. -// -// Before go1.22, this function always returns false. -func Enabled() bool { return false } diff --git a/vendor/golang.org/x/tools/internal/aliases/aliases_go122.go b/vendor/golang.org/x/tools/internal/aliases/aliases_go122.go index b329954841..7716a3331d 100644 --- a/vendor/golang.org/x/tools/internal/aliases/aliases_go122.go +++ b/vendor/golang.org/x/tools/internal/aliases/aliases_go122.go @@ -2,9 +2,6 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build go1.22 -// +build go1.22 - package aliases import ( @@ -14,31 +11,51 @@ import ( "go/types" ) -// Alias is an alias of types.Alias. -type Alias = types.Alias - // Rhs returns the type on the right-hand side of the alias declaration. -func Rhs(alias *Alias) types.Type { +func Rhs(alias *types.Alias) types.Type { if alias, ok := any(alias).(interface{ Rhs() types.Type }); ok { return alias.Rhs() // go1.23+ } // go1.22's Alias didn't have the Rhs method, // so Unalias is the best we can do. - return Unalias(alias) + return types.Unalias(alias) +} + +// TypeParams returns the type parameter list of the alias. +func TypeParams(alias *types.Alias) *types.TypeParamList { + if alias, ok := any(alias).(interface{ TypeParams() *types.TypeParamList }); ok { + return alias.TypeParams() // go1.23+ + } + return nil +} + +// SetTypeParams sets the type parameters of the alias type. +func SetTypeParams(alias *types.Alias, tparams []*types.TypeParam) { + if alias, ok := any(alias).(interface { + SetTypeParams(tparams []*types.TypeParam) + }); ok { + alias.SetTypeParams(tparams) // go1.23+ + } else if len(tparams) > 0 { + panic("cannot set type parameters of an Alias type in go1.22") + } +} + +// TypeArgs returns the type arguments used to instantiate the Alias type. +func TypeArgs(alias *types.Alias) *types.TypeList { + if alias, ok := any(alias).(interface{ TypeArgs() *types.TypeList }); ok { + return alias.TypeArgs() // go1.23+ + } + return nil // empty (go1.22) } -// Unalias is a wrapper of types.Unalias. -func Unalias(t types.Type) types.Type { return types.Unalias(t) } - -// newAlias is an internal alias around types.NewAlias. -// Direct usage is discouraged as the moment. -// Try to use NewAlias instead. -func newAlias(tname *types.TypeName, rhs types.Type) *Alias { - a := types.NewAlias(tname, rhs) - // TODO(go.dev/issue/65455): Remove kludgy workaround to set a.actual as a side-effect. - Unalias(a) - return a +// Origin returns the generic Alias type of which alias is an instance. +// If alias is not an instance of a generic alias, Origin returns alias. +func Origin(alias *types.Alias) *types.Alias { + if alias, ok := any(alias).(interface{ Origin() *types.Alias }); ok { + return alias.Origin() // go1.23+ + } + return alias // not an instance of a generic alias (go1.22) } // Enabled reports whether [NewAlias] should create [types.Alias] types. @@ -56,7 +73,7 @@ func Enabled() bool { // many tests. Therefore any attempt to cache the result // is just incorrect. fset := token.NewFileSet() - f, _ := parser.ParseFile(fset, "a.go", "package p; type A = int", 0) + f, _ := parser.ParseFile(fset, "a.go", "package p; type A = int", parser.SkipObjectResolution) pkg, _ := new(types.Config).Check("p", fset, []*ast.File{f}, nil) _, enabled := pkg.Scope().Lookup("A").Type().(*types.Alias) return enabled diff --git a/vendor/golang.org/x/tools/internal/gcimporter/bimport.go b/vendor/golang.org/x/tools/internal/gcimporter/bimport.go index d98b0db2a9..d79a605ed1 100644 --- a/vendor/golang.org/x/tools/internal/gcimporter/bimport.go +++ b/vendor/golang.org/x/tools/internal/gcimporter/bimport.go @@ -87,64 +87,3 @@ func chanDir(d int) types.ChanDir { return 0 } } - -var predeclOnce sync.Once -var predecl []types.Type // initialized lazily - -func predeclared() []types.Type { - predeclOnce.Do(func() { - // initialize lazily to be sure that all - // elements have been initialized before - predecl = []types.Type{ // basic types - types.Typ[types.Bool], - types.Typ[types.Int], - types.Typ[types.Int8], - types.Typ[types.Int16], - types.Typ[types.Int32], - types.Typ[types.Int64], - types.Typ[types.Uint], - types.Typ[types.Uint8], - types.Typ[types.Uint16], - types.Typ[types.Uint32], - types.Typ[types.Uint64], - types.Typ[types.Uintptr], - types.Typ[types.Float32], - types.Typ[types.Float64], - types.Typ[types.Complex64], - types.Typ[types.Complex128], - types.Typ[types.String], - - // basic type aliases - types.Universe.Lookup("byte").Type(), - types.Universe.Lookup("rune").Type(), - - // error - types.Universe.Lookup("error").Type(), - - // untyped types - types.Typ[types.UntypedBool], - types.Typ[types.UntypedInt], - types.Typ[types.UntypedRune], - types.Typ[types.UntypedFloat], - types.Typ[types.UntypedComplex], - types.Typ[types.UntypedString], - types.Typ[types.UntypedNil], - - // package unsafe - types.Typ[types.UnsafePointer], - - // invalid type - types.Typ[types.Invalid], // only appears in packages with errors - - // used internally by gc; never used by this package or in .a files - anyType{}, - } - predecl = append(predecl, additionalPredeclared()...) - }) - return predecl -} - -type anyType struct{} - -func (t anyType) Underlying() types.Type { return t } -func (t anyType) String() string { return "any" } diff --git a/vendor/golang.org/x/tools/internal/gcimporter/exportdata.go b/vendor/golang.org/x/tools/internal/gcimporter/exportdata.go index f6437feb1c..5662a311da 100644 --- a/vendor/golang.org/x/tools/internal/gcimporter/exportdata.go +++ b/vendor/golang.org/x/tools/internal/gcimporter/exportdata.go @@ -2,49 +2,183 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// This file is a copy of $GOROOT/src/go/internal/gcimporter/exportdata.go. - -// This file implements FindExportData. +// This file should be kept in sync with $GOROOT/src/internal/exportdata/exportdata.go. +// This file also additionally implements FindExportData for gcexportdata.NewReader. package gcimporter import ( "bufio" + "bytes" + "errors" "fmt" + "go/build" "io" - "strconv" + "os" + "os/exec" + "path/filepath" "strings" + "sync" ) -func readGopackHeader(r *bufio.Reader) (name string, size int64, err error) { - // See $GOROOT/include/ar.h. - hdr := make([]byte, 16+12+6+6+8+10+2) - _, err = io.ReadFull(r, hdr) +// FindExportData positions the reader r at the beginning of the +// export data section of an underlying cmd/compile created archive +// file by reading from it. The reader must be positioned at the +// start of the file before calling this function. +// This returns the length of the export data in bytes. +// +// This function is needed by [gcexportdata.Read], which must +// accept inputs produced by the last two releases of cmd/compile, +// plus tip. +func FindExportData(r *bufio.Reader) (size int64, err error) { + arsize, err := FindPackageDefinition(r) + if err != nil { + return + } + size = int64(arsize) + + objapi, headers, err := ReadObjectHeaders(r) if err != nil { return } - // leave for debugging - if false { - fmt.Printf("header: %s", hdr) + size -= int64(len(objapi)) + for _, h := range headers { + size -= int64(len(h)) + } + + // Check for the binary export data section header "$$B\n". + // TODO(taking): Unify with ReadExportDataHeader so that it stops at the 'u' instead of reading + line, err := r.ReadSlice('\n') + if err != nil { + return + } + hdr := string(line) + if hdr != "$$B\n" { + err = fmt.Errorf("unknown export data header: %q", hdr) + return } - s := strings.TrimSpace(string(hdr[16+12+6+6+8:][:10])) - length, err := strconv.Atoi(s) - size = int64(length) - if err != nil || hdr[len(hdr)-2] != '`' || hdr[len(hdr)-1] != '\n' { - err = fmt.Errorf("invalid archive header") + size -= int64(len(hdr)) + + // For files with a binary export data header "$$B\n", + // these are always terminated by an end-of-section marker "\n$$\n". + // So the last bytes must always be this constant. + // + // The end-of-section marker is not a part of the export data itself. + // Do not include these in size. + // + // It would be nice to have sanity check that the final bytes after + // the export data are indeed the end-of-section marker. The split + // of gcexportdata.NewReader and gcexportdata.Read make checking this + // ugly so gcimporter gives up enforcing this. The compiler and go/types + // importer do enforce this, which seems good enough. + const endofsection = "\n$$\n" + size -= int64(len(endofsection)) + + if size < 0 { + err = fmt.Errorf("invalid size (%d) in the archive file: %d bytes remain without section headers (recompile package)", arsize, size) return } - name = strings.TrimSpace(string(hdr[:16])) + return } -// FindExportData positions the reader r at the beginning of the -// export data section of an underlying GC-created object/archive -// file by reading from it. The reader must be positioned at the -// start of the file before calling this function. The hdr result -// is the string before the export data, either "$$" or "$$B". -// The size result is the length of the export data in bytes, or -1 if not known. -func FindExportData(r *bufio.Reader) (hdr string, size int64, err error) { +// ReadUnified reads the contents of the unified export data from a reader r +// that contains the contents of a GC-created archive file. +// +// On success, the reader will be positioned after the end-of-section marker "\n$$\n". +// +// Supported GC-created archive files have 4 layers of nesting: +// - An archive file containing a package definition file. +// - The package definition file contains headers followed by a data section. +// Headers are lines (≤ 4kb) that do not start with "$$". +// - The data section starts with "$$B\n" followed by export data followed +// by an end of section marker "\n$$\n". (The section start "$$\n" is no +// longer supported.) +// - The export data starts with a format byte ('u') followed by the in +// the given format. (See ReadExportDataHeader for older formats.) +// +// Putting this together, the bytes in a GC-created archive files are expected +// to look like the following. +// See cmd/internal/archive for more details on ar file headers. +// +// | \n | ar file signature +// | __.PKGDEF...size...\n | ar header for __.PKGDEF including size. +// | go object <...>\n | objabi header +// | \n | other headers such as build id +// | $$B\n | binary format marker +// | u\n | unified export +// | $$\n | end-of-section marker +// | [optional padding] | padding byte (0x0A) if size is odd +// | [ar file header] | other ar files +// | [ar file data] | +func ReadUnified(r *bufio.Reader) (data []byte, err error) { + // We historically guaranteed headers at the default buffer size (4096) work. + // This ensures we can use ReadSlice throughout. + const minBufferSize = 4096 + r = bufio.NewReaderSize(r, minBufferSize) + + size, err := FindPackageDefinition(r) + if err != nil { + return + } + n := size + + objapi, headers, err := ReadObjectHeaders(r) + if err != nil { + return + } + n -= len(objapi) + for _, h := range headers { + n -= len(h) + } + + hdrlen, err := ReadExportDataHeader(r) + if err != nil { + return + } + n -= hdrlen + + // size also includes the end of section marker. Remove that many bytes from the end. + const marker = "\n$$\n" + n -= len(marker) + + if n < 0 { + err = fmt.Errorf("invalid size (%d) in the archive file: %d bytes remain without section headers (recompile package)", size, n) + return + } + + // Read n bytes from buf. + data = make([]byte, n) + _, err = io.ReadFull(r, data) + if err != nil { + return + } + + // Check for marker at the end. + var suffix [len(marker)]byte + _, err = io.ReadFull(r, suffix[:]) + if err != nil { + return + } + if s := string(suffix[:]); s != marker { + err = fmt.Errorf("read %q instead of end-of-section marker (%q)", s, marker) + return + } + + return +} + +// FindPackageDefinition positions the reader r at the beginning of a package +// definition file ("__.PKGDEF") within a GC-created archive by reading +// from it, and returns the size of the package definition file in the archive. +// +// The reader must be positioned at the start of the archive file before calling +// this function, and "__.PKGDEF" is assumed to be the first file in the archive. +// +// See cmd/internal/archive for details on the archive format. +func FindPackageDefinition(r *bufio.Reader) (size int, err error) { + // Uses ReadSlice to limit risk of malformed inputs. + // Read first line to make sure this is an object file. line, err := r.ReadSlice('\n') if err != nil { @@ -52,48 +186,236 @@ func FindExportData(r *bufio.Reader) (hdr string, size int64, err error) { return } - if string(line) == "!\n" { - // Archive file. Scan to __.PKGDEF. - var name string - if name, size, err = readGopackHeader(r); err != nil { - return - } + // Is the first line an archive file signature? + if string(line) != "!\n" { + err = fmt.Errorf("not the start of an archive file (%q)", line) + return + } + + // package export block should be first + size = readArchiveHeader(r, "__.PKGDEF") + if size <= 0 { + err = fmt.Errorf("not a package file") + return + } + + return +} - // First entry should be __.PKGDEF. - if name != "__.PKGDEF" { - err = fmt.Errorf("go archive is missing __.PKGDEF") +// ReadObjectHeaders reads object headers from the reader. Object headers are +// lines that do not start with an end-of-section marker "$$". The first header +// is the objabi header. On success, the reader will be positioned at the beginning +// of the end-of-section marker. +// +// It returns an error if any header does not fit in r.Size() bytes. +func ReadObjectHeaders(r *bufio.Reader) (objapi string, headers []string, err error) { + // line is a temporary buffer for headers. + // Use bounded reads (ReadSlice, Peek) to limit risk of malformed inputs. + var line []byte + + // objapi header should be the first line + if line, err = r.ReadSlice('\n'); err != nil { + err = fmt.Errorf("can't find export data (%v)", err) + return + } + objapi = string(line) + + // objapi header begins with "go object ". + if !strings.HasPrefix(objapi, "go object ") { + err = fmt.Errorf("not a go object file: %s", objapi) + return + } + + // process remaining object header lines + for { + // check for an end of section marker "$$" + line, err = r.Peek(2) + if err != nil { return } + if string(line) == "$$" { + return // stop + } - // Read first line of __.PKGDEF data, so that line - // is once again the first line of the input. - if line, err = r.ReadSlice('\n'); err != nil { - err = fmt.Errorf("can't find export data (%v)", err) + // read next header + line, err = r.ReadSlice('\n') + if err != nil { return } - size -= int64(len(line)) + headers = append(headers, string(line)) } +} - // Now at __.PKGDEF in archive or still at beginning of file. - // Either way, line should begin with "go object ". - if !strings.HasPrefix(string(line), "go object ") { - err = fmt.Errorf("not a Go object file") +// ReadExportDataHeader reads the export data header and format from r. +// It returns the number of bytes read, or an error if the format is no longer +// supported or it failed to read. +// +// The only currently supported format is binary export data in the +// unified export format. +func ReadExportDataHeader(r *bufio.Reader) (n int, err error) { + // Read export data header. + line, err := r.ReadSlice('\n') + if err != nil { return } - // Skip over object header to export data. - // Begins after first line starting with $$. - for line[0] != '$' { - if line, err = r.ReadSlice('\n'); err != nil { - err = fmt.Errorf("can't find export data (%v)", err) + hdr := string(line) + switch hdr { + case "$$\n": + err = fmt.Errorf("old textual export format no longer supported (recompile package)") + return + + case "$$B\n": + var format byte + format, err = r.ReadByte() + if err != nil { return } - size -= int64(len(line)) - } - hdr = string(line) - if size < 0 { - size = -1 + // The unified export format starts with a 'u'. + switch format { + case 'u': + default: + // Older no longer supported export formats include: + // indexed export format which started with an 'i'; and + // the older binary export format which started with a 'c', + // 'd', or 'v' (from "version"). + err = fmt.Errorf("binary export format %q is no longer supported (recompile package)", format) + return + } + + default: + err = fmt.Errorf("unknown export data header: %q", hdr) + return } + n = len(hdr) + 1 // + 1 is for 'u' return } + +// FindPkg returns the filename and unique package id for an import +// path based on package information provided by build.Import (using +// the build.Default build.Context). A relative srcDir is interpreted +// relative to the current working directory. +// +// FindPkg is only used in tests within x/tools. +func FindPkg(path, srcDir string) (filename, id string, err error) { + // TODO(taking): Move internal/exportdata.FindPkg into its own file, + // and then this copy into a _test package. + if path == "" { + return "", "", errors.New("path is empty") + } + + var noext string + switch { + default: + // "x" -> "$GOPATH/pkg/$GOOS_$GOARCH/x.ext", "x" + // Don't require the source files to be present. + if abs, err := filepath.Abs(srcDir); err == nil { // see issue 14282 + srcDir = abs + } + var bp *build.Package + bp, err = build.Import(path, srcDir, build.FindOnly|build.AllowBinary) + if bp.PkgObj == "" { + if bp.Goroot && bp.Dir != "" { + filename, err = lookupGorootExport(bp.Dir) + if err == nil { + _, err = os.Stat(filename) + } + if err == nil { + return filename, bp.ImportPath, nil + } + } + goto notfound + } else { + noext = strings.TrimSuffix(bp.PkgObj, ".a") + } + id = bp.ImportPath + + case build.IsLocalImport(path): + // "./x" -> "/this/directory/x.ext", "/this/directory/x" + noext = filepath.Join(srcDir, path) + id = noext + + case filepath.IsAbs(path): + // for completeness only - go/build.Import + // does not support absolute imports + // "/x" -> "/x.ext", "/x" + noext = path + id = path + } + + if false { // for debugging + if path != id { + fmt.Printf("%s -> %s\n", path, id) + } + } + + // try extensions + for _, ext := range pkgExts { + filename = noext + ext + f, statErr := os.Stat(filename) + if statErr == nil && !f.IsDir() { + return filename, id, nil + } + if err == nil { + err = statErr + } + } + +notfound: + if err == nil { + return "", path, fmt.Errorf("can't find import: %q", path) + } + return "", path, fmt.Errorf("can't find import: %q: %w", path, err) +} + +var pkgExts = [...]string{".a", ".o"} // a file from the build cache will have no extension + +var exportMap sync.Map // package dir → func() (string, error) + +// lookupGorootExport returns the location of the export data +// (normally found in the build cache, but located in GOROOT/pkg +// in prior Go releases) for the package located in pkgDir. +// +// (We use the package's directory instead of its import path +// mainly to simplify handling of the packages in src/vendor +// and cmd/vendor.) +// +// lookupGorootExport is only used in tests within x/tools. +func lookupGorootExport(pkgDir string) (string, error) { + f, ok := exportMap.Load(pkgDir) + if !ok { + var ( + listOnce sync.Once + exportPath string + err error + ) + f, _ = exportMap.LoadOrStore(pkgDir, func() (string, error) { + listOnce.Do(func() { + cmd := exec.Command(filepath.Join(build.Default.GOROOT, "bin", "go"), "list", "-export", "-f", "{{.Export}}", pkgDir) + cmd.Dir = build.Default.GOROOT + cmd.Env = append(os.Environ(), "PWD="+cmd.Dir, "GOROOT="+build.Default.GOROOT) + var output []byte + output, err = cmd.Output() + if err != nil { + if ee, ok := err.(*exec.ExitError); ok && len(ee.Stderr) > 0 { + err = errors.New(string(ee.Stderr)) + } + return + } + + exports := strings.Split(string(bytes.TrimSpace(output)), "\n") + if len(exports) != 1 { + err = fmt.Errorf("go list reported %d exports; expected 1", len(exports)) + return + } + + exportPath = exports[0] + }) + + return exportPath, err + }) + } + + return f.(func() (string, error))() +} diff --git a/vendor/golang.org/x/tools/internal/gcimporter/gcimporter.go b/vendor/golang.org/x/tools/internal/gcimporter/gcimporter.go index 39df91124a..3dbd21d1b9 100644 --- a/vendor/golang.org/x/tools/internal/gcimporter/gcimporter.go +++ b/vendor/golang.org/x/tools/internal/gcimporter/gcimporter.go @@ -23,17 +23,11 @@ package gcimporter // import "golang.org/x/tools/internal/gcimporter" import ( "bufio" - "bytes" "fmt" - "go/build" "go/token" "go/types" "io" "os" - "os/exec" - "path/filepath" - "strings" - "sync" ) const ( @@ -45,125 +39,14 @@ const ( trace = false ) -var exportMap sync.Map // package dir → func() (string, bool) - -// lookupGorootExport returns the location of the export data -// (normally found in the build cache, but located in GOROOT/pkg -// in prior Go releases) for the package located in pkgDir. -// -// (We use the package's directory instead of its import path -// mainly to simplify handling of the packages in src/vendor -// and cmd/vendor.) -func lookupGorootExport(pkgDir string) (string, bool) { - f, ok := exportMap.Load(pkgDir) - if !ok { - var ( - listOnce sync.Once - exportPath string - ) - f, _ = exportMap.LoadOrStore(pkgDir, func() (string, bool) { - listOnce.Do(func() { - cmd := exec.Command("go", "list", "-export", "-f", "{{.Export}}", pkgDir) - cmd.Dir = build.Default.GOROOT - var output []byte - output, err := cmd.Output() - if err != nil { - return - } - - exports := strings.Split(string(bytes.TrimSpace(output)), "\n") - if len(exports) != 1 { - return - } - - exportPath = exports[0] - }) - - return exportPath, exportPath != "" - }) - } - - return f.(func() (string, bool))() -} - -var pkgExts = [...]string{".a", ".o"} - -// FindPkg returns the filename and unique package id for an import -// path based on package information provided by build.Import (using -// the build.Default build.Context). A relative srcDir is interpreted -// relative to the current working directory. -// If no file was found, an empty filename is returned. -func FindPkg(path, srcDir string) (filename, id string) { - if path == "" { - return - } - - var noext string - switch { - default: - // "x" -> "$GOPATH/pkg/$GOOS_$GOARCH/x.ext", "x" - // Don't require the source files to be present. - if abs, err := filepath.Abs(srcDir); err == nil { // see issue 14282 - srcDir = abs - } - bp, _ := build.Import(path, srcDir, build.FindOnly|build.AllowBinary) - if bp.PkgObj == "" { - var ok bool - if bp.Goroot && bp.Dir != "" { - filename, ok = lookupGorootExport(bp.Dir) - } - if !ok { - id = path // make sure we have an id to print in error message - return - } - } else { - noext = strings.TrimSuffix(bp.PkgObj, ".a") - id = bp.ImportPath - } - - case build.IsLocalImport(path): - // "./x" -> "/this/directory/x.ext", "/this/directory/x" - noext = filepath.Join(srcDir, path) - id = noext - - case filepath.IsAbs(path): - // for completeness only - go/build.Import - // does not support absolute imports - // "/x" -> "/x.ext", "/x" - noext = path - id = path - } - - if false { // for debugging - if path != id { - fmt.Printf("%s -> %s\n", path, id) - } - } - - if filename != "" { - if f, err := os.Stat(filename); err == nil && !f.IsDir() { - return - } - } - - // try extensions - for _, ext := range pkgExts { - filename = noext + ext - if f, err := os.Stat(filename); err == nil && !f.IsDir() { - return - } - } - - filename = "" // not found - return -} - // Import imports a gc-generated package given its import path and srcDir, adds // the corresponding package object to the packages map, and returns the object. // The packages map must contain all packages already imported. -func Import(packages map[string]*types.Package, path, srcDir string, lookup func(path string) (io.ReadCloser, error)) (pkg *types.Package, err error) { +// +// Import is only used in tests. +func Import(fset *token.FileSet, packages map[string]*types.Package, path, srcDir string, lookup func(path string) (io.ReadCloser, error)) (pkg *types.Package, err error) { var rc io.ReadCloser - var filename, id string + var id string if lookup != nil { // With custom lookup specified, assume that caller has // converted path to a canonical import path for use in the map. @@ -182,12 +65,13 @@ func Import(packages map[string]*types.Package, path, srcDir string, lookup func } rc = f } else { - filename, id = FindPkg(path, srcDir) + var filename string + filename, id, err = FindPkg(path, srcDir) if filename == "" { if path == "unsafe" { return types.Unsafe, nil } - return nil, fmt.Errorf("can't find import: %q", id) + return nil, err } // no need to re-import if the package was imported completely before @@ -210,57 +94,15 @@ func Import(packages map[string]*types.Package, path, srcDir string, lookup func } defer rc.Close() - var hdr string - var size int64 buf := bufio.NewReader(rc) - if hdr, size, err = FindExportData(buf); err != nil { + data, err := ReadUnified(buf) + if err != nil { + err = fmt.Errorf("import %q: %v", path, err) return } - switch hdr { - case "$$B\n": - var data []byte - data, err = io.ReadAll(buf) - if err != nil { - break - } - - // TODO(gri): allow clients of go/importer to provide a FileSet. - // Or, define a new standard go/types/gcexportdata package. - fset := token.NewFileSet() - - // Select appropriate importer. - if len(data) > 0 { - switch data[0] { - case 'v', 'c', 'd': // binary, till go1.10 - return nil, fmt.Errorf("binary (%c) import format is no longer supported", data[0]) - - case 'i': // indexed, till go1.19 - _, pkg, err := IImportData(fset, packages, data[1:], id) - return pkg, err - - case 'u': // unified, from go1.20 - _, pkg, err := UImportData(fset, packages, data[1:size], id) - return pkg, err - - default: - l := len(data) - if l > 10 { - l = 10 - } - return nil, fmt.Errorf("unexpected export data with prefix %q for path %s", string(data[:l]), id) - } - } - - default: - err = fmt.Errorf("unknown export data header: %q", hdr) - } + // unified: emitted by cmd/compile since go1.20. + _, pkg, err = UImportData(fset, packages, data, id) return } - -type byPath []*types.Package - -func (a byPath) Len() int { return len(a) } -func (a byPath) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a byPath) Less(i, j int) bool { return a[i].Path() < a[j].Path() } diff --git a/vendor/golang.org/x/tools/internal/gcimporter/iexport.go b/vendor/golang.org/x/tools/internal/gcimporter/iexport.go index deeb67f315..7dfc31a37d 100644 --- a/vendor/golang.org/x/tools/internal/gcimporter/iexport.go +++ b/vendor/golang.org/x/tools/internal/gcimporter/iexport.go @@ -2,9 +2,227 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// Indexed binary package export. -// This file was derived from $GOROOT/src/cmd/compile/internal/gc/iexport.go; -// see that file for specification of the format. +// Indexed package export. +// +// The indexed export data format is an evolution of the previous +// binary export data format. Its chief contribution is introducing an +// index table, which allows efficient random access of individual +// declarations and inline function bodies. In turn, this allows +// avoiding unnecessary work for compilation units that import large +// packages. +// +// +// The top-level data format is structured as: +// +// Header struct { +// Tag byte // 'i' +// Version uvarint +// StringSize uvarint +// DataSize uvarint +// } +// +// Strings [StringSize]byte +// Data [DataSize]byte +// +// MainIndex []struct{ +// PkgPath stringOff +// PkgName stringOff +// PkgHeight uvarint +// +// Decls []struct{ +// Name stringOff +// Offset declOff +// } +// } +// +// Fingerprint [8]byte +// +// uvarint means a uint64 written out using uvarint encoding. +// +// []T means a uvarint followed by that many T objects. In other +// words: +// +// Len uvarint +// Elems [Len]T +// +// stringOff means a uvarint that indicates an offset within the +// Strings section. At that offset is another uvarint, followed by +// that many bytes, which form the string value. +// +// declOff means a uvarint that indicates an offset within the Data +// section where the associated declaration can be found. +// +// +// There are five kinds of declarations, distinguished by their first +// byte: +// +// type Var struct { +// Tag byte // 'V' +// Pos Pos +// Type typeOff +// } +// +// type Func struct { +// Tag byte // 'F' or 'G' +// Pos Pos +// TypeParams []typeOff // only present if Tag == 'G' +// Signature Signature +// } +// +// type Const struct { +// Tag byte // 'C' +// Pos Pos +// Value Value +// } +// +// type Type struct { +// Tag byte // 'T' or 'U' +// Pos Pos +// TypeParams []typeOff // only present if Tag == 'U' +// Underlying typeOff +// +// Methods []struct{ // omitted if Underlying is an interface type +// Pos Pos +// Name stringOff +// Recv Param +// Signature Signature +// } +// } +// +// type Alias struct { +// Tag byte // 'A' or 'B' +// Pos Pos +// TypeParams []typeOff // only present if Tag == 'B' +// Type typeOff +// } +// +// // "Automatic" declaration of each typeparam +// type TypeParam struct { +// Tag byte // 'P' +// Pos Pos +// Implicit bool +// Constraint typeOff +// } +// +// typeOff means a uvarint that either indicates a predeclared type, +// or an offset into the Data section. If the uvarint is less than +// predeclReserved, then it indicates the index into the predeclared +// types list (see predeclared in bexport.go for order). Otherwise, +// subtracting predeclReserved yields the offset of a type descriptor. +// +// Value means a type, kind, and type-specific value. See +// (*exportWriter).value for details. +// +// +// There are twelve kinds of type descriptors, distinguished by an itag: +// +// type DefinedType struct { +// Tag itag // definedType +// Name stringOff +// PkgPath stringOff +// } +// +// type PointerType struct { +// Tag itag // pointerType +// Elem typeOff +// } +// +// type SliceType struct { +// Tag itag // sliceType +// Elem typeOff +// } +// +// type ArrayType struct { +// Tag itag // arrayType +// Len uint64 +// Elem typeOff +// } +// +// type ChanType struct { +// Tag itag // chanType +// Dir uint64 // 1 RecvOnly; 2 SendOnly; 3 SendRecv +// Elem typeOff +// } +// +// type MapType struct { +// Tag itag // mapType +// Key typeOff +// Elem typeOff +// } +// +// type FuncType struct { +// Tag itag // signatureType +// PkgPath stringOff +// Signature Signature +// } +// +// type StructType struct { +// Tag itag // structType +// PkgPath stringOff +// Fields []struct { +// Pos Pos +// Name stringOff +// Type typeOff +// Embedded bool +// Note stringOff +// } +// } +// +// type InterfaceType struct { +// Tag itag // interfaceType +// PkgPath stringOff +// Embeddeds []struct { +// Pos Pos +// Type typeOff +// } +// Methods []struct { +// Pos Pos +// Name stringOff +// Signature Signature +// } +// } +// +// // Reference to a type param declaration +// type TypeParamType struct { +// Tag itag // typeParamType +// Name stringOff +// PkgPath stringOff +// } +// +// // Instantiation of a generic type (like List[T2] or List[int]) +// type InstanceType struct { +// Tag itag // instanceType +// Pos pos +// TypeArgs []typeOff +// BaseType typeOff +// } +// +// type UnionType struct { +// Tag itag // interfaceType +// Terms []struct { +// tilde bool +// Type typeOff +// } +// } +// +// +// +// type Signature struct { +// Params []Param +// Results []Param +// Variadic bool // omitted if Results is empty +// } +// +// type Param struct { +// Pos Pos +// Name stringOff +// Type typOff +// } +// +// +// Pos encodes a file:line:column triple, incorporating a simple delta +// encoding scheme within a data object. See exportWriter.pos for +// details. package gcimporter @@ -24,11 +242,30 @@ import ( "golang.org/x/tools/go/types/objectpath" "golang.org/x/tools/internal/aliases" - "golang.org/x/tools/internal/tokeninternal" ) // IExportShallow encodes "shallow" export data for the specified package. // +// For types, we use "shallow" export data. Historically, the Go +// compiler always produced a summary of the types for a given package +// that included types from other packages that it indirectly +// referenced: "deep" export data. This had the advantage that the +// compiler (and analogous tools such as gopls) need only load one +// file per direct import. However, it meant that the files tended to +// get larger based on the level of the package in the import +// graph. For example, higher-level packages in the kubernetes module +// have over 1MB of "deep" export data, even when they have almost no +// content of their own, merely because they mention a major type that +// references many others. In pathological cases the export data was +// 300x larger than the source for a package due to this quadratic +// growth. +// +// "Shallow" export data means that the serialized types describe only +// a single package. If those types mention types from other packages, +// the type checker may need to request additional packages beyond +// just the direct imports. Type information for the entire transitive +// closure of imports is provided (lazily) by the DAG. +// // No promises are made about the encoding other than that it can be decoded by // the same version of IIExportShallow. If you plan to save export data in the // file system, be sure to include a cryptographic digest of the executable in @@ -51,8 +288,8 @@ func IExportShallow(fset *token.FileSet, pkg *types.Package, reportf ReportFunc) } // IImportShallow decodes "shallow" types.Package data encoded by -// IExportShallow in the same executable. This function cannot import data from -// cmd/compile or gcexportdata.Write. +// [IExportShallow] in the same executable. This function cannot import data +// from cmd/compile or gcexportdata.Write. // // The importer calls getPackages to obtain package symbols for all // packages mentioned in the export data, including the one being @@ -223,7 +460,7 @@ func (p *iexporter) encodeFile(w *intWriter, file *token.File, needed []uint64) // Sort the set of needed offsets. Duplicates are harmless. sort.Slice(needed, func(i, j int) bool { return needed[i] < needed[j] }) - lines := tokeninternal.GetLines(file) // byte offset of each line start + lines := file.Lines() // byte offset of each line start w.uint64(uint64(len(lines))) // Rather than record the entire array of line start offsets, @@ -507,13 +744,13 @@ func (p *iexporter) doDecl(obj types.Object) { case *types.TypeName: t := obj.Type() - if tparam, ok := aliases.Unalias(t).(*types.TypeParam); ok { + if tparam, ok := types.Unalias(t).(*types.TypeParam); ok { w.tag(typeParamTag) w.pos(obj.Pos()) constraint := tparam.Constraint() if p.version >= iexportVersionGo1_18 { implicit := false - if iface, _ := aliases.Unalias(constraint).(*types.Interface); iface != nil { + if iface, _ := types.Unalias(constraint).(*types.Interface); iface != nil { implicit = iface.IsImplicit() } w.bool(implicit) @@ -523,9 +760,22 @@ func (p *iexporter) doDecl(obj types.Object) { } if obj.IsAlias() { - w.tag(aliasTag) + alias, materialized := t.(*types.Alias) // may fail when aliases are not enabled + + var tparams *types.TypeParamList + if materialized { + tparams = aliases.TypeParams(alias) + } + if tparams.Len() == 0 { + w.tag(aliasTag) + } else { + w.tag(genericAliasTag) + } w.pos(obj.Pos()) - if alias, ok := t.(*aliases.Alias); ok { + if tparams.Len() > 0 { + w.tparamList(obj.Name(), tparams, obj.Pkg()) + } + if materialized { // Preserve materialized aliases, // even of non-exported types. t = aliases.Rhs(alias) @@ -744,8 +994,14 @@ func (w *exportWriter) doTyp(t types.Type, pkg *types.Package) { }() } switch t := t.(type) { - case *aliases.Alias: - // TODO(adonovan): support parameterized aliases, following *types.Named. + case *types.Alias: + if targs := aliases.TypeArgs(t); targs.Len() > 0 { + w.startType(instanceType) + w.pos(t.Obj().Pos()) + w.typeList(targs, pkg) + w.typ(aliases.Origin(t), pkg) + return + } w.startType(aliasType) w.qualifiedType(t.Obj()) @@ -854,7 +1110,7 @@ func (w *exportWriter) doTyp(t types.Type, pkg *types.Package) { for i := 0; i < n; i++ { ft := t.EmbeddedType(i) tPkg := pkg - if named, _ := aliases.Unalias(ft).(*types.Named); named != nil { + if named, _ := types.Unalias(ft).(*types.Named); named != nil { w.pos(named.Obj().Pos()) } else { w.pos(token.NoPos) diff --git a/vendor/golang.org/x/tools/internal/gcimporter/iimport.go b/vendor/golang.org/x/tools/internal/gcimporter/iimport.go index 136aa03653..69b1d697cb 100644 --- a/vendor/golang.org/x/tools/internal/gcimporter/iimport.go +++ b/vendor/golang.org/x/tools/internal/gcimporter/iimport.go @@ -3,9 +3,7 @@ // license that can be found in the LICENSE file. // Indexed package import. -// See cmd/compile/internal/gc/iexport.go for the export data format. - -// This file is a copy of $GOROOT/src/go/internal/gcimporter/iimport.go. +// See iexport.go for the export data format. package gcimporter @@ -53,6 +51,7 @@ const ( iexportVersionPosCol = 1 iexportVersionGo1_18 = 2 iexportVersionGenerics = 2 + iexportVersion = iexportVersionGenerics iexportVersionCurrent = 2 ) @@ -540,7 +539,7 @@ func canReuse(def *types.Named, rhs types.Type) bool { if def == nil { return true } - iface, _ := aliases.Unalias(rhs).(*types.Interface) + iface, _ := types.Unalias(rhs).(*types.Interface) if iface == nil { return true } @@ -557,19 +556,28 @@ type importReader struct { prevColumn int64 } +// markBlack is redefined in iimport_go123.go, to work around golang/go#69912. +// +// If TypeNames are not marked black (in the sense of go/types cycle +// detection), they may be mutated when dot-imported. Fix this by punching a +// hole through the type, when compiling with Go 1.23. (The bug has been fixed +// for 1.24, but the fix was not worth back-porting). +var markBlack = func(name *types.TypeName) {} + func (r *importReader) obj(name string) { tag := r.byte() pos := r.pos() switch tag { - case aliasTag: + case aliasTag, genericAliasTag: + var tparams []*types.TypeParam + if tag == genericAliasTag { + tparams = r.tparamList() + } typ := r.typ() - // TODO(adonovan): support generic aliases: - // if tag == genericAliasTag { - // tparams := r.tparamList() - // alias.SetTypeParams(tparams) - // } - r.declare(aliases.NewAlias(r.p.aliases, pos, r.currPkg, name, typ)) + obj := aliases.NewAlias(r.p.aliases, pos, r.currPkg, name, typ, tparams) + markBlack(obj) // workaround for golang/go#69912 + r.declare(obj) case constTag: typ, val := r.value() @@ -589,6 +597,9 @@ func (r *importReader) obj(name string) { // declaration before recursing. obj := types.NewTypeName(pos, r.currPkg, name, nil) named := types.NewNamed(obj, nil, nil) + + markBlack(obj) // workaround for golang/go#69912 + // Declare obj before calling r.tparamList, so the new type name is recognized // if used in the constraint of one of its own typeparams (see #48280). r.declare(obj) @@ -615,7 +626,7 @@ func (r *importReader) obj(name string) { if targs.Len() > 0 { rparams = make([]*types.TypeParam, targs.Len()) for i := range rparams { - rparams[i] = aliases.Unalias(targs.At(i)).(*types.TypeParam) + rparams[i] = types.Unalias(targs.At(i)).(*types.TypeParam) } } msig := r.signature(recv, rparams, nil) @@ -645,7 +656,7 @@ func (r *importReader) obj(name string) { } constraint := r.typ() if implicit { - iface, _ := aliases.Unalias(constraint).(*types.Interface) + iface, _ := types.Unalias(constraint).(*types.Interface) if iface == nil { errorf("non-interface constraint marked implicit") } @@ -852,7 +863,7 @@ func (r *importReader) typ() types.Type { } func isInterface(t types.Type) bool { - _, ok := aliases.Unalias(t).(*types.Interface) + _, ok := types.Unalias(t).(*types.Interface) return ok } @@ -862,7 +873,7 @@ func (r *importReader) string() string { return r.p.stringAt(r.uint64()) } func (r *importReader) doType(base *types.Named) (res types.Type) { k := r.kind() if debug { - r.p.trace("importing type %d (base: %s)", k, base) + r.p.trace("importing type %d (base: %v)", k, base) r.p.indent++ defer func() { r.p.indent-- @@ -959,7 +970,7 @@ func (r *importReader) doType(base *types.Named) (res types.Type) { methods[i] = method } - typ := newInterface(methods, embeddeds) + typ := types.NewInterfaceType(methods, embeddeds) r.p.interfaceList = append(r.p.interfaceList, typ) return typ @@ -1051,7 +1062,7 @@ func (r *importReader) tparamList() []*types.TypeParam { for i := range xs { // Note: the standard library importer is tolerant of nil types here, // though would panic in SetTypeParams. - xs[i] = aliases.Unalias(r.typ()).(*types.TypeParam) + xs[i] = types.Unalias(r.typ()).(*types.TypeParam) } return xs } @@ -1098,3 +1109,9 @@ func (r *importReader) byte() byte { } return x } + +type byPath []*types.Package + +func (a byPath) Len() int { return len(a) } +func (a byPath) Swap(i, j int) { a[i], a[j] = a[j], a[i] } +func (a byPath) Less(i, j int) bool { return a[i].Path() < a[j].Path() } diff --git a/vendor/golang.org/x/tools/internal/gcimporter/iimport_go122.go b/vendor/golang.org/x/tools/internal/gcimporter/iimport_go122.go new file mode 100644 index 0000000000..7586bfaca6 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/gcimporter/iimport_go122.go @@ -0,0 +1,53 @@ +// Copyright 2024 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. + +//go:build go1.22 && !go1.24 + +package gcimporter + +import ( + "go/token" + "go/types" + "unsafe" +) + +// TODO(rfindley): delete this workaround once go1.24 is assured. + +func init() { + // Update markBlack so that it correctly sets the color + // of imported TypeNames. + // + // See the doc comment for markBlack for details. + + type color uint32 + const ( + white color = iota + black + grey + ) + type object struct { + _ *types.Scope + _ token.Pos + _ *types.Package + _ string + _ types.Type + _ uint32 + color_ color + _ token.Pos + } + type typeName struct { + object + } + + // If the size of types.TypeName changes, this will fail to compile. + const delta = int64(unsafe.Sizeof(typeName{})) - int64(unsafe.Sizeof(types.TypeName{})) + var _ [-delta * delta]int + + markBlack = func(obj *types.TypeName) { + type uP = unsafe.Pointer + var ptr *typeName + *(*uP)(uP(&ptr)) = uP(obj) + ptr.color_ = black + } +} diff --git a/vendor/golang.org/x/tools/internal/gcimporter/newInterface10.go b/vendor/golang.org/x/tools/internal/gcimporter/newInterface10.go deleted file mode 100644 index 8b163e3d05..0000000000 --- a/vendor/golang.org/x/tools/internal/gcimporter/newInterface10.go +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2018 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. - -//go:build !go1.11 -// +build !go1.11 - -package gcimporter - -import "go/types" - -func newInterface(methods []*types.Func, embeddeds []types.Type) *types.Interface { - named := make([]*types.Named, len(embeddeds)) - for i, e := range embeddeds { - var ok bool - named[i], ok = e.(*types.Named) - if !ok { - panic("embedding of non-defined interfaces in interfaces is not supported before Go 1.11") - } - } - return types.NewInterface(methods, named) -} diff --git a/vendor/golang.org/x/tools/internal/gcimporter/newInterface11.go b/vendor/golang.org/x/tools/internal/gcimporter/newInterface11.go deleted file mode 100644 index 49984f40fd..0000000000 --- a/vendor/golang.org/x/tools/internal/gcimporter/newInterface11.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2018 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. - -//go:build go1.11 -// +build go1.11 - -package gcimporter - -import "go/types" - -func newInterface(methods []*types.Func, embeddeds []types.Type) *types.Interface { - return types.NewInterfaceType(methods, embeddeds) -} diff --git a/vendor/golang.org/x/tools/internal/gcimporter/predeclared.go b/vendor/golang.org/x/tools/internal/gcimporter/predeclared.go new file mode 100644 index 0000000000..907c8557a5 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/gcimporter/predeclared.go @@ -0,0 +1,91 @@ +// Copyright 2024 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 gcimporter + +import ( + "go/types" + "sync" +) + +// predecl is a cache for the predeclared types in types.Universe. +// +// Cache a distinct result based on the runtime value of any. +// The pointer value of the any type varies based on GODEBUG settings. +var predeclMu sync.Mutex +var predecl map[types.Type][]types.Type + +func predeclared() []types.Type { + anyt := types.Universe.Lookup("any").Type() + + predeclMu.Lock() + defer predeclMu.Unlock() + + if pre, ok := predecl[anyt]; ok { + return pre + } + + if predecl == nil { + predecl = make(map[types.Type][]types.Type) + } + + decls := []types.Type{ // basic types + types.Typ[types.Bool], + types.Typ[types.Int], + types.Typ[types.Int8], + types.Typ[types.Int16], + types.Typ[types.Int32], + types.Typ[types.Int64], + types.Typ[types.Uint], + types.Typ[types.Uint8], + types.Typ[types.Uint16], + types.Typ[types.Uint32], + types.Typ[types.Uint64], + types.Typ[types.Uintptr], + types.Typ[types.Float32], + types.Typ[types.Float64], + types.Typ[types.Complex64], + types.Typ[types.Complex128], + types.Typ[types.String], + + // basic type aliases + types.Universe.Lookup("byte").Type(), + types.Universe.Lookup("rune").Type(), + + // error + types.Universe.Lookup("error").Type(), + + // untyped types + types.Typ[types.UntypedBool], + types.Typ[types.UntypedInt], + types.Typ[types.UntypedRune], + types.Typ[types.UntypedFloat], + types.Typ[types.UntypedComplex], + types.Typ[types.UntypedString], + types.Typ[types.UntypedNil], + + // package unsafe + types.Typ[types.UnsafePointer], + + // invalid type + types.Typ[types.Invalid], // only appears in packages with errors + + // used internally by gc; never used by this package or in .a files + anyType{}, + + // comparable + types.Universe.Lookup("comparable").Type(), + + // any + anyt, + } + + predecl[anyt] = decls + return decls +} + +type anyType struct{} + +func (t anyType) Underlying() types.Type { return t } +func (t anyType) String() string { return "any" } diff --git a/vendor/golang.org/x/tools/internal/gcimporter/support.go b/vendor/golang.org/x/tools/internal/gcimporter/support.go new file mode 100644 index 0000000000..4af810dc41 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/gcimporter/support.go @@ -0,0 +1,30 @@ +// Copyright 2024 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 gcimporter + +import ( + "bufio" + "io" + "strconv" + "strings" +) + +// Copy of $GOROOT/src/cmd/internal/archive.ReadHeader. +func readArchiveHeader(b *bufio.Reader, name string) int { + // architecture-independent object file output + const HeaderSize = 60 + + var buf [HeaderSize]byte + if _, err := io.ReadFull(b, buf[:]); err != nil { + return -1 + } + aname := strings.Trim(string(buf[0:16]), " ") + if !strings.HasPrefix(aname, name) { + return -1 + } + asize := strings.Trim(string(buf[48:58]), " ") + i, _ := strconv.Atoi(asize) + return i +} diff --git a/vendor/golang.org/x/tools/internal/gcimporter/support_go118.go b/vendor/golang.org/x/tools/internal/gcimporter/support_go118.go deleted file mode 100644 index 0cd3b91b65..0000000000 --- a/vendor/golang.org/x/tools/internal/gcimporter/support_go118.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2021 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 gcimporter - -import "go/types" - -const iexportVersion = iexportVersionGenerics - -// additionalPredeclared returns additional predeclared types in go.1.18. -func additionalPredeclared() []types.Type { - return []types.Type{ - // comparable - types.Universe.Lookup("comparable").Type(), - - // any - types.Universe.Lookup("any").Type(), - } -} - -// See cmd/compile/internal/types.SplitVargenSuffix. -func splitVargenSuffix(name string) (base, suffix string) { - i := len(name) - for i > 0 && name[i-1] >= '0' && name[i-1] <= '9' { - i-- - } - const dot = "·" - if i >= len(dot) && name[i-len(dot):i] == dot { - i -= len(dot) - return name[:i], name[i:] - } - return name, "" -} diff --git a/vendor/golang.org/x/tools/internal/gcimporter/unified_no.go b/vendor/golang.org/x/tools/internal/gcimporter/unified_no.go deleted file mode 100644 index 38b624cada..0000000000 --- a/vendor/golang.org/x/tools/internal/gcimporter/unified_no.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2022 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. - -//go:build !goexperiment.unified -// +build !goexperiment.unified - -package gcimporter - -const unifiedIR = false diff --git a/vendor/golang.org/x/tools/internal/gcimporter/unified_yes.go b/vendor/golang.org/x/tools/internal/gcimporter/unified_yes.go deleted file mode 100644 index b5118d0b3a..0000000000 --- a/vendor/golang.org/x/tools/internal/gcimporter/unified_yes.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2022 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. - -//go:build goexperiment.unified -// +build goexperiment.unified - -package gcimporter - -const unifiedIR = true diff --git a/vendor/golang.org/x/tools/internal/gcimporter/ureader_yes.go b/vendor/golang.org/x/tools/internal/gcimporter/ureader_yes.go index 2c07706887..6cdab448ec 100644 --- a/vendor/golang.org/x/tools/internal/gcimporter/ureader_yes.go +++ b/vendor/golang.org/x/tools/internal/gcimporter/ureader_yes.go @@ -11,7 +11,6 @@ import ( "go/token" "go/types" "sort" - "strings" "golang.org/x/tools/internal/aliases" "golang.org/x/tools/internal/pkgbits" @@ -52,8 +51,7 @@ func (pr *pkgReader) later(fn func()) { // See cmd/compile/internal/noder.derivedInfo. type derivedInfo struct { - idx pkgbits.Index - needed bool + idx pkgbits.Index } // See cmd/compile/internal/noder.typeInfo. @@ -72,7 +70,6 @@ func UImportData(fset *token.FileSet, imports map[string]*types.Package, data [] } s := string(data) - s = s[:strings.LastIndex(s, "\n$$\n")] input := pkgbits.NewPkgDecoder(path, s) pkg = readUnifiedPackage(fset, nil, imports, input) return @@ -110,13 +107,17 @@ func readUnifiedPackage(fset *token.FileSet, ctxt *types.Context, imports map[st r := pr.newReader(pkgbits.RelocMeta, pkgbits.PublicRootIdx, pkgbits.SyncPublic) pkg := r.pkg() - r.Bool() // has init + if r.Version().Has(pkgbits.HasInit) { + r.Bool() + } for i, n := 0, r.Len(); i < n; i++ { // As if r.obj(), but avoiding the Scope.Lookup call, // to avoid eager loading of imports. r.Sync(pkgbits.SyncObject) - assert(!r.Bool()) + if r.Version().Has(pkgbits.DerivedFuncInstance) { + assert(!r.Bool()) + } r.p.objIdx(r.Reloc(pkgbits.RelocObj)) assert(r.Len() == 0) } @@ -165,7 +166,7 @@ type readerDict struct { // tparams is a slice of the constructed TypeParams for the element. tparams []*types.TypeParam - // devived is a slice of types derived from tparams, which may be + // derived is a slice of types derived from tparams, which may be // instantiated while reading the current element. derived []derivedInfo derivedTypes []types.Type // lazily instantiated from derived @@ -263,7 +264,12 @@ func (pr *pkgReader) pkgIdx(idx pkgbits.Index) *types.Package { func (r *reader) doPkg() *types.Package { path := r.String() switch path { - case "": + // cmd/compile emits path="main" for main packages because + // that's the linker symbol prefix it used; but we need + // the package's path as it would be reported by go list, + // hence "main" below. + // See test at go/packages.TestMainPackagePathInModeTypes. + case "", "main": path = r.p.PkgPath() case "builtin": return nil // universe @@ -471,7 +477,9 @@ func (r *reader) param() *types.Var { func (r *reader) obj() (types.Object, []types.Type) { r.Sync(pkgbits.SyncObject) - assert(!r.Bool()) + if r.Version().Has(pkgbits.DerivedFuncInstance) { + assert(!r.Bool()) + } pkg, name := r.p.objIdx(r.Reloc(pkgbits.RelocObj)) obj := pkgScope(pkg).Lookup(name) @@ -525,8 +533,12 @@ func (pr *pkgReader) objIdx(idx pkgbits.Index) (*types.Package, string) { case pkgbits.ObjAlias: pos := r.pos() + var tparams []*types.TypeParam + if r.Version().Has(pkgbits.AliasTypeParamNames) { + tparams = r.typeParamNames() + } typ := r.typ() - declare(aliases.NewAlias(r.p.aliases, pos, objPkg, objName, typ)) + declare(aliases.NewAlias(r.p.aliases, pos, objPkg, objName, typ, tparams)) case pkgbits.ObjConst: pos := r.pos() @@ -553,7 +565,7 @@ func (pr *pkgReader) objIdx(idx pkgbits.Index) (*types.Package, string) { // If the underlying type is an interface, we need to // duplicate its methods so we can replace the receiver // parameter's type (#49906). - if iface, ok := aliases.Unalias(underlying).(*types.Interface); ok && iface.NumExplicitMethods() != 0 { + if iface, ok := types.Unalias(underlying).(*types.Interface); ok && iface.NumExplicitMethods() != 0 { methods := make([]*types.Func, iface.NumExplicitMethods()) for i := range methods { fn := iface.ExplicitMethod(i) @@ -632,7 +644,10 @@ func (pr *pkgReader) objDictIdx(idx pkgbits.Index) *readerDict { dict.derived = make([]derivedInfo, r.Len()) dict.derivedTypes = make([]types.Type, len(dict.derived)) for i := range dict.derived { - dict.derived[i] = derivedInfo{r.Reloc(pkgbits.RelocType), r.Bool()} + dict.derived[i] = derivedInfo{idx: r.Reloc(pkgbits.RelocType)} + if r.Version().Has(pkgbits.DerivedInfoNeeded) { + assert(!r.Bool()) + } } pr.retireReader(r) @@ -726,3 +741,17 @@ func pkgScope(pkg *types.Package) *types.Scope { } return types.Universe } + +// See cmd/compile/internal/types.SplitVargenSuffix. +func splitVargenSuffix(name string) (base, suffix string) { + i := len(name) + for i > 0 && name[i-1] >= '0' && name[i-1] <= '9' { + i-- + } + const dot = "·" + if i >= len(dot) && name[i-len(dot):i] == dot { + i -= len(dot) + return name[:i], name[i:] + } + return name, "" +} diff --git a/vendor/golang.org/x/tools/internal/gocommand/invoke.go b/vendor/golang.org/x/tools/internal/gocommand/invoke.go index 2e59ff8558..e333efc87f 100644 --- a/vendor/golang.org/x/tools/internal/gocommand/invoke.go +++ b/vendor/golang.org/x/tools/internal/gocommand/invoke.go @@ -16,7 +16,6 @@ import ( "os" "os/exec" "path/filepath" - "reflect" "regexp" "runtime" "strconv" @@ -250,16 +249,13 @@ func (i *Invocation) run(ctx context.Context, stdout, stderr io.Writer) error { cmd.Stdout = stdout cmd.Stderr = stderr - // cmd.WaitDelay was added only in go1.20 (see #50436). - if waitDelay := reflect.ValueOf(cmd).Elem().FieldByName("WaitDelay"); waitDelay.IsValid() { - // https://go.dev/issue/59541: don't wait forever copying stderr - // after the command has exited. - // After CL 484741 we copy stdout manually, so we we'll stop reading that as - // soon as ctx is done. However, we also don't want to wait around forever - // for stderr. Give a much-longer-than-reasonable delay and then assume that - // something has wedged in the kernel or runtime. - waitDelay.Set(reflect.ValueOf(30 * time.Second)) - } + // https://go.dev/issue/59541: don't wait forever copying stderr + // after the command has exited. + // After CL 484741 we copy stdout manually, so we we'll stop reading that as + // soon as ctx is done. However, we also don't want to wait around forever + // for stderr. Give a much-longer-than-reasonable delay and then assume that + // something has wedged in the kernel or runtime. + cmd.WaitDelay = 30 * time.Second // The cwd gets resolved to the real path. On Darwin, where // /tmp is a symlink, this breaks anything that expects the diff --git a/vendor/golang.org/x/tools/internal/packagesinternal/packages.go b/vendor/golang.org/x/tools/internal/packagesinternal/packages.go index 44719de173..66e69b4389 100644 --- a/vendor/golang.org/x/tools/internal/packagesinternal/packages.go +++ b/vendor/golang.org/x/tools/internal/packagesinternal/packages.go @@ -5,7 +5,6 @@ // Package packagesinternal exposes internal-only fields from go/packages. package packagesinternal -var GetForTest = func(p interface{}) string { return "" } var GetDepsErrors = func(p interface{}) []*PackageError { return nil } type PackageError struct { @@ -16,7 +15,6 @@ type PackageError struct { var TypecheckCgo int var DepsErrors int // must be set as a LoadMode to call GetDepsErrors -var ForTest int // must be set as a LoadMode to call GetForTest var SetModFlag = func(config interface{}, value string) {} var SetModFile = func(config interface{}, value string) {} diff --git a/vendor/golang.org/x/tools/internal/pkgbits/decoder.go b/vendor/golang.org/x/tools/internal/pkgbits/decoder.go index 2acd85851e..f6cb37c5c3 100644 --- a/vendor/golang.org/x/tools/internal/pkgbits/decoder.go +++ b/vendor/golang.org/x/tools/internal/pkgbits/decoder.go @@ -21,10 +21,7 @@ import ( // export data. type PkgDecoder struct { // version is the file format version. - version uint32 - - // aliases determines whether types.Aliases should be created - aliases bool + version Version // sync indicates whether the file uses sync markers. sync bool @@ -71,12 +68,9 @@ func (pr *PkgDecoder) SyncMarkers() bool { return pr.sync } // NewPkgDecoder returns a PkgDecoder initialized to read the Unified // IR export data from input. pkgPath is the package path for the // compilation unit that produced the export data. -// -// TODO(mdempsky): Remove pkgPath parameter; unneeded since CL 391014. func NewPkgDecoder(pkgPath, input string) PkgDecoder { pr := PkgDecoder{ pkgPath: pkgPath, - //aliases: aliases.Enabled(), } // TODO(mdempsky): Implement direct indexing of input string to @@ -84,14 +78,15 @@ func NewPkgDecoder(pkgPath, input string) PkgDecoder { r := strings.NewReader(input) - assert(binary.Read(r, binary.LittleEndian, &pr.version) == nil) + var ver uint32 + assert(binary.Read(r, binary.LittleEndian, &ver) == nil) + pr.version = Version(ver) - switch pr.version { - default: - panic(fmt.Errorf("unsupported version: %v", pr.version)) - case 0: - // no flags - case 1: + if pr.version >= numVersions { + panic(fmt.Errorf("cannot decode %q, export data version %d is greater than maximum supported version %d", pkgPath, pr.version, numVersions-1)) + } + + if pr.version.Has(Flags) { var flags uint32 assert(binary.Read(r, binary.LittleEndian, &flags) == nil) pr.sync = flags&flagSyncMarkers != 0 @@ -106,7 +101,9 @@ func NewPkgDecoder(pkgPath, input string) PkgDecoder { assert(err == nil) pr.elemData = input[pos:] - assert(len(pr.elemData)-8 == int(pr.elemEnds[len(pr.elemEnds)-1])) + + const fingerprintSize = 8 + assert(len(pr.elemData)-fingerprintSize == int(pr.elemEnds[len(pr.elemEnds)-1])) return pr } @@ -140,7 +137,7 @@ func (pr *PkgDecoder) AbsIdx(k RelocKind, idx Index) int { absIdx += int(pr.elemEndsEnds[k-1]) } if absIdx >= int(pr.elemEndsEnds[k]) { - errorf("%v:%v is out of bounds; %v", k, idx, pr.elemEndsEnds) + panicf("%v:%v is out of bounds; %v", k, idx, pr.elemEndsEnds) } return absIdx } @@ -197,9 +194,7 @@ func (pr *PkgDecoder) NewDecoderRaw(k RelocKind, idx Index) Decoder { Idx: idx, } - // TODO(mdempsky) r.data.Reset(...) after #44505 is resolved. - r.Data = *strings.NewReader(pr.DataIdx(k, idx)) - + r.Data.Reset(pr.DataIdx(k, idx)) r.Sync(SyncRelocs) r.Relocs = make([]RelocEnt, r.Len()) for i := range r.Relocs { @@ -248,7 +243,7 @@ type Decoder struct { func (r *Decoder) checkErr(err error) { if err != nil { - errorf("unexpected decoding error: %w", err) + panicf("unexpected decoding error: %w", err) } } @@ -519,3 +514,6 @@ func (pr *PkgDecoder) PeekObj(idx Index) (string, string, CodeObj) { return path, name, tag } + +// Version reports the version of the bitstream. +func (w *Decoder) Version() Version { return w.common.version } diff --git a/vendor/golang.org/x/tools/internal/pkgbits/encoder.go b/vendor/golang.org/x/tools/internal/pkgbits/encoder.go index 6482617a4f..c17a12399d 100644 --- a/vendor/golang.org/x/tools/internal/pkgbits/encoder.go +++ b/vendor/golang.org/x/tools/internal/pkgbits/encoder.go @@ -12,18 +12,15 @@ import ( "io" "math/big" "runtime" + "strings" ) -// currentVersion is the current version number. -// -// - v0: initial prototype -// -// - v1: adds the flags uint32 word -const currentVersion uint32 = 1 - // A PkgEncoder provides methods for encoding a package's Unified IR // export data. type PkgEncoder struct { + // version of the bitstream. + version Version + // elems holds the bitstream for previously encoded elements. elems [numRelocs][]string @@ -47,8 +44,9 @@ func (pw *PkgEncoder) SyncMarkers() bool { return pw.syncFrames >= 0 } // export data files, but can help diagnosing desync errors in // higher-level Unified IR reader/writer code. If syncFrames is // negative, then sync markers are omitted entirely. -func NewPkgEncoder(syncFrames int) PkgEncoder { +func NewPkgEncoder(version Version, syncFrames int) PkgEncoder { return PkgEncoder{ + version: version, stringsIdx: make(map[string]Index), syncFrames: syncFrames, } @@ -64,13 +62,15 @@ func (pw *PkgEncoder) DumpTo(out0 io.Writer) (fingerprint [8]byte) { assert(binary.Write(out, binary.LittleEndian, x) == nil) } - writeUint32(currentVersion) + writeUint32(uint32(pw.version)) - var flags uint32 - if pw.SyncMarkers() { - flags |= flagSyncMarkers + if pw.version.Has(Flags) { + var flags uint32 + if pw.SyncMarkers() { + flags |= flagSyncMarkers + } + writeUint32(flags) } - writeUint32(flags) // Write elemEndsEnds. var sum uint32 @@ -159,7 +159,7 @@ type Encoder struct { // Flush finalizes the element's bitstream and returns its Index. func (w *Encoder) Flush() Index { - var sb bytes.Buffer // TODO(mdempsky): strings.Builder after #44505 is resolved + var sb strings.Builder // Backup the data so we write the relocations at the front. var tmp bytes.Buffer @@ -189,7 +189,7 @@ func (w *Encoder) Flush() Index { func (w *Encoder) checkErr(err error) { if err != nil { - errorf("unexpected encoding error: %v", err) + panicf("unexpected encoding error: %v", err) } } @@ -320,8 +320,14 @@ func (w *Encoder) Code(c Code) { // section (if not already present), and then writing a relocation // into the element bitstream. func (w *Encoder) String(s string) { + w.StringRef(w.p.StringIdx(s)) +} + +// StringRef writes a reference to the given index, which must be a +// previously encoded string value. +func (w *Encoder) StringRef(idx Index) { w.Sync(SyncString) - w.Reloc(RelocString, w.p.StringIdx(s)) + w.Reloc(RelocString, idx) } // Strings encodes and writes a variable-length slice of strings into @@ -348,7 +354,7 @@ func (w *Encoder) Value(val constant.Value) { func (w *Encoder) scalar(val constant.Value) { switch v := constant.Val(val).(type) { default: - errorf("unhandled %v (%v)", val, val.Kind()) + panicf("unhandled %v (%v)", val, val.Kind()) case bool: w.Code(ValBool) w.Bool(v) @@ -381,3 +387,6 @@ func (w *Encoder) bigFloat(v *big.Float) { b := v.Append(nil, 'p', -1) w.String(string(b)) // TODO: More efficient encoding. } + +// Version reports the version of the bitstream. +func (w *Encoder) Version() Version { return w.p.version } diff --git a/vendor/golang.org/x/tools/internal/pkgbits/frames_go1.go b/vendor/golang.org/x/tools/internal/pkgbits/frames_go1.go deleted file mode 100644 index 5294f6a63e..0000000000 --- a/vendor/golang.org/x/tools/internal/pkgbits/frames_go1.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2021 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. - -//go:build !go1.7 -// +build !go1.7 - -// TODO(mdempsky): Remove after #44505 is resolved - -package pkgbits - -import "runtime" - -func walkFrames(pcs []uintptr, visit frameVisitor) { - for _, pc := range pcs { - fn := runtime.FuncForPC(pc) - file, line := fn.FileLine(pc) - - visit(file, line, fn.Name(), pc-fn.Entry()) - } -} diff --git a/vendor/golang.org/x/tools/internal/pkgbits/frames_go17.go b/vendor/golang.org/x/tools/internal/pkgbits/frames_go17.go deleted file mode 100644 index 2324ae7adf..0000000000 --- a/vendor/golang.org/x/tools/internal/pkgbits/frames_go17.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2021 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. - -//go:build go1.7 -// +build go1.7 - -package pkgbits - -import "runtime" - -// walkFrames calls visit for each call frame represented by pcs. -// -// pcs should be a slice of PCs, as returned by runtime.Callers. -func walkFrames(pcs []uintptr, visit frameVisitor) { - if len(pcs) == 0 { - return - } - - frames := runtime.CallersFrames(pcs) - for { - frame, more := frames.Next() - visit(frame.File, frame.Line, frame.Function, frame.PC-frame.Entry) - if !more { - return - } - } -} diff --git a/vendor/golang.org/x/tools/internal/pkgbits/support.go b/vendor/golang.org/x/tools/internal/pkgbits/support.go index ad26d3b28c..50534a2955 100644 --- a/vendor/golang.org/x/tools/internal/pkgbits/support.go +++ b/vendor/golang.org/x/tools/internal/pkgbits/support.go @@ -12,6 +12,6 @@ func assert(b bool) { } } -func errorf(format string, args ...interface{}) { +func panicf(format string, args ...any) { panic(fmt.Errorf(format, args...)) } diff --git a/vendor/golang.org/x/tools/internal/pkgbits/sync.go b/vendor/golang.org/x/tools/internal/pkgbits/sync.go index 5bd51ef717..1520b73afb 100644 --- a/vendor/golang.org/x/tools/internal/pkgbits/sync.go +++ b/vendor/golang.org/x/tools/internal/pkgbits/sync.go @@ -6,6 +6,7 @@ package pkgbits import ( "fmt" + "runtime" "strings" ) @@ -23,6 +24,24 @@ func fmtFrames(pcs ...uintptr) []string { type frameVisitor func(file string, line int, name string, offset uintptr) +// walkFrames calls visit for each call frame represented by pcs. +// +// pcs should be a slice of PCs, as returned by runtime.Callers. +func walkFrames(pcs []uintptr, visit frameVisitor) { + if len(pcs) == 0 { + return + } + + frames := runtime.CallersFrames(pcs) + for { + frame, more := frames.Next() + visit(frame.File, frame.Line, frame.Function, frame.PC-frame.Entry) + if !more { + return + } + } +} + // SyncMarker is an enum type that represents markers that may be // written to export data to ensure the reader and writer stay // synchronized. @@ -110,4 +129,8 @@ const ( SyncStmtsEnd SyncLabel SyncOptLabel + + SyncMultiExpr + SyncRType + SyncConvRTTI ) diff --git a/vendor/golang.org/x/tools/internal/pkgbits/syncmarker_string.go b/vendor/golang.org/x/tools/internal/pkgbits/syncmarker_string.go index 4a5b0ca5f2..582ad56d3e 100644 --- a/vendor/golang.org/x/tools/internal/pkgbits/syncmarker_string.go +++ b/vendor/golang.org/x/tools/internal/pkgbits/syncmarker_string.go @@ -74,11 +74,14 @@ func _() { _ = x[SyncStmtsEnd-64] _ = x[SyncLabel-65] _ = x[SyncOptLabel-66] + _ = x[SyncMultiExpr-67] + _ = x[SyncRType-68] + _ = x[SyncConvRTTI-69] } -const _SyncMarker_name = "EOFBoolInt64Uint64StringValueValRelocsRelocUseRelocPublicPosPosBaseObjectObject1PkgPkgDefMethodTypeTypeIdxTypeParamNamesSignatureParamsParamCodeObjSymLocalIdentSelectorPrivateFuncExtVarExtTypeExtPragmaExprListExprsExprExprTypeAssignOpFuncLitCompLitDeclFuncBodyOpenScopeCloseScopeCloseAnotherScopeDeclNamesDeclNameStmtsBlockStmtIfStmtForStmtSwitchStmtRangeStmtCaseClauseCommClauseSelectStmtDeclsLabeledStmtUseObjLocalAddLocalLinknameStmt1StmtsEndLabelOptLabel" +const _SyncMarker_name = "EOFBoolInt64Uint64StringValueValRelocsRelocUseRelocPublicPosPosBaseObjectObject1PkgPkgDefMethodTypeTypeIdxTypeParamNamesSignatureParamsParamCodeObjSymLocalIdentSelectorPrivateFuncExtVarExtTypeExtPragmaExprListExprsExprExprTypeAssignOpFuncLitCompLitDeclFuncBodyOpenScopeCloseScopeCloseAnotherScopeDeclNamesDeclNameStmtsBlockStmtIfStmtForStmtSwitchStmtRangeStmtCaseClauseCommClauseSelectStmtDeclsLabeledStmtUseObjLocalAddLocalLinknameStmt1StmtsEndLabelOptLabelMultiExprRTypeConvRTTI" -var _SyncMarker_index = [...]uint16{0, 3, 7, 12, 18, 24, 29, 32, 38, 43, 51, 57, 60, 67, 73, 80, 83, 89, 95, 99, 106, 120, 129, 135, 140, 147, 150, 160, 168, 175, 182, 188, 195, 201, 209, 214, 218, 226, 232, 234, 241, 248, 252, 260, 269, 279, 296, 305, 313, 318, 327, 333, 340, 350, 359, 369, 379, 389, 394, 405, 416, 424, 432, 437, 445, 450, 458} +var _SyncMarker_index = [...]uint16{0, 3, 7, 12, 18, 24, 29, 32, 38, 43, 51, 57, 60, 67, 73, 80, 83, 89, 95, 99, 106, 120, 129, 135, 140, 147, 150, 160, 168, 175, 182, 188, 195, 201, 209, 214, 218, 226, 232, 234, 241, 248, 252, 260, 269, 279, 296, 305, 313, 318, 327, 333, 340, 350, 359, 369, 379, 389, 394, 405, 416, 424, 432, 437, 445, 450, 458, 467, 472, 480} func (i SyncMarker) String() string { i -= 1 diff --git a/vendor/golang.org/x/tools/internal/pkgbits/version.go b/vendor/golang.org/x/tools/internal/pkgbits/version.go new file mode 100644 index 0000000000..53af9df22b --- /dev/null +++ b/vendor/golang.org/x/tools/internal/pkgbits/version.go @@ -0,0 +1,85 @@ +// Copyright 2024 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 pkgbits + +// Version indicates a version of a unified IR bitstream. +// Each Version indicates the addition, removal, or change of +// new data in the bitstream. +// +// These are serialized to disk and the interpretation remains fixed. +type Version uint32 + +const ( + // V0: initial prototype. + // + // All data that is not assigned a Field is in version V0 + // and has not been deprecated. + V0 Version = iota + + // V1: adds the Flags uint32 word + V1 + + // V2: removes unused legacy fields and supports type parameters for aliases. + // - remove the legacy "has init" bool from the public root + // - remove obj's "derived func instance" bool + // - add a TypeParamNames field to ObjAlias + // - remove derived info "needed" bool + V2 + + numVersions = iota +) + +// Field denotes a unit of data in the serialized unified IR bitstream. +// It is conceptually a like field in a structure. +// +// We only really need Fields when the data may or may not be present +// in a stream based on the Version of the bitstream. +// +// Unlike much of pkgbits, Fields are not serialized and +// can change values as needed. +type Field int + +const ( + // Flags in a uint32 in the header of a bitstream + // that is used to indicate whether optional features are enabled. + Flags Field = iota + + // Deprecated: HasInit was a bool indicating whether a package + // has any init functions. + HasInit + + // Deprecated: DerivedFuncInstance was a bool indicating + // whether an object was a function instance. + DerivedFuncInstance + + // ObjAlias has a list of TypeParamNames. + AliasTypeParamNames + + // Deprecated: DerivedInfoNeeded was a bool indicating + // whether a type was a derived type. + DerivedInfoNeeded + + numFields = iota +) + +// introduced is the version a field was added. +var introduced = [numFields]Version{ + Flags: V1, + AliasTypeParamNames: V2, +} + +// removed is the version a field was removed in or 0 for fields +// that have not yet been deprecated. +// (So removed[f]-1 is the last version it is included in.) +var removed = [numFields]Version{ + HasInit: V2, + DerivedFuncInstance: V2, + DerivedInfoNeeded: V2, +} + +// Has reports whether field f is present in a bitstream at version v. +func (v Version) Has(f Field) bool { + return introduced[f] <= v && (v < removed[f] || removed[f] == V0) +} diff --git a/vendor/golang.org/x/tools/internal/stdlib/manifest.go b/vendor/golang.org/x/tools/internal/stdlib/manifest.go index a928acf29f..9f0b871ff6 100644 --- a/vendor/golang.org/x/tools/internal/stdlib/manifest.go +++ b/vendor/golang.org/x/tools/internal/stdlib/manifest.go @@ -268,6 +268,8 @@ var PackageSymbols = map[string][]Symbol{ {"ErrTooLarge", Var, 0}, {"Fields", Func, 0}, {"FieldsFunc", Func, 0}, + {"FieldsFuncSeq", Func, 24}, + {"FieldsSeq", Func, 24}, {"HasPrefix", Func, 0}, {"HasSuffix", Func, 0}, {"Index", Func, 0}, @@ -280,6 +282,7 @@ var PackageSymbols = map[string][]Symbol{ {"LastIndexAny", Func, 0}, {"LastIndexByte", Func, 5}, {"LastIndexFunc", Func, 0}, + {"Lines", Func, 24}, {"Map", Func, 0}, {"MinRead", Const, 0}, {"NewBuffer", Func, 0}, @@ -293,7 +296,9 @@ var PackageSymbols = map[string][]Symbol{ {"Split", Func, 0}, {"SplitAfter", Func, 0}, {"SplitAfterN", Func, 0}, + {"SplitAfterSeq", Func, 24}, {"SplitN", Func, 0}, + {"SplitSeq", Func, 24}, {"Title", Func, 0}, {"ToLower", Func, 0}, {"ToLowerSpecial", Func, 0}, @@ -535,6 +540,7 @@ var PackageSymbols = map[string][]Symbol{ {"NewCTR", Func, 0}, {"NewGCM", Func, 2}, {"NewGCMWithNonceSize", Func, 5}, + {"NewGCMWithRandomNonce", Func, 24}, {"NewGCMWithTagSize", Func, 11}, {"NewOFB", Func, 0}, {"Stream", Type, 0}, @@ -673,6 +679,14 @@ var PackageSymbols = map[string][]Symbol{ {"Unmarshal", Func, 0}, {"UnmarshalCompressed", Func, 15}, }, + "crypto/fips140": { + {"Enabled", Func, 24}, + }, + "crypto/hkdf": { + {"Expand", Func, 24}, + {"Extract", Func, 24}, + {"Key", Func, 24}, + }, "crypto/hmac": { {"Equal", Func, 1}, {"New", Func, 0}, @@ -683,11 +697,43 @@ var PackageSymbols = map[string][]Symbol{ {"Size", Const, 0}, {"Sum", Func, 2}, }, + "crypto/mlkem": { + {"(*DecapsulationKey1024).Bytes", Method, 24}, + {"(*DecapsulationKey1024).Decapsulate", Method, 24}, + {"(*DecapsulationKey1024).EncapsulationKey", Method, 24}, + {"(*DecapsulationKey768).Bytes", Method, 24}, + {"(*DecapsulationKey768).Decapsulate", Method, 24}, + {"(*DecapsulationKey768).EncapsulationKey", Method, 24}, + {"(*EncapsulationKey1024).Bytes", Method, 24}, + {"(*EncapsulationKey1024).Encapsulate", Method, 24}, + {"(*EncapsulationKey768).Bytes", Method, 24}, + {"(*EncapsulationKey768).Encapsulate", Method, 24}, + {"CiphertextSize1024", Const, 24}, + {"CiphertextSize768", Const, 24}, + {"DecapsulationKey1024", Type, 24}, + {"DecapsulationKey768", Type, 24}, + {"EncapsulationKey1024", Type, 24}, + {"EncapsulationKey768", Type, 24}, + {"EncapsulationKeySize1024", Const, 24}, + {"EncapsulationKeySize768", Const, 24}, + {"GenerateKey1024", Func, 24}, + {"GenerateKey768", Func, 24}, + {"NewDecapsulationKey1024", Func, 24}, + {"NewDecapsulationKey768", Func, 24}, + {"NewEncapsulationKey1024", Func, 24}, + {"NewEncapsulationKey768", Func, 24}, + {"SeedSize", Const, 24}, + {"SharedKeySize", Const, 24}, + }, + "crypto/pbkdf2": { + {"Key", Func, 24}, + }, "crypto/rand": { {"Int", Func, 0}, {"Prime", Func, 0}, {"Read", Func, 0}, {"Reader", Var, 0}, + {"Text", Func, 24}, }, "crypto/rc4": { {"(*Cipher).Reset", Method, 0}, @@ -766,6 +812,39 @@ var PackageSymbols = map[string][]Symbol{ {"Sum224", Func, 2}, {"Sum256", Func, 2}, }, + "crypto/sha3": { + {"(*SHA3).AppendBinary", Method, 24}, + {"(*SHA3).BlockSize", Method, 24}, + {"(*SHA3).MarshalBinary", Method, 24}, + {"(*SHA3).Reset", Method, 24}, + {"(*SHA3).Size", Method, 24}, + {"(*SHA3).Sum", Method, 24}, + {"(*SHA3).UnmarshalBinary", Method, 24}, + {"(*SHA3).Write", Method, 24}, + {"(*SHAKE).AppendBinary", Method, 24}, + {"(*SHAKE).BlockSize", Method, 24}, + {"(*SHAKE).MarshalBinary", Method, 24}, + {"(*SHAKE).Read", Method, 24}, + {"(*SHAKE).Reset", Method, 24}, + {"(*SHAKE).UnmarshalBinary", Method, 24}, + {"(*SHAKE).Write", Method, 24}, + {"New224", Func, 24}, + {"New256", Func, 24}, + {"New384", Func, 24}, + {"New512", Func, 24}, + {"NewCSHAKE128", Func, 24}, + {"NewCSHAKE256", Func, 24}, + {"NewSHAKE128", Func, 24}, + {"NewSHAKE256", Func, 24}, + {"SHA3", Type, 24}, + {"SHAKE", Type, 24}, + {"Sum224", Func, 24}, + {"Sum256", Func, 24}, + {"Sum384", Func, 24}, + {"Sum512", Func, 24}, + {"SumSHAKE128", Func, 24}, + {"SumSHAKE256", Func, 24}, + }, "crypto/sha512": { {"BlockSize", Const, 0}, {"New", Func, 0}, @@ -788,6 +867,7 @@ var PackageSymbols = map[string][]Symbol{ {"ConstantTimeEq", Func, 0}, {"ConstantTimeLessOrEq", Func, 2}, {"ConstantTimeSelect", Func, 0}, + {"WithDataIndependentTiming", Func, 24}, {"XORBytes", Func, 20}, }, "crypto/tls": { @@ -864,6 +944,7 @@ var PackageSymbols = map[string][]Symbol{ {"ClientHelloInfo", Type, 4}, {"ClientHelloInfo.CipherSuites", Field, 4}, {"ClientHelloInfo.Conn", Field, 8}, + {"ClientHelloInfo.Extensions", Field, 24}, {"ClientHelloInfo.ServerName", Field, 4}, {"ClientHelloInfo.SignatureSchemes", Field, 8}, {"ClientHelloInfo.SupportedCurves", Field, 4}, @@ -881,6 +962,7 @@ var PackageSymbols = map[string][]Symbol{ {"Config.CurvePreferences", Field, 3}, {"Config.DynamicRecordSizingDisabled", Field, 7}, {"Config.EncryptedClientHelloConfigList", Field, 23}, + {"Config.EncryptedClientHelloKeys", Field, 24}, {"Config.EncryptedClientHelloRejectionVerify", Field, 23}, {"Config.GetCertificate", Field, 4}, {"Config.GetClientCertificate", Field, 8}, @@ -934,6 +1016,10 @@ var PackageSymbols = map[string][]Symbol{ {"ECHRejectionError", Type, 23}, {"ECHRejectionError.RetryConfigList", Field, 23}, {"Ed25519", Const, 13}, + {"EncryptedClientHelloKey", Type, 24}, + {"EncryptedClientHelloKey.Config", Field, 24}, + {"EncryptedClientHelloKey.PrivateKey", Field, 24}, + {"EncryptedClientHelloKey.SendAsRetry", Field, 24}, {"InsecureCipherSuites", Func, 14}, {"Listen", Func, 0}, {"LoadX509KeyPair", Func, 0}, @@ -951,7 +1037,7 @@ var PackageSymbols = map[string][]Symbol{ {"ParseSessionState", Func, 21}, {"QUICClient", Func, 21}, {"QUICConfig", Type, 21}, - {"QUICConfig.EnableStoreSessionEvent", Field, 23}, + {"QUICConfig.EnableSessionEvents", Field, 23}, {"QUICConfig.TLSConfig", Field, 21}, {"QUICConn", Type, 21}, {"QUICEncryptionLevel", Type, 21}, @@ -1032,6 +1118,7 @@ var PackageSymbols = map[string][]Symbol{ {"VersionTLS12", Const, 2}, {"VersionTLS13", Const, 12}, {"X25519", Const, 8}, + {"X25519MLKEM768", Const, 24}, {"X509KeyPair", Func, 0}, }, "crypto/x509": { @@ -1056,6 +1143,8 @@ var PackageSymbols = map[string][]Symbol{ {"(ConstraintViolationError).Error", Method, 0}, {"(HostnameError).Error", Method, 0}, {"(InsecureAlgorithmError).Error", Method, 6}, + {"(OID).AppendBinary", Method, 24}, + {"(OID).AppendText", Method, 24}, {"(OID).Equal", Method, 22}, {"(OID).EqualASN1OID", Method, 22}, {"(OID).MarshalBinary", Method, 23}, @@ -1084,6 +1173,10 @@ var PackageSymbols = map[string][]Symbol{ {"Certificate.Extensions", Field, 2}, {"Certificate.ExtraExtensions", Field, 2}, {"Certificate.IPAddresses", Field, 1}, + {"Certificate.InhibitAnyPolicy", Field, 24}, + {"Certificate.InhibitAnyPolicyZero", Field, 24}, + {"Certificate.InhibitPolicyMapping", Field, 24}, + {"Certificate.InhibitPolicyMappingZero", Field, 24}, {"Certificate.IsCA", Field, 0}, {"Certificate.Issuer", Field, 0}, {"Certificate.IssuingCertificateURL", Field, 2}, @@ -1100,6 +1193,7 @@ var PackageSymbols = map[string][]Symbol{ {"Certificate.PermittedURIDomains", Field, 10}, {"Certificate.Policies", Field, 22}, {"Certificate.PolicyIdentifiers", Field, 0}, + {"Certificate.PolicyMappings", Field, 24}, {"Certificate.PublicKey", Field, 0}, {"Certificate.PublicKeyAlgorithm", Field, 0}, {"Certificate.Raw", Field, 0}, @@ -1107,6 +1201,8 @@ var PackageSymbols = map[string][]Symbol{ {"Certificate.RawSubject", Field, 0}, {"Certificate.RawSubjectPublicKeyInfo", Field, 0}, {"Certificate.RawTBSCertificate", Field, 0}, + {"Certificate.RequireExplicitPolicy", Field, 24}, + {"Certificate.RequireExplicitPolicyZero", Field, 24}, {"Certificate.SerialNumber", Field, 0}, {"Certificate.Signature", Field, 0}, {"Certificate.SignatureAlgorithm", Field, 0}, @@ -1198,6 +1294,7 @@ var PackageSymbols = map[string][]Symbol{ {"NameConstraintsWithoutSANs", Const, 10}, {"NameMismatch", Const, 8}, {"NewCertPool", Func, 0}, + {"NoValidChains", Const, 24}, {"NotAuthorizedToSign", Const, 0}, {"OID", Type, 22}, {"OIDFromInts", Func, 22}, @@ -1219,6 +1316,9 @@ var PackageSymbols = map[string][]Symbol{ {"ParsePKCS8PrivateKey", Func, 0}, {"ParsePKIXPublicKey", Func, 0}, {"ParseRevocationList", Func, 19}, + {"PolicyMapping", Type, 24}, + {"PolicyMapping.IssuerDomainPolicy", Field, 24}, + {"PolicyMapping.SubjectDomainPolicy", Field, 24}, {"PublicKeyAlgorithm", Type, 0}, {"PureEd25519", Const, 13}, {"RSA", Const, 0}, @@ -1265,6 +1365,7 @@ var PackageSymbols = map[string][]Symbol{ {"UnknownPublicKeyAlgorithm", Const, 0}, {"UnknownSignatureAlgorithm", Const, 0}, {"VerifyOptions", Type, 0}, + {"VerifyOptions.CertificatePolicies", Field, 24}, {"VerifyOptions.CurrentTime", Field, 0}, {"VerifyOptions.DNSName", Field, 0}, {"VerifyOptions.Intermediates", Field, 0}, @@ -1975,6 +2076,8 @@ var PackageSymbols = map[string][]Symbol{ {"(*File).DynString", Method, 1}, {"(*File).DynValue", Method, 21}, {"(*File).DynamicSymbols", Method, 4}, + {"(*File).DynamicVersionNeeds", Method, 24}, + {"(*File).DynamicVersions", Method, 24}, {"(*File).ImportedLibraries", Method, 0}, {"(*File).ImportedSymbols", Method, 0}, {"(*File).Section", Method, 0}, @@ -2240,6 +2343,19 @@ var PackageSymbols = map[string][]Symbol{ {"DynFlag", Type, 0}, {"DynFlag1", Type, 21}, {"DynTag", Type, 0}, + {"DynamicVersion", Type, 24}, + {"DynamicVersion.Deps", Field, 24}, + {"DynamicVersion.Flags", Field, 24}, + {"DynamicVersion.Index", Field, 24}, + {"DynamicVersion.Name", Field, 24}, + {"DynamicVersionDep", Type, 24}, + {"DynamicVersionDep.Dep", Field, 24}, + {"DynamicVersionDep.Flags", Field, 24}, + {"DynamicVersionDep.Index", Field, 24}, + {"DynamicVersionFlag", Type, 24}, + {"DynamicVersionNeed", Type, 24}, + {"DynamicVersionNeed.Name", Field, 24}, + {"DynamicVersionNeed.Needs", Field, 24}, {"EI_ABIVERSION", Const, 0}, {"EI_CLASS", Const, 0}, {"EI_DATA", Const, 0}, @@ -3726,8 +3842,19 @@ var PackageSymbols = map[string][]Symbol{ {"Symbol.Size", Field, 0}, {"Symbol.Value", Field, 0}, {"Symbol.Version", Field, 13}, + {"Symbol.VersionIndex", Field, 24}, + {"Symbol.VersionScope", Field, 24}, + {"SymbolVersionScope", Type, 24}, {"Type", Type, 0}, + {"VER_FLG_BASE", Const, 24}, + {"VER_FLG_INFO", Const, 24}, + {"VER_FLG_WEAK", Const, 24}, {"Version", Type, 0}, + {"VersionScopeGlobal", Const, 24}, + {"VersionScopeHidden", Const, 24}, + {"VersionScopeLocal", Const, 24}, + {"VersionScopeNone", Const, 24}, + {"VersionScopeSpecific", Const, 24}, }, "debug/gosym": { {"(*DecodingError).Error", Method, 0}, @@ -4453,8 +4580,10 @@ var PackageSymbols = map[string][]Symbol{ {"FS", Type, 16}, }, "encoding": { + {"BinaryAppender", Type, 24}, {"BinaryMarshaler", Type, 2}, {"BinaryUnmarshaler", Type, 2}, + {"TextAppender", Type, 24}, {"TextMarshaler", Type, 2}, {"TextUnmarshaler", Type, 2}, }, @@ -5984,13 +6113,16 @@ var PackageSymbols = map[string][]Symbol{ {"(*Interface).Complete", Method, 5}, {"(*Interface).Embedded", Method, 5}, {"(*Interface).EmbeddedType", Method, 11}, + {"(*Interface).EmbeddedTypes", Method, 24}, {"(*Interface).Empty", Method, 5}, {"(*Interface).ExplicitMethod", Method, 5}, + {"(*Interface).ExplicitMethods", Method, 24}, {"(*Interface).IsComparable", Method, 18}, {"(*Interface).IsImplicit", Method, 18}, {"(*Interface).IsMethodSet", Method, 18}, {"(*Interface).MarkImplicit", Method, 18}, {"(*Interface).Method", Method, 5}, + {"(*Interface).Methods", Method, 24}, {"(*Interface).NumEmbeddeds", Method, 5}, {"(*Interface).NumExplicitMethods", Method, 5}, {"(*Interface).NumMethods", Method, 5}, @@ -6011,9 +6143,11 @@ var PackageSymbols = map[string][]Symbol{ {"(*MethodSet).At", Method, 5}, {"(*MethodSet).Len", Method, 5}, {"(*MethodSet).Lookup", Method, 5}, + {"(*MethodSet).Methods", Method, 24}, {"(*MethodSet).String", Method, 5}, {"(*Named).AddMethod", Method, 5}, {"(*Named).Method", Method, 5}, + {"(*Named).Methods", Method, 24}, {"(*Named).NumMethods", Method, 5}, {"(*Named).Obj", Method, 5}, {"(*Named).Origin", Method, 18}, @@ -6054,6 +6188,7 @@ var PackageSymbols = map[string][]Symbol{ {"(*Pointer).String", Method, 5}, {"(*Pointer).Underlying", Method, 5}, {"(*Scope).Child", Method, 5}, + {"(*Scope).Children", Method, 24}, {"(*Scope).Contains", Method, 5}, {"(*Scope).End", Method, 5}, {"(*Scope).Innermost", Method, 5}, @@ -6089,6 +6224,7 @@ var PackageSymbols = map[string][]Symbol{ {"(*StdSizes).Offsetsof", Method, 5}, {"(*StdSizes).Sizeof", Method, 5}, {"(*Struct).Field", Method, 5}, + {"(*Struct).Fields", Method, 24}, {"(*Struct).NumFields", Method, 5}, {"(*Struct).String", Method, 5}, {"(*Struct).Tag", Method, 5}, @@ -6100,8 +6236,10 @@ var PackageSymbols = map[string][]Symbol{ {"(*Tuple).Len", Method, 5}, {"(*Tuple).String", Method, 5}, {"(*Tuple).Underlying", Method, 5}, + {"(*Tuple).Variables", Method, 24}, {"(*TypeList).At", Method, 18}, {"(*TypeList).Len", Method, 18}, + {"(*TypeList).Types", Method, 24}, {"(*TypeName).Exported", Method, 5}, {"(*TypeName).Id", Method, 5}, {"(*TypeName).IsAlias", Method, 9}, @@ -6119,9 +6257,11 @@ var PackageSymbols = map[string][]Symbol{ {"(*TypeParam).Underlying", Method, 18}, {"(*TypeParamList).At", Method, 18}, {"(*TypeParamList).Len", Method, 18}, + {"(*TypeParamList).TypeParams", Method, 24}, {"(*Union).Len", Method, 18}, {"(*Union).String", Method, 18}, {"(*Union).Term", Method, 18}, + {"(*Union).Terms", Method, 24}, {"(*Union).Underlying", Method, 18}, {"(*Var).Anonymous", Method, 5}, {"(*Var).Embedded", Method, 11}, @@ -6392,10 +6532,12 @@ var PackageSymbols = map[string][]Symbol{ {"(*Hash).WriteByte", Method, 14}, {"(*Hash).WriteString", Method, 14}, {"Bytes", Func, 19}, + {"Comparable", Func, 24}, {"Hash", Type, 14}, {"MakeSeed", Func, 14}, {"Seed", Type, 14}, {"String", Func, 19}, + {"WriteComparable", Func, 24}, }, "html": { {"EscapeString", Func, 0}, @@ -7082,6 +7224,7 @@ var PackageSymbols = map[string][]Symbol{ {"(*JSONHandler).WithGroup", Method, 21}, {"(*Level).UnmarshalJSON", Method, 21}, {"(*Level).UnmarshalText", Method, 21}, + {"(*LevelVar).AppendText", Method, 24}, {"(*LevelVar).Level", Method, 21}, {"(*LevelVar).MarshalText", Method, 21}, {"(*LevelVar).Set", Method, 21}, @@ -7110,6 +7253,7 @@ var PackageSymbols = map[string][]Symbol{ {"(Attr).Equal", Method, 21}, {"(Attr).String", Method, 21}, {"(Kind).String", Method, 21}, + {"(Level).AppendText", Method, 24}, {"(Level).Level", Method, 21}, {"(Level).MarshalJSON", Method, 21}, {"(Level).MarshalText", Method, 21}, @@ -7140,6 +7284,7 @@ var PackageSymbols = map[string][]Symbol{ {"Debug", Func, 21}, {"DebugContext", Func, 21}, {"Default", Func, 21}, + {"DiscardHandler", Var, 24}, {"Duration", Func, 21}, {"DurationValue", Func, 21}, {"Error", Func, 21}, @@ -7375,6 +7520,7 @@ var PackageSymbols = map[string][]Symbol{ {"(*Float).Acc", Method, 5}, {"(*Float).Add", Method, 5}, {"(*Float).Append", Method, 5}, + {"(*Float).AppendText", Method, 24}, {"(*Float).Cmp", Method, 5}, {"(*Float).Copy", Method, 5}, {"(*Float).Float32", Method, 5}, @@ -7421,6 +7567,7 @@ var PackageSymbols = map[string][]Symbol{ {"(*Int).And", Method, 0}, {"(*Int).AndNot", Method, 0}, {"(*Int).Append", Method, 6}, + {"(*Int).AppendText", Method, 24}, {"(*Int).Binomial", Method, 0}, {"(*Int).Bit", Method, 0}, {"(*Int).BitLen", Method, 0}, @@ -7477,6 +7624,7 @@ var PackageSymbols = map[string][]Symbol{ {"(*Int).Xor", Method, 0}, {"(*Rat).Abs", Method, 0}, {"(*Rat).Add", Method, 0}, + {"(*Rat).AppendText", Method, 24}, {"(*Rat).Cmp", Method, 0}, {"(*Rat).Denom", Method, 0}, {"(*Rat).Float32", Method, 4}, @@ -7659,11 +7807,13 @@ var PackageSymbols = map[string][]Symbol{ {"Zipf", Type, 0}, }, "math/rand/v2": { + {"(*ChaCha8).AppendBinary", Method, 24}, {"(*ChaCha8).MarshalBinary", Method, 22}, {"(*ChaCha8).Read", Method, 23}, {"(*ChaCha8).Seed", Method, 22}, {"(*ChaCha8).Uint64", Method, 22}, {"(*ChaCha8).UnmarshalBinary", Method, 22}, + {"(*PCG).AppendBinary", Method, 24}, {"(*PCG).MarshalBinary", Method, 22}, {"(*PCG).Seed", Method, 22}, {"(*PCG).Uint64", Method, 22}, @@ -7931,6 +8081,7 @@ var PackageSymbols = map[string][]Symbol{ {"(*UnixListener).SyscallConn", Method, 10}, {"(Flags).String", Method, 0}, {"(HardwareAddr).String", Method, 0}, + {"(IP).AppendText", Method, 24}, {"(IP).DefaultMask", Method, 0}, {"(IP).Equal", Method, 0}, {"(IP).IsGlobalUnicast", Method, 0}, @@ -8131,6 +8282,9 @@ var PackageSymbols = map[string][]Symbol{ {"(*MaxBytesError).Error", Method, 19}, {"(*ProtocolError).Error", Method, 0}, {"(*ProtocolError).Is", Method, 21}, + {"(*Protocols).SetHTTP1", Method, 24}, + {"(*Protocols).SetHTTP2", Method, 24}, + {"(*Protocols).SetUnencryptedHTTP2", Method, 24}, {"(*Request).AddCookie", Method, 0}, {"(*Request).BasicAuth", Method, 4}, {"(*Request).Clone", Method, 13}, @@ -8190,6 +8344,10 @@ var PackageSymbols = map[string][]Symbol{ {"(Header).Values", Method, 14}, {"(Header).Write", Method, 0}, {"(Header).WriteSubset", Method, 0}, + {"(Protocols).HTTP1", Method, 24}, + {"(Protocols).HTTP2", Method, 24}, + {"(Protocols).String", Method, 24}, + {"(Protocols).UnencryptedHTTP2", Method, 24}, {"AllowQuerySemicolons", Func, 17}, {"CanonicalHeaderKey", Func, 0}, {"Client", Type, 0}, @@ -8252,6 +8410,18 @@ var PackageSymbols = map[string][]Symbol{ {"FileSystem", Type, 0}, {"Flusher", Type, 0}, {"Get", Func, 0}, + {"HTTP2Config", Type, 24}, + {"HTTP2Config.CountError", Field, 24}, + {"HTTP2Config.MaxConcurrentStreams", Field, 24}, + {"HTTP2Config.MaxDecoderHeaderTableSize", Field, 24}, + {"HTTP2Config.MaxEncoderHeaderTableSize", Field, 24}, + {"HTTP2Config.MaxReadFrameSize", Field, 24}, + {"HTTP2Config.MaxReceiveBufferPerConnection", Field, 24}, + {"HTTP2Config.MaxReceiveBufferPerStream", Field, 24}, + {"HTTP2Config.PermitProhibitedCipherSuites", Field, 24}, + {"HTTP2Config.PingTimeout", Field, 24}, + {"HTTP2Config.SendPingTimeout", Field, 24}, + {"HTTP2Config.WriteByteTimeout", Field, 24}, {"Handle", Func, 0}, {"HandleFunc", Func, 0}, {"Handler", Type, 0}, @@ -8292,6 +8462,7 @@ var PackageSymbols = map[string][]Symbol{ {"PostForm", Func, 0}, {"ProtocolError", Type, 0}, {"ProtocolError.ErrorString", Field, 0}, + {"Protocols", Type, 24}, {"ProxyFromEnvironment", Func, 0}, {"ProxyURL", Func, 0}, {"PushOptions", Type, 8}, @@ -8361,9 +8532,11 @@ var PackageSymbols = map[string][]Symbol{ {"Server.ConnState", Field, 3}, {"Server.DisableGeneralOptionsHandler", Field, 20}, {"Server.ErrorLog", Field, 3}, + {"Server.HTTP2", Field, 24}, {"Server.Handler", Field, 0}, {"Server.IdleTimeout", Field, 8}, {"Server.MaxHeaderBytes", Field, 0}, + {"Server.Protocols", Field, 24}, {"Server.ReadHeaderTimeout", Field, 8}, {"Server.ReadTimeout", Field, 0}, {"Server.TLSConfig", Field, 0}, @@ -8453,12 +8626,14 @@ var PackageSymbols = map[string][]Symbol{ {"Transport.ExpectContinueTimeout", Field, 6}, {"Transport.ForceAttemptHTTP2", Field, 13}, {"Transport.GetProxyConnectHeader", Field, 16}, + {"Transport.HTTP2", Field, 24}, {"Transport.IdleConnTimeout", Field, 7}, {"Transport.MaxConnsPerHost", Field, 11}, {"Transport.MaxIdleConns", Field, 7}, {"Transport.MaxIdleConnsPerHost", Field, 0}, {"Transport.MaxResponseHeaderBytes", Field, 7}, {"Transport.OnProxyConnectResponse", Field, 20}, + {"Transport.Protocols", Field, 24}, {"Transport.Proxy", Field, 0}, {"Transport.ProxyConnectHeader", Field, 8}, {"Transport.ReadBufferSize", Field, 13}, @@ -8646,6 +8821,8 @@ var PackageSymbols = map[string][]Symbol{ {"(*AddrPort).UnmarshalText", Method, 18}, {"(*Prefix).UnmarshalBinary", Method, 18}, {"(*Prefix).UnmarshalText", Method, 18}, + {"(Addr).AppendBinary", Method, 24}, + {"(Addr).AppendText", Method, 24}, {"(Addr).AppendTo", Method, 18}, {"(Addr).As16", Method, 18}, {"(Addr).As4", Method, 18}, @@ -8676,6 +8853,8 @@ var PackageSymbols = map[string][]Symbol{ {"(Addr).WithZone", Method, 18}, {"(Addr).Zone", Method, 18}, {"(AddrPort).Addr", Method, 18}, + {"(AddrPort).AppendBinary", Method, 24}, + {"(AddrPort).AppendText", Method, 24}, {"(AddrPort).AppendTo", Method, 18}, {"(AddrPort).Compare", Method, 22}, {"(AddrPort).IsValid", Method, 18}, @@ -8684,6 +8863,8 @@ var PackageSymbols = map[string][]Symbol{ {"(AddrPort).Port", Method, 18}, {"(AddrPort).String", Method, 18}, {"(Prefix).Addr", Method, 18}, + {"(Prefix).AppendBinary", Method, 24}, + {"(Prefix).AppendText", Method, 24}, {"(Prefix).AppendTo", Method, 18}, {"(Prefix).Bits", Method, 18}, {"(Prefix).Contains", Method, 18}, @@ -8868,6 +9049,7 @@ var PackageSymbols = map[string][]Symbol{ {"(*Error).Temporary", Method, 6}, {"(*Error).Timeout", Method, 6}, {"(*Error).Unwrap", Method, 13}, + {"(*URL).AppendBinary", Method, 24}, {"(*URL).EscapedFragment", Method, 15}, {"(*URL).EscapedPath", Method, 5}, {"(*URL).Hostname", Method, 8}, @@ -8967,6 +9149,17 @@ var PackageSymbols = map[string][]Symbol{ {"(*ProcessState).SysUsage", Method, 0}, {"(*ProcessState).SystemTime", Method, 0}, {"(*ProcessState).UserTime", Method, 0}, + {"(*Root).Close", Method, 24}, + {"(*Root).Create", Method, 24}, + {"(*Root).FS", Method, 24}, + {"(*Root).Lstat", Method, 24}, + {"(*Root).Mkdir", Method, 24}, + {"(*Root).Name", Method, 24}, + {"(*Root).Open", Method, 24}, + {"(*Root).OpenFile", Method, 24}, + {"(*Root).OpenRoot", Method, 24}, + {"(*Root).Remove", Method, 24}, + {"(*Root).Stat", Method, 24}, {"(*SyscallError).Error", Method, 0}, {"(*SyscallError).Timeout", Method, 10}, {"(*SyscallError).Unwrap", Method, 13}, @@ -9060,6 +9253,8 @@ var PackageSymbols = map[string][]Symbol{ {"O_WRONLY", Const, 0}, {"Open", Func, 0}, {"OpenFile", Func, 0}, + {"OpenInRoot", Func, 24}, + {"OpenRoot", Func, 24}, {"PathError", Type, 0}, {"PathError.Err", Field, 0}, {"PathError.Op", Field, 0}, @@ -9081,6 +9276,7 @@ var PackageSymbols = map[string][]Symbol{ {"Remove", Func, 0}, {"RemoveAll", Func, 0}, {"Rename", Func, 0}, + {"Root", Type, 24}, {"SEEK_CUR", Const, 0}, {"SEEK_END", Const, 0}, {"SEEK_SET", Const, 0}, @@ -9422,6 +9618,7 @@ var PackageSymbols = map[string][]Symbol{ {"Zero", Func, 0}, }, "regexp": { + {"(*Regexp).AppendText", Method, 24}, {"(*Regexp).Copy", Method, 6}, {"(*Regexp).Expand", Method, 0}, {"(*Regexp).ExpandString", Method, 0}, @@ -9602,6 +9799,8 @@ var PackageSymbols = map[string][]Symbol{ {"(*StackRecord).Stack", Method, 0}, {"(*TypeAssertionError).Error", Method, 0}, {"(*TypeAssertionError).RuntimeError", Method, 0}, + {"(Cleanup).Stop", Method, 24}, + {"AddCleanup", Func, 24}, {"BlockProfile", Func, 1}, {"BlockProfileRecord", Type, 1}, {"BlockProfileRecord.Count", Field, 1}, @@ -9612,6 +9811,7 @@ var PackageSymbols = map[string][]Symbol{ {"Caller", Func, 0}, {"Callers", Func, 0}, {"CallersFrames", Func, 7}, + {"Cleanup", Type, 24}, {"Compiler", Const, 0}, {"Error", Type, 0}, {"Frame", Type, 7}, @@ -9974,6 +10174,8 @@ var PackageSymbols = map[string][]Symbol{ {"EqualFold", Func, 0}, {"Fields", Func, 0}, {"FieldsFunc", Func, 0}, + {"FieldsFuncSeq", Func, 24}, + {"FieldsSeq", Func, 24}, {"HasPrefix", Func, 0}, {"HasSuffix", Func, 0}, {"Index", Func, 0}, @@ -9986,6 +10188,7 @@ var PackageSymbols = map[string][]Symbol{ {"LastIndexAny", Func, 0}, {"LastIndexByte", Func, 5}, {"LastIndexFunc", Func, 0}, + {"Lines", Func, 24}, {"Map", Func, 0}, {"NewReader", Func, 0}, {"NewReplacer", Func, 0}, @@ -9997,7 +10200,9 @@ var PackageSymbols = map[string][]Symbol{ {"Split", Func, 0}, {"SplitAfter", Func, 0}, {"SplitAfterN", Func, 0}, + {"SplitAfterSeq", Func, 24}, {"SplitN", Func, 0}, + {"SplitSeq", Func, 24}, {"Title", Func, 0}, {"ToLower", Func, 0}, {"ToLowerSpecial", Func, 0}, @@ -16413,7 +16618,9 @@ var PackageSymbols = map[string][]Symbol{ {"ValueOf", Func, 0}, }, "testing": { + {"(*B).Chdir", Method, 24}, {"(*B).Cleanup", Method, 14}, + {"(*B).Context", Method, 24}, {"(*B).Elapsed", Method, 20}, {"(*B).Error", Method, 0}, {"(*B).Errorf", Method, 0}, @@ -16425,6 +16632,7 @@ var PackageSymbols = map[string][]Symbol{ {"(*B).Helper", Method, 9}, {"(*B).Log", Method, 0}, {"(*B).Logf", Method, 0}, + {"(*B).Loop", Method, 24}, {"(*B).Name", Method, 8}, {"(*B).ReportAllocs", Method, 1}, {"(*B).ReportMetric", Method, 13}, @@ -16442,7 +16650,9 @@ var PackageSymbols = map[string][]Symbol{ {"(*B).StopTimer", Method, 0}, {"(*B).TempDir", Method, 15}, {"(*F).Add", Method, 18}, + {"(*F).Chdir", Method, 24}, {"(*F).Cleanup", Method, 18}, + {"(*F).Context", Method, 24}, {"(*F).Error", Method, 18}, {"(*F).Errorf", Method, 18}, {"(*F).Fail", Method, 18}, @@ -16463,7 +16673,9 @@ var PackageSymbols = map[string][]Symbol{ {"(*F).TempDir", Method, 18}, {"(*M).Run", Method, 4}, {"(*PB).Next", Method, 3}, + {"(*T).Chdir", Method, 24}, {"(*T).Cleanup", Method, 14}, + {"(*T).Context", Method, 24}, {"(*T).Deadline", Method, 15}, {"(*T).Error", Method, 0}, {"(*T).Errorf", Method, 0}, @@ -16954,7 +17166,9 @@ var PackageSymbols = map[string][]Symbol{ {"(Time).Add", Method, 0}, {"(Time).AddDate", Method, 0}, {"(Time).After", Method, 0}, + {"(Time).AppendBinary", Method, 24}, {"(Time).AppendFormat", Method, 5}, + {"(Time).AppendText", Method, 24}, {"(Time).Before", Method, 0}, {"(Time).Clock", Method, 0}, {"(Time).Compare", Method, 20}, @@ -17428,4 +17642,9 @@ var PackageSymbols = map[string][]Symbol{ {"String", Func, 0}, {"StringData", Func, 0}, }, + "weak": { + {"(Pointer).Value", Method, 24}, + {"Make", Func, 24}, + {"Pointer", Type, 24}, + }, } diff --git a/vendor/golang.org/x/tools/internal/tokeninternal/tokeninternal.go b/vendor/golang.org/x/tools/internal/tokeninternal/tokeninternal.go deleted file mode 100644 index ff9437a36c..0000000000 --- a/vendor/golang.org/x/tools/internal/tokeninternal/tokeninternal.go +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright 2023 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 tokeninternal provides access to some internal features of the token -// package. -package tokeninternal - -import ( - "fmt" - "go/token" - "sort" - "sync" - "unsafe" -) - -// GetLines returns the table of line-start offsets from a token.File. -func GetLines(file *token.File) []int { - // token.File has a Lines method on Go 1.21 and later. - if file, ok := (interface{})(file).(interface{ Lines() []int }); ok { - return file.Lines() - } - - // This declaration must match that of token.File. - // This creates a risk of dependency skew. - // For now we check that the size of the two - // declarations is the same, on the (fragile) assumption - // that future changes would add fields. - type tokenFile119 struct { - _ string - _ int - _ int - mu sync.Mutex // we're not complete monsters - lines []int - _ []struct{} - } - - if unsafe.Sizeof(*file) != unsafe.Sizeof(tokenFile119{}) { - panic("unexpected token.File size") - } - var ptr *tokenFile119 - type uP = unsafe.Pointer - *(*uP)(uP(&ptr)) = uP(file) - ptr.mu.Lock() - defer ptr.mu.Unlock() - return ptr.lines -} - -// AddExistingFiles adds the specified files to the FileSet if they -// are not already present. It panics if any pair of files in the -// resulting FileSet would overlap. -func AddExistingFiles(fset *token.FileSet, files []*token.File) { - // Punch through the FileSet encapsulation. - type tokenFileSet struct { - // This type remained essentially consistent from go1.16 to go1.21. - mutex sync.RWMutex - base int - files []*token.File - _ *token.File // changed to atomic.Pointer[token.File] in go1.19 - } - - // If the size of token.FileSet changes, this will fail to compile. - const delta = int64(unsafe.Sizeof(tokenFileSet{})) - int64(unsafe.Sizeof(token.FileSet{})) - var _ [-delta * delta]int - - type uP = unsafe.Pointer - var ptr *tokenFileSet - *(*uP)(uP(&ptr)) = uP(fset) - ptr.mutex.Lock() - defer ptr.mutex.Unlock() - - // Merge and sort. - newFiles := append(ptr.files, files...) - sort.Slice(newFiles, func(i, j int) bool { - return newFiles[i].Base() < newFiles[j].Base() - }) - - // Reject overlapping files. - // Discard adjacent identical files. - out := newFiles[:0] - for i, file := range newFiles { - if i > 0 { - prev := newFiles[i-1] - if file == prev { - continue - } - if prev.Base()+prev.Size()+1 > file.Base() { - panic(fmt.Sprintf("file %s (%d-%d) overlaps with file %s (%d-%d)", - prev.Name(), prev.Base(), prev.Base()+prev.Size(), - file.Name(), file.Base(), file.Base()+file.Size())) - } - } - out = append(out, file) - } - newFiles = out - - ptr.files = newFiles - - // Advance FileSet.Base(). - if len(newFiles) > 0 { - last := newFiles[len(newFiles)-1] - newBase := last.Base() + last.Size() + 1 - if ptr.base < newBase { - ptr.base = newBase - } - } -} - -// FileSetFor returns a new FileSet containing a sequence of new Files with -// the same base, size, and line as the input files, for use in APIs that -// require a FileSet. -// -// Precondition: the input files must be non-overlapping, and sorted in order -// of their Base. -func FileSetFor(files ...*token.File) *token.FileSet { - fset := token.NewFileSet() - for _, f := range files { - f2 := fset.AddFile(f.Name(), f.Base(), f.Size()) - lines := GetLines(f) - f2.SetLines(lines) - } - return fset -} - -// CloneFileSet creates a new FileSet holding all files in fset. It does not -// create copies of the token.Files in fset: they are added to the resulting -// FileSet unmodified. -func CloneFileSet(fset *token.FileSet) *token.FileSet { - var files []*token.File - fset.Iterate(func(f *token.File) bool { - files = append(files, f) - return true - }) - newFileSet := token.NewFileSet() - AddExistingFiles(newFileSet, files) - return newFileSet -} diff --git a/vendor/golang.org/x/tools/internal/typeparams/common.go b/vendor/golang.org/x/tools/internal/typeparams/common.go new file mode 100644 index 0000000000..cdae2b8e81 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/typeparams/common.go @@ -0,0 +1,68 @@ +// Copyright 2021 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 typeparams contains common utilities for writing tools that +// interact with generic Go code, as introduced with Go 1.18. It +// supplements the standard library APIs. Notably, the StructuralTerms +// API computes a minimal representation of the structural +// restrictions on a type parameter. +// +// An external version of these APIs is available in the +// golang.org/x/exp/typeparams module. +package typeparams + +import ( + "go/ast" + "go/token" + "go/types" +) + +// UnpackIndexExpr extracts data from AST nodes that represent index +// expressions. +// +// For an ast.IndexExpr, the resulting indices slice will contain exactly one +// index expression. For an ast.IndexListExpr (go1.18+), it may have a variable +// number of index expressions. +// +// For nodes that don't represent index expressions, the first return value of +// UnpackIndexExpr will be nil. +func UnpackIndexExpr(n ast.Node) (x ast.Expr, lbrack token.Pos, indices []ast.Expr, rbrack token.Pos) { + switch e := n.(type) { + case *ast.IndexExpr: + return e.X, e.Lbrack, []ast.Expr{e.Index}, e.Rbrack + case *ast.IndexListExpr: + return e.X, e.Lbrack, e.Indices, e.Rbrack + } + return nil, token.NoPos, nil, token.NoPos +} + +// PackIndexExpr returns an *ast.IndexExpr or *ast.IndexListExpr, depending on +// the cardinality of indices. Calling PackIndexExpr with len(indices) == 0 +// will panic. +func PackIndexExpr(x ast.Expr, lbrack token.Pos, indices []ast.Expr, rbrack token.Pos) ast.Expr { + switch len(indices) { + case 0: + panic("empty indices") + case 1: + return &ast.IndexExpr{ + X: x, + Lbrack: lbrack, + Index: indices[0], + Rbrack: rbrack, + } + default: + return &ast.IndexListExpr{ + X: x, + Lbrack: lbrack, + Indices: indices, + Rbrack: rbrack, + } + } +} + +// IsTypeParam reports whether t is a type parameter (or an alias of one). +func IsTypeParam(t types.Type) bool { + _, ok := types.Unalias(t).(*types.TypeParam) + return ok +} diff --git a/vendor/golang.org/x/tools/internal/typeparams/coretype.go b/vendor/golang.org/x/tools/internal/typeparams/coretype.go new file mode 100644 index 0000000000..6e83c6fb1a --- /dev/null +++ b/vendor/golang.org/x/tools/internal/typeparams/coretype.go @@ -0,0 +1,150 @@ +// Copyright 2022 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 typeparams + +import ( + "fmt" + "go/types" +) + +// CoreType returns the core type of T or nil if T does not have a core type. +// +// See https://go.dev/ref/spec#Core_types for the definition of a core type. +func CoreType(T types.Type) types.Type { + U := T.Underlying() + if _, ok := U.(*types.Interface); !ok { + return U // for non-interface types, + } + + terms, err := NormalTerms(U) + if len(terms) == 0 || err != nil { + // len(terms) -> empty type set of interface. + // err != nil => U is invalid, exceeds complexity bounds, or has an empty type set. + return nil // no core type. + } + + U = terms[0].Type().Underlying() + var identical int // i in [0,identical) => Identical(U, terms[i].Type().Underlying()) + for identical = 1; identical < len(terms); identical++ { + if !types.Identical(U, terms[identical].Type().Underlying()) { + break + } + } + + if identical == len(terms) { + // https://go.dev/ref/spec#Core_types + // "There is a single type U which is the underlying type of all types in the type set of T" + return U + } + ch, ok := U.(*types.Chan) + if !ok { + return nil // no core type as identical < len(terms) and U is not a channel. + } + // https://go.dev/ref/spec#Core_types + // "the type chan E if T contains only bidirectional channels, or the type chan<- E or + // <-chan E depending on the direction of the directional channels present." + for chans := identical; chans < len(terms); chans++ { + curr, ok := terms[chans].Type().Underlying().(*types.Chan) + if !ok { + return nil + } + if !types.Identical(ch.Elem(), curr.Elem()) { + return nil // channel elements are not identical. + } + if ch.Dir() == types.SendRecv { + // ch is bidirectional. We can safely always use curr's direction. + ch = curr + } else if curr.Dir() != types.SendRecv && ch.Dir() != curr.Dir() { + // ch and curr are not bidirectional and not the same direction. + return nil + } + } + return ch +} + +// NormalTerms returns a slice of terms representing the normalized structural +// type restrictions of a type, if any. +// +// For all types other than *types.TypeParam, *types.Interface, and +// *types.Union, this is just a single term with Tilde() == false and +// Type() == typ. For *types.TypeParam, *types.Interface, and *types.Union, see +// below. +// +// Structural type restrictions of a type parameter are created via +// non-interface types embedded in its constraint interface (directly, or via a +// chain of interface embeddings). For example, in the declaration type +// T[P interface{~int; m()}] int the structural restriction of the type +// parameter P is ~int. +// +// With interface embedding and unions, the specification of structural type +// restrictions may be arbitrarily complex. For example, consider the +// following: +// +// type A interface{ ~string|~[]byte } +// +// type B interface{ int|string } +// +// type C interface { ~string|~int } +// +// type T[P interface{ A|B; C }] int +// +// In this example, the structural type restriction of P is ~string|int: A|B +// expands to ~string|~[]byte|int|string, which reduces to ~string|~[]byte|int, +// which when intersected with C (~string|~int) yields ~string|int. +// +// NormalTerms computes these expansions and reductions, producing a +// "normalized" form of the embeddings. A structural restriction is normalized +// if it is a single union containing no interface terms, and is minimal in the +// sense that removing any term changes the set of types satisfying the +// constraint. It is left as a proof for the reader that, modulo sorting, there +// is exactly one such normalized form. +// +// Because the minimal representation always takes this form, NormalTerms +// returns a slice of tilde terms corresponding to the terms of the union in +// the normalized structural restriction. An error is returned if the type is +// invalid, exceeds complexity bounds, or has an empty type set. In the latter +// case, NormalTerms returns ErrEmptyTypeSet. +// +// NormalTerms makes no guarantees about the order of terms, except that it +// is deterministic. +func NormalTerms(typ types.Type) ([]*types.Term, error) { + switch typ := typ.Underlying().(type) { + case *types.TypeParam: + return StructuralTerms(typ) + case *types.Union: + return UnionTermSet(typ) + case *types.Interface: + return InterfaceTermSet(typ) + default: + return []*types.Term{types.NewTerm(false, typ)}, nil + } +} + +// Deref returns the type of the variable pointed to by t, +// if t's core type is a pointer; otherwise it returns t. +// +// Do not assume that Deref(T)==T implies T is not a pointer: +// consider "type T *T", for example. +// +// TODO(adonovan): ideally this would live in typesinternal, but that +// creates an import cycle. Move there when we melt this package down. +func Deref(t types.Type) types.Type { + if ptr, ok := CoreType(t).(*types.Pointer); ok { + return ptr.Elem() + } + return t +} + +// MustDeref returns the type of the variable pointed to by t. +// It panics if t's core type is not a pointer. +// +// TODO(adonovan): ideally this would live in typesinternal, but that +// creates an import cycle. Move there when we melt this package down. +func MustDeref(t types.Type) types.Type { + if ptr, ok := CoreType(t).(*types.Pointer); ok { + return ptr.Elem() + } + panic(fmt.Sprintf("%v is not a pointer", t)) +} diff --git a/vendor/golang.org/x/tools/internal/typeparams/free.go b/vendor/golang.org/x/tools/internal/typeparams/free.go new file mode 100644 index 0000000000..0ade5c2949 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/typeparams/free.go @@ -0,0 +1,131 @@ +// Copyright 2024 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 typeparams + +import ( + "go/types" + + "golang.org/x/tools/internal/aliases" +) + +// Free is a memoization of the set of free type parameters within a +// type. It makes a sequence of calls to [Free.Has] for overlapping +// types more efficient. The zero value is ready for use. +// +// NOTE: Adapted from go/types/infer.go. If it is later exported, factor. +type Free struct { + seen map[types.Type]bool +} + +// Has reports whether the specified type has a free type parameter. +func (w *Free) Has(typ types.Type) (res bool) { + // detect cycles + if x, ok := w.seen[typ]; ok { + return x + } + if w.seen == nil { + w.seen = make(map[types.Type]bool) + } + w.seen[typ] = false + defer func() { + w.seen[typ] = res + }() + + switch t := typ.(type) { + case nil, *types.Basic: // TODO(gri) should nil be handled here? + break + + case *types.Alias: + if aliases.TypeParams(t).Len() > aliases.TypeArgs(t).Len() { + return true // This is an uninstantiated Alias. + } + // The expansion of an alias can have free type parameters, + // whether or not the alias itself has type parameters: + // + // func _[K comparable]() { + // type Set = map[K]bool // free(Set) = {K} + // type MapTo[V] = map[K]V // free(Map[foo]) = {V} + // } + // + // So, we must Unalias. + return w.Has(types.Unalias(t)) + + case *types.Array: + return w.Has(t.Elem()) + + case *types.Slice: + return w.Has(t.Elem()) + + case *types.Struct: + for i, n := 0, t.NumFields(); i < n; i++ { + if w.Has(t.Field(i).Type()) { + return true + } + } + + case *types.Pointer: + return w.Has(t.Elem()) + + case *types.Tuple: + n := t.Len() + for i := 0; i < n; i++ { + if w.Has(t.At(i).Type()) { + return true + } + } + + case *types.Signature: + // t.tparams may not be nil if we are looking at a signature + // of a generic function type (or an interface method) that is + // part of the type we're testing. We don't care about these type + // parameters. + // Similarly, the receiver of a method may declare (rather than + // use) type parameters, we don't care about those either. + // Thus, we only need to look at the input and result parameters. + return w.Has(t.Params()) || w.Has(t.Results()) + + case *types.Interface: + for i, n := 0, t.NumMethods(); i < n; i++ { + if w.Has(t.Method(i).Type()) { + return true + } + } + terms, err := InterfaceTermSet(t) + if err != nil { + return false // ill typed + } + for _, term := range terms { + if w.Has(term.Type()) { + return true + } + } + + case *types.Map: + return w.Has(t.Key()) || w.Has(t.Elem()) + + case *types.Chan: + return w.Has(t.Elem()) + + case *types.Named: + args := t.TypeArgs() + if params := t.TypeParams(); params.Len() > args.Len() { + return true // this is an uninstantiated named type. + } + for i, n := 0, args.Len(); i < n; i++ { + if w.Has(args.At(i)) { + return true + } + } + return w.Has(t.Underlying()) // recurse for types local to parameterized functions + + case *types.TypeParam: + return true + + default: + panic(t) // unreachable + } + + return false +} diff --git a/vendor/golang.org/x/tools/internal/typeparams/normalize.go b/vendor/golang.org/x/tools/internal/typeparams/normalize.go new file mode 100644 index 0000000000..93c80fdc96 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/typeparams/normalize.go @@ -0,0 +1,218 @@ +// Copyright 2021 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 typeparams + +import ( + "errors" + "fmt" + "go/types" + "os" + "strings" +) + +//go:generate go run copytermlist.go + +const debug = false + +var ErrEmptyTypeSet = errors.New("empty type set") + +// StructuralTerms returns a slice of terms representing the normalized +// structural type restrictions of a type parameter, if any. +// +// Structural type restrictions of a type parameter are created via +// non-interface types embedded in its constraint interface (directly, or via a +// chain of interface embeddings). For example, in the declaration +// +// type T[P interface{~int; m()}] int +// +// the structural restriction of the type parameter P is ~int. +// +// With interface embedding and unions, the specification of structural type +// restrictions may be arbitrarily complex. For example, consider the +// following: +// +// type A interface{ ~string|~[]byte } +// +// type B interface{ int|string } +// +// type C interface { ~string|~int } +// +// type T[P interface{ A|B; C }] int +// +// In this example, the structural type restriction of P is ~string|int: A|B +// expands to ~string|~[]byte|int|string, which reduces to ~string|~[]byte|int, +// which when intersected with C (~string|~int) yields ~string|int. +// +// StructuralTerms computes these expansions and reductions, producing a +// "normalized" form of the embeddings. A structural restriction is normalized +// if it is a single union containing no interface terms, and is minimal in the +// sense that removing any term changes the set of types satisfying the +// constraint. It is left as a proof for the reader that, modulo sorting, there +// is exactly one such normalized form. +// +// Because the minimal representation always takes this form, StructuralTerms +// returns a slice of tilde terms corresponding to the terms of the union in +// the normalized structural restriction. An error is returned if the +// constraint interface is invalid, exceeds complexity bounds, or has an empty +// type set. In the latter case, StructuralTerms returns ErrEmptyTypeSet. +// +// StructuralTerms makes no guarantees about the order of terms, except that it +// is deterministic. +func StructuralTerms(tparam *types.TypeParam) ([]*types.Term, error) { + constraint := tparam.Constraint() + if constraint == nil { + return nil, fmt.Errorf("%s has nil constraint", tparam) + } + iface, _ := constraint.Underlying().(*types.Interface) + if iface == nil { + return nil, fmt.Errorf("constraint is %T, not *types.Interface", constraint.Underlying()) + } + return InterfaceTermSet(iface) +} + +// InterfaceTermSet computes the normalized terms for a constraint interface, +// returning an error if the term set cannot be computed or is empty. In the +// latter case, the error will be ErrEmptyTypeSet. +// +// See the documentation of StructuralTerms for more information on +// normalization. +func InterfaceTermSet(iface *types.Interface) ([]*types.Term, error) { + return computeTermSet(iface) +} + +// UnionTermSet computes the normalized terms for a union, returning an error +// if the term set cannot be computed or is empty. In the latter case, the +// error will be ErrEmptyTypeSet. +// +// See the documentation of StructuralTerms for more information on +// normalization. +func UnionTermSet(union *types.Union) ([]*types.Term, error) { + return computeTermSet(union) +} + +func computeTermSet(typ types.Type) ([]*types.Term, error) { + tset, err := computeTermSetInternal(typ, make(map[types.Type]*termSet), 0) + if err != nil { + return nil, err + } + if tset.terms.isEmpty() { + return nil, ErrEmptyTypeSet + } + if tset.terms.isAll() { + return nil, nil + } + var terms []*types.Term + for _, term := range tset.terms { + terms = append(terms, types.NewTerm(term.tilde, term.typ)) + } + return terms, nil +} + +// A termSet holds the normalized set of terms for a given type. +// +// The name termSet is intentionally distinct from 'type set': a type set is +// all types that implement a type (and includes method restrictions), whereas +// a term set just represents the structural restrictions on a type. +type termSet struct { + complete bool + terms termlist +} + +func indentf(depth int, format string, args ...interface{}) { + fmt.Fprintf(os.Stderr, strings.Repeat(".", depth)+format+"\n", args...) +} + +func computeTermSetInternal(t types.Type, seen map[types.Type]*termSet, depth int) (res *termSet, err error) { + if t == nil { + panic("nil type") + } + + if debug { + indentf(depth, "%s", t.String()) + defer func() { + if err != nil { + indentf(depth, "=> %s", err) + } else { + indentf(depth, "=> %s", res.terms.String()) + } + }() + } + + const maxTermCount = 100 + if tset, ok := seen[t]; ok { + if !tset.complete { + return nil, fmt.Errorf("cycle detected in the declaration of %s", t) + } + return tset, nil + } + + // Mark the current type as seen to avoid infinite recursion. + tset := new(termSet) + defer func() { + tset.complete = true + }() + seen[t] = tset + + switch u := t.Underlying().(type) { + case *types.Interface: + // The term set of an interface is the intersection of the term sets of its + // embedded types. + tset.terms = allTermlist + for i := 0; i < u.NumEmbeddeds(); i++ { + embedded := u.EmbeddedType(i) + if _, ok := embedded.Underlying().(*types.TypeParam); ok { + return nil, fmt.Errorf("invalid embedded type %T", embedded) + } + tset2, err := computeTermSetInternal(embedded, seen, depth+1) + if err != nil { + return nil, err + } + tset.terms = tset.terms.intersect(tset2.terms) + } + case *types.Union: + // The term set of a union is the union of term sets of its terms. + tset.terms = nil + for i := 0; i < u.Len(); i++ { + t := u.Term(i) + var terms termlist + switch t.Type().Underlying().(type) { + case *types.Interface: + tset2, err := computeTermSetInternal(t.Type(), seen, depth+1) + if err != nil { + return nil, err + } + terms = tset2.terms + case *types.TypeParam, *types.Union: + // A stand-alone type parameter or union is not permitted as union + // term. + return nil, fmt.Errorf("invalid union term %T", t) + default: + if t.Type() == types.Typ[types.Invalid] { + continue + } + terms = termlist{{t.Tilde(), t.Type()}} + } + tset.terms = tset.terms.union(terms) + if len(tset.terms) > maxTermCount { + return nil, fmt.Errorf("exceeded max term count %d", maxTermCount) + } + } + case *types.TypeParam: + panic("unreachable") + default: + // For all other types, the term set is just a single non-tilde term + // holding the type itself. + if u != types.Typ[types.Invalid] { + tset.terms = termlist{{false, t}} + } + } + return tset, nil +} + +// under is a facade for the go/types internal function of the same name. It is +// used by typeterm.go. +func under(t types.Type) types.Type { + return t.Underlying() +} diff --git a/vendor/golang.org/x/tools/internal/typeparams/termlist.go b/vendor/golang.org/x/tools/internal/typeparams/termlist.go new file mode 100644 index 0000000000..cbd12f8013 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/typeparams/termlist.go @@ -0,0 +1,163 @@ +// Copyright 2021 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. + +// Code generated by copytermlist.go DO NOT EDIT. + +package typeparams + +import ( + "bytes" + "go/types" +) + +// A termlist represents the type set represented by the union +// t1 ∪ y2 ∪ ... tn of the type sets of the terms t1 to tn. +// A termlist is in normal form if all terms are disjoint. +// termlist operations don't require the operands to be in +// normal form. +type termlist []*term + +// allTermlist represents the set of all types. +// It is in normal form. +var allTermlist = termlist{new(term)} + +// String prints the termlist exactly (without normalization). +func (xl termlist) String() string { + if len(xl) == 0 { + return "∅" + } + var buf bytes.Buffer + for i, x := range xl { + if i > 0 { + buf.WriteString(" | ") + } + buf.WriteString(x.String()) + } + return buf.String() +} + +// isEmpty reports whether the termlist xl represents the empty set of types. +func (xl termlist) isEmpty() bool { + // If there's a non-nil term, the entire list is not empty. + // If the termlist is in normal form, this requires at most + // one iteration. + for _, x := range xl { + if x != nil { + return false + } + } + return true +} + +// isAll reports whether the termlist xl represents the set of all types. +func (xl termlist) isAll() bool { + // If there's a 𝓤 term, the entire list is 𝓤. + // If the termlist is in normal form, this requires at most + // one iteration. + for _, x := range xl { + if x != nil && x.typ == nil { + return true + } + } + return false +} + +// norm returns the normal form of xl. +func (xl termlist) norm() termlist { + // Quadratic algorithm, but good enough for now. + // TODO(gri) fix asymptotic performance + used := make([]bool, len(xl)) + var rl termlist + for i, xi := range xl { + if xi == nil || used[i] { + continue + } + for j := i + 1; j < len(xl); j++ { + xj := xl[j] + if xj == nil || used[j] { + continue + } + if u1, u2 := xi.union(xj); u2 == nil { + // If we encounter a 𝓤 term, the entire list is 𝓤. + // Exit early. + // (Note that this is not just an optimization; + // if we continue, we may end up with a 𝓤 term + // and other terms and the result would not be + // in normal form.) + if u1.typ == nil { + return allTermlist + } + xi = u1 + used[j] = true // xj is now unioned into xi - ignore it in future iterations + } + } + rl = append(rl, xi) + } + return rl +} + +// union returns the union xl ∪ yl. +func (xl termlist) union(yl termlist) termlist { + return append(xl, yl...).norm() +} + +// intersect returns the intersection xl ∩ yl. +func (xl termlist) intersect(yl termlist) termlist { + if xl.isEmpty() || yl.isEmpty() { + return nil + } + + // Quadratic algorithm, but good enough for now. + // TODO(gri) fix asymptotic performance + var rl termlist + for _, x := range xl { + for _, y := range yl { + if r := x.intersect(y); r != nil { + rl = append(rl, r) + } + } + } + return rl.norm() +} + +// equal reports whether xl and yl represent the same type set. +func (xl termlist) equal(yl termlist) bool { + // TODO(gri) this should be more efficient + return xl.subsetOf(yl) && yl.subsetOf(xl) +} + +// includes reports whether t ∈ xl. +func (xl termlist) includes(t types.Type) bool { + for _, x := range xl { + if x.includes(t) { + return true + } + } + return false +} + +// supersetOf reports whether y ⊆ xl. +func (xl termlist) supersetOf(y *term) bool { + for _, x := range xl { + if y.subsetOf(x) { + return true + } + } + return false +} + +// subsetOf reports whether xl ⊆ yl. +func (xl termlist) subsetOf(yl termlist) bool { + if yl.isEmpty() { + return xl.isEmpty() + } + + // each term x of xl must be a subset of yl + for _, x := range xl { + if !yl.supersetOf(x) { + return false // x is not a subset yl + } + } + return true +} diff --git a/vendor/golang.org/x/tools/internal/typeparams/typeterm.go b/vendor/golang.org/x/tools/internal/typeparams/typeterm.go new file mode 100644 index 0000000000..7350bb702a --- /dev/null +++ b/vendor/golang.org/x/tools/internal/typeparams/typeterm.go @@ -0,0 +1,169 @@ +// Copyright 2021 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. + +// Code generated by copytermlist.go DO NOT EDIT. + +package typeparams + +import "go/types" + +// A term describes elementary type sets: +// +// ∅: (*term)(nil) == ∅ // set of no types (empty set) +// 𝓤: &term{} == 𝓤 // set of all types (𝓤niverse) +// T: &term{false, T} == {T} // set of type T +// ~t: &term{true, t} == {t' | under(t') == t} // set of types with underlying type t +type term struct { + tilde bool // valid if typ != nil + typ types.Type +} + +func (x *term) String() string { + switch { + case x == nil: + return "∅" + case x.typ == nil: + return "𝓤" + case x.tilde: + return "~" + x.typ.String() + default: + return x.typ.String() + } +} + +// equal reports whether x and y represent the same type set. +func (x *term) equal(y *term) bool { + // easy cases + switch { + case x == nil || y == nil: + return x == y + case x.typ == nil || y.typ == nil: + return x.typ == y.typ + } + // ∅ ⊂ x, y ⊂ 𝓤 + + return x.tilde == y.tilde && types.Identical(x.typ, y.typ) +} + +// union returns the union x ∪ y: zero, one, or two non-nil terms. +func (x *term) union(y *term) (_, _ *term) { + // easy cases + switch { + case x == nil && y == nil: + return nil, nil // ∅ ∪ ∅ == ∅ + case x == nil: + return y, nil // ∅ ∪ y == y + case y == nil: + return x, nil // x ∪ ∅ == x + case x.typ == nil: + return x, nil // 𝓤 ∪ y == 𝓤 + case y.typ == nil: + return y, nil // x ∪ 𝓤 == 𝓤 + } + // ∅ ⊂ x, y ⊂ 𝓤 + + if x.disjoint(y) { + return x, y // x ∪ y == (x, y) if x ∩ y == ∅ + } + // x.typ == y.typ + + // ~t ∪ ~t == ~t + // ~t ∪ T == ~t + // T ∪ ~t == ~t + // T ∪ T == T + if x.tilde || !y.tilde { + return x, nil + } + return y, nil +} + +// intersect returns the intersection x ∩ y. +func (x *term) intersect(y *term) *term { + // easy cases + switch { + case x == nil || y == nil: + return nil // ∅ ∩ y == ∅ and ∩ ∅ == ∅ + case x.typ == nil: + return y // 𝓤 ∩ y == y + case y.typ == nil: + return x // x ∩ 𝓤 == x + } + // ∅ ⊂ x, y ⊂ 𝓤 + + if x.disjoint(y) { + return nil // x ∩ y == ∅ if x ∩ y == ∅ + } + // x.typ == y.typ + + // ~t ∩ ~t == ~t + // ~t ∩ T == T + // T ∩ ~t == T + // T ∩ T == T + if !x.tilde || y.tilde { + return x + } + return y +} + +// includes reports whether t ∈ x. +func (x *term) includes(t types.Type) bool { + // easy cases + switch { + case x == nil: + return false // t ∈ ∅ == false + case x.typ == nil: + return true // t ∈ 𝓤 == true + } + // ∅ ⊂ x ⊂ 𝓤 + + u := t + if x.tilde { + u = under(u) + } + return types.Identical(x.typ, u) +} + +// subsetOf reports whether x ⊆ y. +func (x *term) subsetOf(y *term) bool { + // easy cases + switch { + case x == nil: + return true // ∅ ⊆ y == true + case y == nil: + return false // x ⊆ ∅ == false since x != ∅ + case y.typ == nil: + return true // x ⊆ 𝓤 == true + case x.typ == nil: + return false // 𝓤 ⊆ y == false since y != 𝓤 + } + // ∅ ⊂ x, y ⊂ 𝓤 + + if x.disjoint(y) { + return false // x ⊆ y == false if x ∩ y == ∅ + } + // x.typ == y.typ + + // ~t ⊆ ~t == true + // ~t ⊆ T == false + // T ⊆ ~t == true + // T ⊆ T == true + return !x.tilde || y.tilde +} + +// disjoint reports whether x ∩ y == ∅. +// x.typ and y.typ must not be nil. +func (x *term) disjoint(y *term) bool { + if debug && (x.typ == nil || y.typ == nil) { + panic("invalid argument(s)") + } + ux := x.typ + if y.tilde { + ux = under(ux) + } + uy := y.typ + if x.tilde { + uy = under(uy) + } + return !types.Identical(ux, uy) +} diff --git a/vendor/golang.org/x/tools/internal/typesinternal/element.go b/vendor/golang.org/x/tools/internal/typesinternal/element.go new file mode 100644 index 0000000000..4957f02164 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/typesinternal/element.go @@ -0,0 +1,133 @@ +// Copyright 2024 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 typesinternal + +import ( + "fmt" + "go/types" + + "golang.org/x/tools/go/types/typeutil" +) + +// ForEachElement calls f for type T and each type reachable from its +// type through reflection. It does this by recursively stripping off +// type constructors; in addition, for each named type N, the type *N +// is added to the result as it may have additional methods. +// +// The caller must provide an initially empty set used to de-duplicate +// identical types, potentially across multiple calls to ForEachElement. +// (Its final value holds all the elements seen, matching the arguments +// passed to f.) +// +// TODO(adonovan): share/harmonize with go/callgraph/rta. +func ForEachElement(rtypes *typeutil.Map, msets *typeutil.MethodSetCache, T types.Type, f func(types.Type)) { + var visit func(T types.Type, skip bool) + visit = func(T types.Type, skip bool) { + if !skip { + if seen, _ := rtypes.Set(T, true).(bool); seen { + return // de-dup + } + + f(T) // notify caller of new element type + } + + // Recursion over signatures of each method. + tmset := msets.MethodSet(T) + for i := 0; i < tmset.Len(); i++ { + sig := tmset.At(i).Type().(*types.Signature) + // It is tempting to call visit(sig, false) + // but, as noted in golang.org/cl/65450043, + // the Signature.Recv field is ignored by + // types.Identical and typeutil.Map, which + // is confusing at best. + // + // More importantly, the true signature rtype + // reachable from a method using reflection + // has no receiver but an extra ordinary parameter. + // For the Read method of io.Reader we want: + // func(Reader, []byte) (int, error) + // but here sig is: + // func([]byte) (int, error) + // with .Recv = Reader (though it is hard to + // notice because it doesn't affect Signature.String + // or types.Identical). + // + // TODO(adonovan): construct and visit the correct + // non-method signature with an extra parameter + // (though since unnamed func types have no methods + // there is essentially no actual demand for this). + // + // TODO(adonovan): document whether or not it is + // safe to skip non-exported methods (as RTA does). + visit(sig.Params(), true) // skip the Tuple + visit(sig.Results(), true) // skip the Tuple + } + + switch T := T.(type) { + case *types.Alias: + visit(types.Unalias(T), skip) // emulates the pre-Alias behavior + + case *types.Basic: + // nop + + case *types.Interface: + // nop---handled by recursion over method set. + + case *types.Pointer: + visit(T.Elem(), false) + + case *types.Slice: + visit(T.Elem(), false) + + case *types.Chan: + visit(T.Elem(), false) + + case *types.Map: + visit(T.Key(), false) + visit(T.Elem(), false) + + case *types.Signature: + if T.Recv() != nil { + panic(fmt.Sprintf("Signature %s has Recv %s", T, T.Recv())) + } + visit(T.Params(), true) // skip the Tuple + visit(T.Results(), true) // skip the Tuple + + case *types.Named: + // A pointer-to-named type can be derived from a named + // type via reflection. It may have methods too. + visit(types.NewPointer(T), false) + + // Consider 'type T struct{S}' where S has methods. + // Reflection provides no way to get from T to struct{S}, + // only to S, so the method set of struct{S} is unwanted, + // so set 'skip' flag during recursion. + visit(T.Underlying(), true) // skip the unnamed type + + case *types.Array: + visit(T.Elem(), false) + + case *types.Struct: + for i, n := 0, T.NumFields(); i < n; i++ { + // TODO(adonovan): document whether or not + // it is safe to skip non-exported fields. + visit(T.Field(i).Type(), false) + } + + case *types.Tuple: + for i, n := 0, T.Len(); i < n; i++ { + visit(T.At(i).Type(), false) + } + + case *types.TypeParam, *types.Union: + // forEachReachable must not be called on parameterized types. + panic(T) + + default: + panic(T) + } + } + visit(T, false) +} diff --git a/vendor/golang.org/x/tools/internal/typesinternal/errorcode.go b/vendor/golang.org/x/tools/internal/typesinternal/errorcode.go index 834e05381c..131caab284 100644 --- a/vendor/golang.org/x/tools/internal/typesinternal/errorcode.go +++ b/vendor/golang.org/x/tools/internal/typesinternal/errorcode.go @@ -838,7 +838,7 @@ const ( // InvalidCap occurs when an argument to the cap built-in function is not of // supported type. // - // See https://golang.org/ref/spec#Lengthand_capacity for information on + // See https://golang.org/ref/spec#Length_and_capacity for information on // which underlying types are supported as arguments to cap and len. // // Example: @@ -859,7 +859,7 @@ const ( // InvalidCopy occurs when the arguments are not of slice type or do not // have compatible type. // - // See https://golang.org/ref/spec#Appendingand_copying_slices for more + // See https://golang.org/ref/spec#Appending_and_copying_slices for more // information on the type requirements for the copy built-in. // // Example: @@ -897,7 +897,7 @@ const ( // InvalidLen occurs when an argument to the len built-in function is not of // supported type. // - // See https://golang.org/ref/spec#Lengthand_capacity for information on + // See https://golang.org/ref/spec#Length_and_capacity for information on // which underlying types are supported as arguments to cap and len. // // Example: @@ -914,7 +914,7 @@ const ( // InvalidMake occurs when make is called with an unsupported type argument. // - // See https://golang.org/ref/spec#Makingslices_maps_and_channels for + // See https://golang.org/ref/spec#Making_slices_maps_and_channels for // information on the types that may be created using make. // // Example: diff --git a/vendor/golang.org/x/tools/internal/typesinternal/qualifier.go b/vendor/golang.org/x/tools/internal/typesinternal/qualifier.go new file mode 100644 index 0000000000..b64f714eb3 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/typesinternal/qualifier.go @@ -0,0 +1,46 @@ +// Copyright 2024 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 typesinternal + +import ( + "go/ast" + "go/types" + "strconv" +) + +// FileQualifier returns a [types.Qualifier] function that qualifies +// imported symbols appropriately based on the import environment of a given +// file. +// If the same package is imported multiple times, the last appearance is +// recorded. +func FileQualifier(f *ast.File, pkg *types.Package) types.Qualifier { + // Construct mapping of import paths to their defined names. + // It is only necessary to look at renaming imports. + imports := make(map[string]string) + for _, imp := range f.Imports { + if imp.Name != nil && imp.Name.Name != "_" { + path, _ := strconv.Unquote(imp.Path.Value) + imports[path] = imp.Name.Name + } + } + + // Define qualifier to replace full package paths with names of the imports. + return func(p *types.Package) string { + if p == nil || p == pkg { + return "" + } + + if name, ok := imports[p.Path()]; ok { + if name == "." { + return "" + } else { + return name + } + } + + // If there is no local renaming, fall back to the package name. + return p.Name() + } +} diff --git a/vendor/golang.org/x/tools/internal/typesinternal/recv.go b/vendor/golang.org/x/tools/internal/typesinternal/recv.go index fea7c8b75e..e54accc69a 100644 --- a/vendor/golang.org/x/tools/internal/typesinternal/recv.go +++ b/vendor/golang.org/x/tools/internal/typesinternal/recv.go @@ -6,20 +6,20 @@ package typesinternal import ( "go/types" - - "golang.org/x/tools/internal/aliases" ) // ReceiverNamed returns the named type (if any) associated with the // type of recv, which may be of the form N or *N, or aliases thereof. // It also reports whether a Pointer was present. +// +// The named result may be nil in ill-typed code. func ReceiverNamed(recv *types.Var) (isPtr bool, named *types.Named) { t := recv.Type() - if ptr, ok := aliases.Unalias(t).(*types.Pointer); ok { + if ptr, ok := types.Unalias(t).(*types.Pointer); ok { isPtr = true t = ptr.Elem() } - named, _ = aliases.Unalias(t).(*types.Named) + named, _ = types.Unalias(t).(*types.Named) return } @@ -36,7 +36,7 @@ func ReceiverNamed(recv *types.Var) (isPtr bool, named *types.Named) { // indirection from the type, regardless of named types (analogous to // a LOAD instruction). func Unpointer(t types.Type) types.Type { - if ptr, ok := aliases.Unalias(t).(*types.Pointer); ok { + if ptr, ok := types.Unalias(t).(*types.Pointer); ok { return ptr.Elem() } return t diff --git a/vendor/golang.org/x/tools/internal/typesinternal/types.go b/vendor/golang.org/x/tools/internal/typesinternal/types.go index 8392328612..a93d51f988 100644 --- a/vendor/golang.org/x/tools/internal/typesinternal/types.go +++ b/vendor/golang.org/x/tools/internal/typesinternal/types.go @@ -11,6 +11,8 @@ import ( "go/types" "reflect" "unsafe" + + "golang.org/x/tools/internal/aliases" ) func SetUsesCgo(conf *types.Config) bool { @@ -63,3 +65,58 @@ func NameRelativeTo(pkg *types.Package) types.Qualifier { return other.Name() } } + +// A NamedOrAlias is a [types.Type] that is named (as +// defined by the spec) and capable of bearing type parameters: it +// abstracts aliases ([types.Alias]) and defined types +// ([types.Named]). +// +// Every type declared by an explicit "type" declaration is a +// NamedOrAlias. (Built-in type symbols may additionally +// have type [types.Basic], which is not a NamedOrAlias, +// though the spec regards them as "named".) +// +// NamedOrAlias cannot expose the Origin method, because +// [types.Alias.Origin] and [types.Named.Origin] have different +// (covariant) result types; use [Origin] instead. +type NamedOrAlias interface { + types.Type + Obj() *types.TypeName + // TODO(hxjiang): add method TypeArgs() *types.TypeList after stop supporting go1.22. +} + +// TypeParams is a light shim around t.TypeParams(). +// (go/types.Alias).TypeParams requires >= 1.23. +func TypeParams(t NamedOrAlias) *types.TypeParamList { + switch t := t.(type) { + case *types.Alias: + return aliases.TypeParams(t) + case *types.Named: + return t.TypeParams() + } + return nil +} + +// TypeArgs is a light shim around t.TypeArgs(). +// (go/types.Alias).TypeArgs requires >= 1.23. +func TypeArgs(t NamedOrAlias) *types.TypeList { + switch t := t.(type) { + case *types.Alias: + return aliases.TypeArgs(t) + case *types.Named: + return t.TypeArgs() + } + return nil +} + +// Origin returns the generic type of the Named or Alias type t if it +// is instantiated, otherwise it returns t. +func Origin(t NamedOrAlias) NamedOrAlias { + switch t := t.(type) { + case *types.Alias: + return aliases.Origin(t) + case *types.Named: + return t.Origin() + } + return t +} diff --git a/vendor/golang.org/x/tools/internal/typesinternal/zerovalue.go b/vendor/golang.org/x/tools/internal/typesinternal/zerovalue.go new file mode 100644 index 0000000000..d272949c17 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/typesinternal/zerovalue.go @@ -0,0 +1,392 @@ +// Copyright 2024 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 typesinternal + +import ( + "fmt" + "go/ast" + "go/token" + "go/types" + "strings" +) + +// ZeroString returns the string representation of the zero value for any type t. +// The boolean result indicates whether the type is or contains an invalid type +// or a non-basic (constraint) interface type. +// +// Even for invalid input types, ZeroString may return a partially correct +// string representation. The caller should use the returned isValid boolean +// to determine the validity of the expression. +// +// When assigning to a wider type (such as 'any'), it's the caller's +// responsibility to handle any necessary type conversions. +// +// This string can be used on the right-hand side of an assignment where the +// left-hand side has that explicit type. +// References to named types are qualified by an appropriate (optional) +// qualifier function. +// Exception: This does not apply to tuples. Their string representation is +// informational only and cannot be used in an assignment. +// +// See [ZeroExpr] for a variant that returns an [ast.Expr]. +func ZeroString(t types.Type, qual types.Qualifier) (_ string, isValid bool) { + switch t := t.(type) { + case *types.Basic: + switch { + case t.Info()&types.IsBoolean != 0: + return "false", true + case t.Info()&types.IsNumeric != 0: + return "0", true + case t.Info()&types.IsString != 0: + return `""`, true + case t.Kind() == types.UnsafePointer: + fallthrough + case t.Kind() == types.UntypedNil: + return "nil", true + case t.Kind() == types.Invalid: + return "invalid", false + default: + panic(fmt.Sprintf("ZeroString for unexpected type %v", t)) + } + + case *types.Pointer, *types.Slice, *types.Chan, *types.Map, *types.Signature: + return "nil", true + + case *types.Interface: + if !t.IsMethodSet() { + return "invalid", false + } + return "nil", true + + case *types.Named: + switch under := t.Underlying().(type) { + case *types.Struct, *types.Array: + return types.TypeString(t, qual) + "{}", true + default: + return ZeroString(under, qual) + } + + case *types.Alias: + switch t.Underlying().(type) { + case *types.Struct, *types.Array: + return types.TypeString(t, qual) + "{}", true + default: + // A type parameter can have alias but alias type's underlying type + // can never be a type parameter. + // Use types.Unalias to preserve the info of type parameter instead + // of call Underlying() going right through and get the underlying + // type of the type parameter which is always an interface. + return ZeroString(types.Unalias(t), qual) + } + + case *types.Array, *types.Struct: + return types.TypeString(t, qual) + "{}", true + + case *types.TypeParam: + // Assumes func new is not shadowed. + return "*new(" + types.TypeString(t, qual) + ")", true + + case *types.Tuple: + // Tuples are not normal values. + // We are currently format as "(t[0], ..., t[n])". Could be something else. + isValid := true + components := make([]string, t.Len()) + for i := 0; i < t.Len(); i++ { + comp, ok := ZeroString(t.At(i).Type(), qual) + + components[i] = comp + isValid = isValid && ok + } + return "(" + strings.Join(components, ", ") + ")", isValid + + case *types.Union: + // Variables of these types cannot be created, so it makes + // no sense to ask for their zero value. + panic(fmt.Sprintf("invalid type for a variable: %v", t)) + + default: + panic(t) // unreachable. + } +} + +// ZeroExpr returns the ast.Expr representation of the zero value for any type t. +// The boolean result indicates whether the type is or contains an invalid type +// or a non-basic (constraint) interface type. +// +// Even for invalid input types, ZeroExpr may return a partially correct ast.Expr +// representation. The caller should use the returned isValid boolean to determine +// the validity of the expression. +// +// This function is designed for types suitable for variables and should not be +// used with Tuple or Union types.References to named types are qualified by an +// appropriate (optional) qualifier function. +// +// See [ZeroString] for a variant that returns a string. +func ZeroExpr(t types.Type, qual types.Qualifier) (_ ast.Expr, isValid bool) { + switch t := t.(type) { + case *types.Basic: + switch { + case t.Info()&types.IsBoolean != 0: + return &ast.Ident{Name: "false"}, true + case t.Info()&types.IsNumeric != 0: + return &ast.BasicLit{Kind: token.INT, Value: "0"}, true + case t.Info()&types.IsString != 0: + return &ast.BasicLit{Kind: token.STRING, Value: `""`}, true + case t.Kind() == types.UnsafePointer: + fallthrough + case t.Kind() == types.UntypedNil: + return ast.NewIdent("nil"), true + case t.Kind() == types.Invalid: + return &ast.BasicLit{Kind: token.STRING, Value: `"invalid"`}, false + default: + panic(fmt.Sprintf("ZeroExpr for unexpected type %v", t)) + } + + case *types.Pointer, *types.Slice, *types.Chan, *types.Map, *types.Signature: + return ast.NewIdent("nil"), true + + case *types.Interface: + if !t.IsMethodSet() { + return &ast.BasicLit{Kind: token.STRING, Value: `"invalid"`}, false + } + return ast.NewIdent("nil"), true + + case *types.Named: + switch under := t.Underlying().(type) { + case *types.Struct, *types.Array: + return &ast.CompositeLit{ + Type: TypeExpr(t, qual), + }, true + default: + return ZeroExpr(under, qual) + } + + case *types.Alias: + switch t.Underlying().(type) { + case *types.Struct, *types.Array: + return &ast.CompositeLit{ + Type: TypeExpr(t, qual), + }, true + default: + return ZeroExpr(types.Unalias(t), qual) + } + + case *types.Array, *types.Struct: + return &ast.CompositeLit{ + Type: TypeExpr(t, qual), + }, true + + case *types.TypeParam: + return &ast.StarExpr{ // *new(T) + X: &ast.CallExpr{ + // Assumes func new is not shadowed. + Fun: ast.NewIdent("new"), + Args: []ast.Expr{ + ast.NewIdent(t.Obj().Name()), + }, + }, + }, true + + case *types.Tuple: + // Unlike ZeroString, there is no ast.Expr can express tuple by + // "(t[0], ..., t[n])". + panic(fmt.Sprintf("invalid type for a variable: %v", t)) + + case *types.Union: + // Variables of these types cannot be created, so it makes + // no sense to ask for their zero value. + panic(fmt.Sprintf("invalid type for a variable: %v", t)) + + default: + panic(t) // unreachable. + } +} + +// IsZeroExpr uses simple syntactic heuristics to report whether expr +// is a obvious zero value, such as 0, "", nil, or false. +// It cannot do better without type information. +func IsZeroExpr(expr ast.Expr) bool { + switch e := expr.(type) { + case *ast.BasicLit: + return e.Value == "0" || e.Value == `""` + case *ast.Ident: + return e.Name == "nil" || e.Name == "false" + default: + return false + } +} + +// TypeExpr returns syntax for the specified type. References to named types +// are qualified by an appropriate (optional) qualifier function. +// It may panic for types such as Tuple or Union. +func TypeExpr(t types.Type, qual types.Qualifier) ast.Expr { + switch t := t.(type) { + case *types.Basic: + switch t.Kind() { + case types.UnsafePointer: + return &ast.SelectorExpr{X: ast.NewIdent(qual(types.NewPackage("unsafe", "unsafe"))), Sel: ast.NewIdent("Pointer")} + default: + return ast.NewIdent(t.Name()) + } + + case *types.Pointer: + return &ast.UnaryExpr{ + Op: token.MUL, + X: TypeExpr(t.Elem(), qual), + } + + case *types.Array: + return &ast.ArrayType{ + Len: &ast.BasicLit{ + Kind: token.INT, + Value: fmt.Sprintf("%d", t.Len()), + }, + Elt: TypeExpr(t.Elem(), qual), + } + + case *types.Slice: + return &ast.ArrayType{ + Elt: TypeExpr(t.Elem(), qual), + } + + case *types.Map: + return &ast.MapType{ + Key: TypeExpr(t.Key(), qual), + Value: TypeExpr(t.Elem(), qual), + } + + case *types.Chan: + dir := ast.ChanDir(t.Dir()) + if t.Dir() == types.SendRecv { + dir = ast.SEND | ast.RECV + } + return &ast.ChanType{ + Dir: dir, + Value: TypeExpr(t.Elem(), qual), + } + + case *types.Signature: + var params []*ast.Field + for i := 0; i < t.Params().Len(); i++ { + params = append(params, &ast.Field{ + Type: TypeExpr(t.Params().At(i).Type(), qual), + Names: []*ast.Ident{ + { + Name: t.Params().At(i).Name(), + }, + }, + }) + } + if t.Variadic() { + last := params[len(params)-1] + last.Type = &ast.Ellipsis{Elt: last.Type.(*ast.ArrayType).Elt} + } + var returns []*ast.Field + for i := 0; i < t.Results().Len(); i++ { + returns = append(returns, &ast.Field{ + Type: TypeExpr(t.Results().At(i).Type(), qual), + }) + } + return &ast.FuncType{ + Params: &ast.FieldList{ + List: params, + }, + Results: &ast.FieldList{ + List: returns, + }, + } + + case *types.TypeParam: + pkgName := qual(t.Obj().Pkg()) + if pkgName == "" || t.Obj().Pkg() == nil { + return ast.NewIdent(t.Obj().Name()) + } + return &ast.SelectorExpr{ + X: ast.NewIdent(pkgName), + Sel: ast.NewIdent(t.Obj().Name()), + } + + // types.TypeParam also implements interface NamedOrAlias. To differentiate, + // case TypeParam need to be present before case NamedOrAlias. + // TODO(hxjiang): remove this comment once TypeArgs() is added to interface + // NamedOrAlias. + case NamedOrAlias: + var expr ast.Expr = ast.NewIdent(t.Obj().Name()) + if pkgName := qual(t.Obj().Pkg()); pkgName != "." && pkgName != "" { + expr = &ast.SelectorExpr{ + X: ast.NewIdent(pkgName), + Sel: expr.(*ast.Ident), + } + } + + // TODO(hxjiang): call t.TypeArgs after adding method TypeArgs() to + // typesinternal.NamedOrAlias. + if hasTypeArgs, ok := t.(interface{ TypeArgs() *types.TypeList }); ok { + if typeArgs := hasTypeArgs.TypeArgs(); typeArgs != nil && typeArgs.Len() > 0 { + var indices []ast.Expr + for i := range typeArgs.Len() { + indices = append(indices, TypeExpr(typeArgs.At(i), qual)) + } + expr = &ast.IndexListExpr{ + X: expr, + Indices: indices, + } + } + } + + return expr + + case *types.Struct: + return ast.NewIdent(t.String()) + + case *types.Interface: + return ast.NewIdent(t.String()) + + case *types.Union: + if t.Len() == 0 { + panic("Union type should have at least one term") + } + // Same as go/ast, the return expression will put last term in the + // Y field at topmost level of BinaryExpr. + // For union of type "float32 | float64 | int64", the structure looks + // similar to: + // { + // X: { + // X: float32, + // Op: | + // Y: float64, + // } + // Op: |, + // Y: int64, + // } + var union ast.Expr + for i := range t.Len() { + term := t.Term(i) + termExpr := TypeExpr(term.Type(), qual) + if term.Tilde() { + termExpr = &ast.UnaryExpr{ + Op: token.TILDE, + X: termExpr, + } + } + if i == 0 { + union = termExpr + } else { + union = &ast.BinaryExpr{ + X: union, + Op: token.OR, + Y: termExpr, + } + } + } + return union + + case *types.Tuple: + panic("invalid input type types.Tuple") + + default: + panic("unreachable") + } +} diff --git a/vendor/golang.org/x/tools/internal/versions/toolchain.go b/vendor/golang.org/x/tools/internal/versions/toolchain.go deleted file mode 100644 index 377bf7a53b..0000000000 --- a/vendor/golang.org/x/tools/internal/versions/toolchain.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2024 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 versions - -// toolchain is maximum version (<1.22) that the go toolchain used -// to build the current tool is known to support. -// -// When a tool is built with >=1.22, the value of toolchain is unused. -// -// x/tools does not support building with go <1.18. So we take this -// as the minimum possible maximum. -var toolchain string = Go1_18 diff --git a/vendor/golang.org/x/tools/internal/versions/toolchain_go119.go b/vendor/golang.org/x/tools/internal/versions/toolchain_go119.go deleted file mode 100644 index f65beed9d8..0000000000 --- a/vendor/golang.org/x/tools/internal/versions/toolchain_go119.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2024 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. - -//go:build go1.19 -// +build go1.19 - -package versions - -func init() { - if Compare(toolchain, Go1_19) < 0 { - toolchain = Go1_19 - } -} diff --git a/vendor/golang.org/x/tools/internal/versions/toolchain_go120.go b/vendor/golang.org/x/tools/internal/versions/toolchain_go120.go deleted file mode 100644 index 1a9efa126c..0000000000 --- a/vendor/golang.org/x/tools/internal/versions/toolchain_go120.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2024 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. - -//go:build go1.20 -// +build go1.20 - -package versions - -func init() { - if Compare(toolchain, Go1_20) < 0 { - toolchain = Go1_20 - } -} diff --git a/vendor/golang.org/x/tools/internal/versions/toolchain_go121.go b/vendor/golang.org/x/tools/internal/versions/toolchain_go121.go deleted file mode 100644 index b7ef216dfe..0000000000 --- a/vendor/golang.org/x/tools/internal/versions/toolchain_go121.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2024 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. - -//go:build go1.21 -// +build go1.21 - -package versions - -func init() { - if Compare(toolchain, Go1_21) < 0 { - toolchain = Go1_21 - } -} diff --git a/vendor/golang.org/x/tools/internal/versions/types.go b/vendor/golang.org/x/tools/internal/versions/types.go index 562eef21fa..0fc10ce4eb 100644 --- a/vendor/golang.org/x/tools/internal/versions/types.go +++ b/vendor/golang.org/x/tools/internal/versions/types.go @@ -5,15 +5,29 @@ package versions import ( + "go/ast" "go/types" ) -// GoVersion returns the Go version of the type package. -// It returns zero if no version can be determined. -func GoVersion(pkg *types.Package) string { - // TODO(taking): x/tools can call GoVersion() [from 1.21] after 1.25. - if pkg, ok := any(pkg).(interface{ GoVersion() string }); ok { - return pkg.GoVersion() +// FileVersion returns a file's Go version. +// The reported version is an unknown Future version if a +// version cannot be determined. +func FileVersion(info *types.Info, file *ast.File) string { + // In tools built with Go >= 1.22, the Go version of a file + // follow a cascades of sources: + // 1) types.Info.FileVersion, which follows the cascade: + // 1.a) file version (ast.File.GoVersion), + // 1.b) the package version (types.Config.GoVersion), or + // 2) is some unknown Future version. + // + // File versions require a valid package version to be provided to types + // in Config.GoVersion. Config.GoVersion is either from the package's module + // or the toolchain (go run). This value should be provided by go/packages + // or unitchecker.Config.GoVersion. + if v := info.FileVersions[file]; IsValid(v) { + return v } - return "" + // Note: we could instead return runtime.Version() [if valid]. + // This would act as a max version on what a tool can support. + return Future } diff --git a/vendor/golang.org/x/tools/internal/versions/types_go121.go b/vendor/golang.org/x/tools/internal/versions/types_go121.go deleted file mode 100644 index b4345d3349..0000000000 --- a/vendor/golang.org/x/tools/internal/versions/types_go121.go +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2023 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. - -//go:build !go1.22 -// +build !go1.22 - -package versions - -import ( - "go/ast" - "go/types" -) - -// FileVersion returns a language version (<=1.21) derived from runtime.Version() -// or an unknown future version. -func FileVersion(info *types.Info, file *ast.File) string { - // In x/tools built with Go <= 1.21, we do not have Info.FileVersions - // available. We use a go version derived from the toolchain used to - // compile the tool by default. - // This will be <= go1.21. We take this as the maximum version that - // this tool can support. - // - // There are no features currently in x/tools that need to tell fine grained - // differences for versions <1.22. - return toolchain -} - -// InitFileVersions is a noop when compiled with this Go version. -func InitFileVersions(*types.Info) {} diff --git a/vendor/golang.org/x/tools/internal/versions/types_go122.go b/vendor/golang.org/x/tools/internal/versions/types_go122.go deleted file mode 100644 index aac5db62c9..0000000000 --- a/vendor/golang.org/x/tools/internal/versions/types_go122.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2023 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. - -//go:build go1.22 -// +build go1.22 - -package versions - -import ( - "go/ast" - "go/types" -) - -// FileVersion returns a file's Go version. -// The reported version is an unknown Future version if a -// version cannot be determined. -func FileVersion(info *types.Info, file *ast.File) string { - // In tools built with Go >= 1.22, the Go version of a file - // follow a cascades of sources: - // 1) types.Info.FileVersion, which follows the cascade: - // 1.a) file version (ast.File.GoVersion), - // 1.b) the package version (types.Config.GoVersion), or - // 2) is some unknown Future version. - // - // File versions require a valid package version to be provided to types - // in Config.GoVersion. Config.GoVersion is either from the package's module - // or the toolchain (go run). This value should be provided by go/packages - // or unitchecker.Config.GoVersion. - if v := info.FileVersions[file]; IsValid(v) { - return v - } - // Note: we could instead return runtime.Version() [if valid]. - // This would act as a max version on what a tool can support. - return Future -} - -// InitFileVersions initializes info to record Go versions for Go files. -func InitFileVersions(info *types.Info) { - info.FileVersions = make(map[*ast.File]string) -} diff --git a/vendor/modules.txt b/vendor/modules.txt index 0fa1170ecb..003f99eedf 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -26,7 +26,7 @@ github.com/Microsoft/go-winio/pkg/guid # github.com/aead/siphash v1.0.1 ## explicit github.com/aead/siphash -# github.com/bits-and-blooms/bitset v1.13.0 +# github.com/bits-and-blooms/bitset v1.17.0 ## explicit; go 1.16 github.com/bits-and-blooms/bitset # github.com/btcsuite/btcd v0.24.2 @@ -62,11 +62,11 @@ github.com/btcsuite/btcd/chaincfg/chainhash github.com/btcsuite/btclog # github.com/cespare/cp v1.1.1 ## explicit -# github.com/consensys/bavard v0.1.13 -## explicit; go 1.15 +# github.com/consensys/bavard v0.1.22 +## explicit; go 1.22 github.com/consensys/bavard -# github.com/consensys/gnark-crypto v0.13.0 -## explicit; go 1.19 +# github.com/consensys/gnark-crypto v0.14.0 +## explicit; go 1.22 github.com/consensys/gnark-crypto/ecc github.com/consensys/gnark-crypto/ecc/bls12-381 github.com/consensys/gnark-crypto/ecc/bls12-381/bandersnatch @@ -79,7 +79,7 @@ github.com/consensys/gnark-crypto/field/hash github.com/consensys/gnark-crypto/field/pool github.com/consensys/gnark-crypto/internal/generator/config github.com/consensys/gnark-crypto/internal/parallel -# github.com/crate-crypto/go-ipa v0.0.0-20240223125850-b1e8a79f509c +# github.com/crate-crypto/go-ipa v0.0.0-20240724233137-53bbb0ceb27a ## explicit; go 1.18 github.com/crate-crypto/go-ipa github.com/crate-crypto/go-ipa/bandersnatch @@ -112,8 +112,8 @@ github.com/decred/dcrd/dcrec/secp256k1/v4/schnorr # github.com/ethereum/c-kzg-4844 v1.0.3 ## explicit; go 1.19 github.com/ethereum/c-kzg-4844/bindings/go -# github.com/ethereum/go-ethereum v1.14.13 -## explicit; go 1.22 +# github.com/ethereum/go-ethereum v1.15.4 +## explicit; go 1.23.0 github.com/ethereum/go-ethereum github.com/ethereum/go-ethereum/accounts github.com/ethereum/go-ethereum/accounts/abi @@ -141,7 +141,7 @@ github.com/ethereum/go-ethereum/rlp github.com/ethereum/go-ethereum/rlp/internal/rlpstruct github.com/ethereum/go-ethereum/rpc github.com/ethereum/go-ethereum/signer/core/apitypes -# github.com/ethereum/go-verkle v0.1.1-0.20240829091221-dffa7562dbe9 +# github.com/ethereum/go-verkle v0.2.2 ## explicit; go 1.22 github.com/ethereum/go-verkle # github.com/flynn/noise v1.1.0 @@ -163,7 +163,7 @@ github.com/gorilla/mux # github.com/gorilla/websocket v1.5.3 ## explicit; go 1.12 github.com/gorilla/websocket -# github.com/holiman/uint256 v1.3.1 +# github.com/holiman/uint256 v1.3.2 ## explicit; go 1.19 github.com/holiman/uint256 # github.com/karalabe/hid v1.0.1-0.20240919124526-821c38d2678e @@ -236,7 +236,7 @@ github.com/stretchr/testify/assert/yaml github.com/stretchr/testify/mock github.com/stretchr/testify/require github.com/stretchr/testify/suite -# github.com/supranational/blst v0.3.13 +# github.com/supranational/blst v0.3.14 ## explicit; go 1.11 github.com/supranational/blst/bindings/go # github.com/tklauser/go-sysconf v0.3.14 @@ -266,7 +266,6 @@ golang.org/x/crypto/scrypt golang.org/x/crypto/sha3 # golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 ## explicit; go 1.20 -golang.org/x/exp/maps # golang.org/x/mobile v0.0.0-20240716161057-1ad2df20a8b6 ## explicit; go 1.18 golang.org/x/mobile/bind @@ -277,14 +276,14 @@ golang.org/x/mobile/internal/importers golang.org/x/mobile/internal/importers/java golang.org/x/mobile/internal/importers/objc golang.org/x/mobile/internal/mobileinit -# golang.org/x/mod v0.19.0 -## explicit; go 1.18 +# golang.org/x/mod v0.22.0 +## explicit; go 1.22.0 golang.org/x/mod/semver # golang.org/x/net v0.34.0 ## explicit; go 1.18 golang.org/x/net/internal/socks golang.org/x/net/proxy -# golang.org/x/sync v0.7.0 +# golang.org/x/sync v0.10.0 ## explicit; go 1.18 golang.org/x/sync/errgroup # golang.org/x/sys v0.29.0 @@ -292,11 +291,12 @@ golang.org/x/sync/errgroup golang.org/x/sys/cpu golang.org/x/sys/unix golang.org/x/sys/windows -# golang.org/x/tools v0.23.0 -## explicit; go 1.19 +# golang.org/x/tools v0.29.0 +## explicit; go 1.22.0 golang.org/x/tools/go/gcexportdata golang.org/x/tools/go/packages golang.org/x/tools/go/types/objectpath +golang.org/x/tools/go/types/typeutil golang.org/x/tools/internal/aliases golang.org/x/tools/internal/event golang.org/x/tools/internal/event/core @@ -307,7 +307,7 @@ golang.org/x/tools/internal/gocommand golang.org/x/tools/internal/packagesinternal golang.org/x/tools/internal/pkgbits golang.org/x/tools/internal/stdlib -golang.org/x/tools/internal/tokeninternal +golang.org/x/tools/internal/typeparams golang.org/x/tools/internal/typesinternal golang.org/x/tools/internal/versions # google.golang.org/protobuf v1.34.2