diff --git a/CHANGELOG-V2.md b/CHANGELOG-V2.md index db5a94c22..c82f5dc7c 100644 --- a/CHANGELOG-V2.md +++ b/CHANGELOG-V2.md @@ -3,6 +3,42 @@ This document tracks changes to Temporal and its related projects for all `v2.x.x` releases. See our [versioning policy](/VERSIONING.md) for more details. +## v2.0.4 + +* relevant PRs: + * [#305](https://github.com/RTradeLtd/Temporal/pull/305) + * [#306](https://github.com/RTradeLtd/Temporal/pull/306) + * [#307](https://github.com/RTradeLtd/Temporal/pull/307) + * [#308](https://github.com/RTradeLtd/Temporal/pull/308) + +### scripts + +* miscellaneus script cleanup +* add executable permissions to all scripts + +### configs + +* update zabbix monitoring template + * monitor all new services + * include graphs, and triggers for alerting + +### travis + +* fix personal access token for travis deployments + +### queue + +* fix key generation process + +### grpc clients + +* add client for kaas, and allow fallback mode + +### deps + +* general dependency update +* update [RTradeLtd/config](https://github.com/RTradeLtd/config) + ## v2.0.3 * api/v2: fix private network creation ([#304](https://github.com/RTradeLtd/Temporal/pull/304)) diff --git a/Gopkg.lock b/Gopkg.lock index 7baac00c7..cbdb6d47c 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -34,12 +34,12 @@ version = "v2.0.1" [[projects]] - digest = "1:d914e7b89490aab7ff3dafd9e79f6b431328803f5e25b59428d62531fa6c2ec0" + digest = "1:345cf7ecad29e982752447f3a23827f4eb84bda1595cea7d2ce358fa0db0ee2c" name = "github.com/RTradeLtd/config" packages = ["."] pruneopts = "UT" - revision = "c973c5b0c01ab295f86502599286dbee04a6f1d4" - version = "v2.0.0" + revision = "8a4af7437b526a027348bdbc2530f93bf5efd424" + version = "v2.0.2" [[projects]] digest = "1:8859d83d94d112382fbdd97fc04c2ce196ea044f271ffe8e170826b25131a4f0" @@ -50,7 +50,7 @@ version = "v2.0.0" [[projects]] - digest = "1:5c3fe898838beddd697991b6d0129b47531a13d80cd357a15d36ea004c9dfb0d" + digest = "1:fffe5651bfebceb2383a2ea0940e88d74b00a733c5e78fc9c6ceff25065911fc" name = "github.com/RTradeLtd/database" packages = [ ".", @@ -58,8 +58,8 @@ "utils", ] pruneopts = "UT" - revision = "d579a64da5da3ffd1729d2f2a707c83fc616f5fb" - version = "v2.0.2" + revision = "4b656032faa6d6859dc0e0c45203ac55bcda76e5" + version = "v2.0.3" [[projects]] branch = "master" @@ -130,18 +130,6 @@ revision = "ac1c6e92072ad9652c702d3d55d97ec938acff91" version = "v2.0.0" -[[projects]] - branch = "master" - digest = "1:4cf11742b199ab3aacf26b00187e72f7ff8ba2145f363b74f295d54f098f79e4" - name = "github.com/agl/ed25519" - packages = [ - ".", - "edwards25519", - "extra25519", - ] - pruneopts = "UT" - revision = "5312a61534124124185d41f09206b9fef1d88403" - [[projects]] digest = "1:a164e093eccfde4fb63dc94707f3570d112ff4549072a065a48813c37c0c76a9" name = "github.com/appleboy/gin-jwt" @@ -163,7 +151,7 @@ name = "github.com/btcsuite/btcd" packages = ["btcec"] pruneopts = "UT" - revision = "ed77733ec07dfc8a513741138419b8d9d3de9d2d" + revision = "306aecffea325e97f513b3ff0cf7895a5310651d" [[projects]] branch = "master" @@ -254,7 +242,7 @@ [[projects]] branch = "master" - digest = "1:8284c199bc9f5c75da71578c0c68481f465d075c4f2faf8fd2756eee0b4f2f6d" + digest = "1:f2df2de9ad26d31adfb64ea2b57ebf8834a7fef673032ecd4ea8e722e54161b9" name = "github.com/gin-gonic/gin" packages = [ ".", @@ -263,18 +251,18 @@ "render", ] pruneopts = "UT" - revision = "5acf6601170bb49a1958c055d66d54ba152dc34b" + revision = "31bbb10f34e4673815ab66099571bac95cf4113d" [[projects]] - digest = "1:db75c3971e4fcaa251e4726f132fab3b17ad90beb7829d90ade140533b577861" + digest = "1:760b2447d30444b6c2da7f77b677921f095fe19e6ed423b2edc1cd47a8507789" name = "github.com/gogo/protobuf" packages = [ "io", "proto", ] pruneopts = "UT" - revision = "4cbf7e384e768b4e01799441fdf2a706a5635ae7" - version = "v1.2.0" + revision = "ba06b47c162d49f2af050fb4c75bcbc86a159d5c" + version = "v1.2.1" [[projects]] branch = "master" @@ -342,19 +330,19 @@ [[projects]] branch = "master" - digest = "1:ae72f80e79008e24bcde7de64d9cf1dac2704533a621ba9afc5d5eb011403510" + digest = "1:3afdc56b02a78be62fd27008d22902a002cc30a6bf99baffdb8756160f2b87ce" name = "github.com/hsanjuan/go-libp2p-gostream" packages = ["."] pruneopts = "UT" - revision = "a644999a753d19a833611650865390b6da97c914" + revision = "27b5b1545d9e6c65d0dc64471885f161c825ade8" [[projects]] branch = "master" - digest = "1:11ad23f2c2d54e9a384c80c231c3f6d919d90845ed42c9cf87964a8790c05fa7" + digest = "1:5b71bf83a2bc08c390fa9aea003f9a1839e88aac83eb46af6bd469cf1d5d1ed4" name = "github.com/hsanjuan/go-libp2p-http" packages = ["."] pruneopts = "UT" - revision = "2a7d4fc2f66adb2bec60a3eb05e36d1379ede88b" + revision = "0bda6dc50529762a7556cfff6159ab947da4b5e4" [[projects]] digest = "1:c00cc6d95a674b4b923ac069d364445043bc67836e9bd8aeff8440cfbe6a2cc7" @@ -445,11 +433,11 @@ [[projects]] branch = "master" - digest = "1:9f355cab3caa2b4413f5b9638d313429b3d34513c0deb13ef41c22a075b48b25" + digest = "1:f0cee7fa25319760e00912c6fd16499d3d2d81e086865e9a79701d0ebe45788b" name = "github.com/ipfs/go-ipfs-files" packages = ["."] pruneopts = "UT" - revision = "267cdfe2e27a621acf3567cc072e5bf4ecf168ee" + revision = "b9ab5987284914bf7c73b9c450b2ae6777051a3d" [[projects]] digest = "1:aae82c244bd91107575a0244a29e82e34ba23e06b6892557e33728de48deba96" @@ -618,14 +606,14 @@ [[projects]] branch = "master" - digest = "1:181c737f32564a5ce23898a5d8957d13a89bf9ca2f562a853e2ce5521fb33c35" + digest = "1:8a4307cb902876329d37e7a414291b7cb7061224e837256eebcf6ceb7cef64ac" name = "github.com/libp2p/go-libp2p-autonat" packages = [ ".", "pb", ] pruneopts = "UT" - revision = "93b1787f76de807b9ab3a7c7edd45cf906139bdb" + revision = "842b9c4919f5be0df3baee15b0f97e493f6d3fb2" [[projects]] digest = "1:6f00253ed14e76cf0b0179ee83311d378388054b3fb3446b4607cab76f5b7297" @@ -639,23 +627,23 @@ version = "v2.3.2" [[projects]] - digest = "1:4ff86c6d6dd8df23a58e6b6060fea5f150d1a502cdfe8a3e9efd5d25339196c6" + digest = "1:43d92dca90cd6c7096383a0a8bf4b7af6cb0a8f97c44558a5bb2d386a626367d" name = "github.com/libp2p/go-libp2p-crypto" packages = [ ".", "pb", ] pruneopts = "UT" - revision = "274de1bb6c27780863df6b230c91324ab481dab2" - version = "v2.0.1" + revision = "a3075f70fa87dfd2b8dae2c80c6908bb3aa1bc77" + version = "v2.0.5" [[projects]] branch = "master" - digest = "1:a607dfc95b409c84567c32cbd742e466e5864e1f3839cd2fa366990984ad0412" + digest = "1:a8eeac3102118ab43ac13023da34002f615e66c18398a3e129d5a0ecc83bf2dc" name = "github.com/libp2p/go-libp2p-discovery" packages = ["."] pruneopts = "UT" - revision = "cc4105e21706452e5b0f7e05390f987017188d31" + revision = "d369eed95f2d5748d1fa5688d97b6ae162658e1a" [[projects]] digest = "1:de92515b23a5c4cd04893e67cd9af1dfff7a2a5337f95c36de273ecf757628e7" @@ -715,11 +703,11 @@ [[projects]] branch = "master" - digest = "1:1509a6790d5fd554e6ef866f282a953ea9a089eb8e1f2d0b59f9d1adceedd208" + digest = "1:762ccffe657ebf3d014c9c595cdc5a043a02f95123a1b917b9ad09e67e819652" name = "github.com/libp2p/go-libp2p-peer" packages = ["."] pruneopts = "UT" - revision = "f5c52cebf45bb99d2b871cec48dd3ad6e2edaa11" + revision = "9a193a66da547245154976338737b11eac2d583e" [[projects]] digest = "1:2063708efd5552590aeec525a47d0e9dcf981336c20af73f952fb8599ddc394d" @@ -837,11 +825,11 @@ [[projects]] branch = "master" - digest = "1:2059c93108811c310c58f104f5ec806398a35213a5db058913013bb31f11ff81" + digest = "1:fa535cf250af638fa3d857de9855af86abba1654c89c3fbece6b3735d6479ed7" name = "github.com/libp2p/go-reuseport-transport" packages = ["."] pruneopts = "UT" - revision = "98b2c72d32537d3e48ca636e63e180a5b06384a0" + revision = "7c623f705b2b7639b091d045d7ea1f973e24c5c0" [[projects]] digest = "1:6dab34eae15e82d15c17cedabb7d641b62731cc5c7a3ed233dba226f8e5cb688" @@ -1070,11 +1058,11 @@ [[projects]] branch = "master" - digest = "1:525ac3364813b4688df380594e562133e07830dfce0722effda64b37634c13d0" + digest = "1:dbd2b63224b02f9c7fd0631edaf6588dfb05fc20608f548fb603ef096fa87474" name = "github.com/streadway/amqp" packages = ["."] pruneopts = "UT" - revision = "a314942b2fd9dde7a3f70ba3f1062848ce6eb392" + revision = "884228600bc96c993ab12fb81ba78bf0c280e88a" [[projects]] digest = "1:4887e9e89c80299aa520d718239809fdd2a47a9aa394909b169959bfbc424ddf" @@ -1222,12 +1210,14 @@ [[projects]] branch = "master" - digest = "1:89405c62c196dd1b0da798c5f03b1a65dc9dc3b980548b52a8e79a3063cc11ca" + digest = "1:2b98b3cf89303123bc72c8caebbcf221ff2de97a307647db125ce1012e55bee9" name = "golang.org/x/crypto" packages = [ "bcrypt", "blake2s", "blowfish", + "ed25519", + "ed25519/internal/edwards25519", "internal/subtle", "pbkdf2", "salsa20", @@ -1235,11 +1225,11 @@ "sha3", ] pruneopts = "UT" - revision = "b8fe1690c61389d7d2a8074a507d1d40c5d30448" + revision = "74369b46fc6756741c016591724fd1cb8e26845f" [[projects]] branch = "master" - digest = "1:e4cb09624f31f9e33fce26702314da5a1383962d7e0861bfe39dfdc00a848fa3" + digest = "1:13d98d4a123176d59926946c44709a930054a7034d466cbbdbb92dd149790bcf" name = "golang.org/x/net" packages = [ "context", @@ -1254,11 +1244,11 @@ "trace", ] pruneopts = "UT" - revision = "d26f9f9a57f3fab6a695bec0d84433c2c50f8bbf" + revision = "3a22650c66bd7f4fb6d1e8072ffd7b75c8a27898" [[projects]] branch = "master" - digest = "1:8b38d0f580ac12385b9b7dc1a242441ff4d59a4889f20044f5c23cc47c2004bb" + digest = "1:a6fbffb15d4bd8fcd16b26a557ce78820815320618b34d9101c502b4769674a1" name = "golang.org/x/sys" packages = [ "cpu", @@ -1266,7 +1256,7 @@ "windows", ] pruneopts = "UT" - revision = "41f3e6584952bb034a481797859f6ab34b6803bd" + revision = "d0b11bdaac8adb652bff00e49bcacf992835621a" [[projects]] digest = "1:436b24586f8fee329e0dd65fd67c817681420cda1d7f934345c13fe78c212a73" @@ -1305,14 +1295,14 @@ [[projects]] branch = "master" - digest = "1:6c6b70cf6d2788d9f7dc6589bc88e0e1c7edc40612294431ebb7d09536d12240" + digest = "1:48cd63b152af9cc0010714d881a3d29a68c19a265fbb914d884dfde42fe9337a" name = "google.golang.org/genproto" packages = [ "googleapis/api/annotations", "googleapis/rpc/status", ] pruneopts = "UT" - revision = "4b09977fb92221987e99d190c8f88f2c92727a29" + revision = "bd968387e4aa590b3c6e4ba38ecac1ed314d43ad" [[projects]] digest = "1:9ab5a33d8cb5c120602a34d2e985ce17956a4e8c2edce7e6961568f95e40c09a" diff --git a/Makefile b/Makefile index 2d655f81d..6787570b8 100644 --- a/Makefile +++ b/Makefile @@ -107,8 +107,8 @@ vendor: # Nuke vendor directory rm -rf vendor - # Update standard dependencies - dep ensure -v -update + # rebuild dependencies + dep ensure -v $(DEPFLAGS) # Generate IPFS dependencies rm -rf vendor/github.com/ipfs/go-ipfs diff --git a/api/v2/api.go b/api/v2/api.go index e8798418b..f97044167 100644 --- a/api/v2/api.go +++ b/api/v2/api.go @@ -9,14 +9,14 @@ import ( "strconv" "time" + gClients "github.com/RTradeLtd/Temporal/grpc-clients" + "github.com/streadway/amqp" "github.com/RTradeLtd/Temporal/log" "github.com/RTradeLtd/Temporal/rtfscluster" "go.uber.org/zap" - "github.com/RTradeLtd/kaas" - "github.com/RTradeLtd/ChainRider-Go/dash" "github.com/RTradeLtd/Temporal/queue" "github.com/RTradeLtd/rtfs" @@ -46,7 +46,7 @@ var ( type API struct { ipfs rtfs.Manager ipfsCluster *rtfscluster.ClusterManager - keys *kaas.Client + keys keys r *gin.Engine cfg *config.TemporalConfig dbm *database.Manager @@ -169,7 +169,11 @@ func new(cfg *config.TemporalConfig, router *gin.Engine, l *zap.SugaredLogger, c Blockchain: networkVersion, Token: cfg.APIKeys.ChainRider, }) - keys, err := kaas.NewClient(cfg.Services) + kb1, err := gClients.NewKaasClient(cfg.Services, false) + if err != nil { + return nil, err + } + kb2, err := gClients.NewKaasClient(cfg.Services, true) if err != nil { return nil, err } @@ -218,7 +222,7 @@ func new(cfg *config.TemporalConfig, router *gin.Engine, l *zap.SugaredLogger, c return &API{ ipfs: ipfs, ipfsCluster: ipfsCluster, - keys: keys, + keys: keys{kb1: kb1, kb2: kb2}, cfg: cfg, service: "api", r: router, diff --git a/api/v2/routes_account.go b/api/v2/routes_account.go index 70d71c48c..0310d6101 100644 --- a/api/v2/routes_account.go +++ b/api/v2/routes_account.go @@ -212,7 +212,7 @@ func (api *API) createIPFSKey(c *gin.Context) { NetworkName: "public", } // send message for processing - if err = api.queues.key.PublishMessageWithExchange(key, queue.IpfsKeyExchange); err != nil { + if err = api.queues.key.PublishMessage(key); err != nil { api.LogError(c, err, eh.QueuePublishError)(http.StatusBadRequest) return } diff --git a/api/v2/routes_utils.go b/api/v2/routes_utils.go index 94c465e0e..42a87f264 100644 --- a/api/v2/routes_utils.go +++ b/api/v2/routes_utils.go @@ -122,7 +122,7 @@ func (api *API) exportKey(c *gin.Context) { return } // get private key from krab keystore - resp, err := api.keys.GetPrivateKey(context.Background(), &pb.KeyGet{Name: keyName}) + resp, err := api.keys.kb1.GetPrivateKey(context.Background(), &pb.KeyGet{Name: keyName}) if err != nil { api.LogError(c, err, eh.KeyExportError)(http.StatusBadRequest) return @@ -133,8 +133,16 @@ func (api *API) exportKey(c *gin.Context) { api.LogError(c, err, eh.KeyExportError)(http.StatusBadRequest) return } - // after successful parsing delete key from krab - if resp, err := api.keys.DeletePrivateKey(context.Background(), &pb.KeyDelete{Name: keyName}); err != nil { + // after successful parsing delete key from krab primary + if resp, err := api.keys.kb1.DeletePrivateKey(context.Background(), &pb.KeyDelete{Name: keyName}); err != nil { + api.LogError(c, err, "failed to delete key")(http.StatusBadRequest) + return + } else if resp.Status != "private key deleted" { + Fail(c, errors.New("failed to delete private key")) + return + } + // after successful parsing delete key from krab fallback + if resp, err := api.keys.kb2.DeletePrivateKey(context.Background(), &pb.KeyDelete{Name: keyName}); err != nil { api.LogError(c, err, "failed to delete key")(http.StatusBadRequest) return } else if resp.Status != "private key deleted" { diff --git a/api/v2/types.go b/api/v2/types.go index f761003b9..ea8e68c17 100644 --- a/api/v2/types.go +++ b/api/v2/types.go @@ -1,6 +1,7 @@ package v2 import ( + clients "github.com/RTradeLtd/Temporal/grpc-clients" "github.com/RTradeLtd/Temporal/queue" ) @@ -20,3 +21,9 @@ type queues struct { dash *queue.Manager eth *queue.Manager } + +// kaas key managers +type keys struct { + kb1 *clients.KaasClient + kb2 *clients.KaasClient +} diff --git a/grpc-clients/clients_test.go b/grpc-clients/clients_test.go index 2e3bbc658..519055116 100644 --- a/grpc-clients/clients_test.go +++ b/grpc-clients/clients_test.go @@ -3,7 +3,7 @@ package clients_test import ( "testing" - "github.com/RTradeLtd/Temporal/grpc-clients" + clients "github.com/RTradeLtd/Temporal/grpc-clients" "github.com/RTradeLtd/config" ) @@ -60,3 +60,34 @@ func TestOrchestratorClient_Pass(t *testing.T) { t.Fatal(err) } } + +func TestKaasClient_Pass(t *testing.T) { + cfg, err := config.LoadConfig(testCfgPath) + if err != nil { + t.Fatal(err) + } + // test non fallback + if _, err := clients.NewKaasClient(cfg.Services, false); err != nil { + t.Fatal(err) + } + if _, err := clients.NewKaasClient(cfg.Services, true); err != nil { + t.Fatal(err) + } +} + +func TestKaasClient_Fail(t *testing.T) { + cfg, err := config.LoadConfig(testCfgPath) + if err != nil { + t.Fatal(err) + } + cfg.Services.Krab.URL = "notarealurls" + cfg.Services.Krab.TLS.CertPath = "/root/toor" + cfg.Services.KrabFallback.URL = "notarealurls" + cfg.Services.KrabFallback.TLS.CertPath = "/root/toor" + if _, err := clients.NewKaasClient(cfg.Services, false); err == nil { + t.Fatal("expected error") + } + if _, err := clients.NewKaasClient(cfg.Services, true); err == nil { + t.Fatal("expected error") + } +} diff --git a/grpc-clients/kaas.go b/grpc-clients/kaas.go new file mode 100644 index 000000000..937ead2d6 --- /dev/null +++ b/grpc-clients/kaas.go @@ -0,0 +1,54 @@ +package clients + +import ( + "fmt" + + "github.com/RTradeLtd/config" + "github.com/RTradeLtd/grpc/dialer" + pb "github.com/RTradeLtd/grpc/krab" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials" +) + +// KaasClient is how we interface with the kaas grpc key manager +type KaasClient struct { + pb.ServiceClient + conn *grpc.ClientConn +} + +// NewKaasClient is used to instantiate our kaas client in primary or fallback mode +func NewKaasClient(opts config.Services, fallback bool) (*KaasClient, error) { + var ( + dialOpts []grpc.DialOption + krabConfig config.Krab + ) + if fallback { + krabConfig = opts.KrabFallback + } else { + krabConfig = opts.Krab + } + if krabConfig.TLS.CertPath != "" { + creds, err := credentials.NewClientTLSFromFile(krabConfig.TLS.CertPath, "") + if err != nil { + return nil, fmt.Errorf("could not load tls cert: %s", err) + } + dialOpts = append(dialOpts, + grpc.WithTransportCredentials(creds), + grpc.WithPerRPCCredentials(dialer.NewCredentials(krabConfig.AuthKey, true))) + } else { + dialOpts = append(dialOpts, + grpc.WithInsecure(), + grpc.WithPerRPCCredentials(dialer.NewCredentials(krabConfig.AuthKey, false))) + } + conn, err := grpc.Dial(krabConfig.URL, dialOpts...) + if err != nil { + return nil, err + } + return &KaasClient{ + conn: conn, + ServiceClient: pb.NewServiceClient(conn), + }, nil +} + +// Close shuts down the client's gRPC connection +func (kc *KaasClient) Close() error { return kc.conn.Close() } diff --git a/queue/exchanges.go b/queue/exchanges.go deleted file mode 100644 index f941058fc..000000000 --- a/queue/exchanges.go +++ /dev/null @@ -1,34 +0,0 @@ -package queue - -import "errors" - -const ( - // IpfsKeyExchange is the exchange topic used for key creation requests - IpfsKeyExchange = "ipfs-key-exchange" - // IpfsKeyExchangeKey is the exchange key used for key creation requests - IpfsKeyExchangeKey = "ipfs-key-exchange-key" -) - -// DeclareIPFSKeyExchange is used to declare the exchange used to handle ipfs key creation requests -func (qm *Manager) declareIPFSKeyExchange() error { - return qm.channel.ExchangeDeclare( - IpfsKeyExchange, // name - "fanout", // type - true, // durable - false, // auto-delete - false, // internal - false, // no wait - nil, // args - ) -} - -// SetupExchange is used to setup our various exchanges -func (qm *Manager) setupExchange(queueType Queue) error { - switch queueType { - case IpfsKeyCreationQueue: - qm.ExchangeName = IpfsKeyExchange - return qm.declareIPFSKeyExchange() - default: - return errors.New("invalid queue name for non default exchange") - } -} diff --git a/queue/ipfs.go b/queue/ipfs.go index f9f16f39b..57d01701c 100644 --- a/queue/ipfs.go +++ b/queue/ipfs.go @@ -9,8 +9,9 @@ import ( "sync" "time" + clients "github.com/RTradeLtd/Temporal/grpc-clients" + "github.com/RTradeLtd/Temporal/log" - "github.com/RTradeLtd/kaas" "github.com/RTradeLtd/rtfs" "github.com/RTradeLtd/database/models" @@ -24,7 +25,11 @@ import ( // ProcessIPFSKeyCreation is used to create IPFS keys func (qm *Manager) ProcessIPFSKeyCreation(ctx context.Context, wg *sync.WaitGroup, msgs <-chan amqp.Delivery) error { - kb, err := kaas.NewClient(qm.cfg.Services) + kbPrimary, err := clients.NewKaasClient(qm.cfg.Services, false) + if err != nil { + return err + } + kbBackup, err := clients.NewKaasClient(qm.cfg.Services, true) if err != nil { return err } @@ -34,7 +39,7 @@ func (qm *Manager) ProcessIPFSKeyCreation(ctx context.Context, wg *sync.WaitGrou select { case d := <-msgs: wg.Add(1) - go qm.processIPFSKeyCreation(d, wg, kb, userManager) + go qm.processIPFSKeyCreation(d, wg, kbPrimary, kbBackup, userManager) case <-ctx.Done(): qm.Close() wg.Done() @@ -190,7 +195,7 @@ func (qm *Manager) processIPFSPin(d amqp.Delivery, wg *sync.WaitGroup, usrm *mod return // we must return here in order to trigger the wg.Done() defer } -func (qm *Manager) processIPFSKeyCreation(d amqp.Delivery, wg *sync.WaitGroup, kb *kaas.Client, um *models.UserManager) { +func (qm *Manager) processIPFSKeyCreation(d amqp.Delivery, wg *sync.WaitGroup, kbPrimary *clients.KaasClient, kbBackup *clients.KaasClient, um *models.UserManager) { defer wg.Done() qm.l.Info("new key creation request detected") key := IPFSKeyCreation{} @@ -270,8 +275,8 @@ func (qm *Manager) processIPFSKeyCreation(d amqp.Delivery, wg *sync.WaitGroup, k return } - // store the key in krab - if _, err := kb.PutPrivateKey(context.Background(), &pb.KeyPut{Name: key.Name, PrivateKey: pkBytes}); err != nil { + // store the key in local krab + if _, err := kbPrimary.PutPrivateKey(context.Background(), &pb.KeyPut{Name: key.Name, PrivateKey: pkBytes}); err != nil { qm.l.Errorw( "failed to store key in krab", "error", err.Error(), @@ -280,6 +285,17 @@ func (qm *Manager) processIPFSKeyCreation(d amqp.Delivery, wg *sync.WaitGroup, k d.Ack(false) return } + // store the key in remote krab + if _, err := kbBackup.PutPrivateKey(context.Background(), &pb.KeyPut{Name: key.Name, PrivateKey: pkBytes}); err != nil { + qm.l.Errorw( + "failed to store key in krab", + "error", err.Error(), + "user", key.UserName, + "key_name", key.Name) + d.Ack(false) + return + } + // doesn't need a refund, key was generated and stored in our keystore, but information not saved to db if err := um.AddIPFSKeyForUser(key.UserName, key.Name, id.Pretty()); err != nil { qm.l.Errorw( diff --git a/queue/ipns.go b/queue/ipns.go index be444ff5f..f4b30bad1 100644 --- a/queue/ipns.go +++ b/queue/ipns.go @@ -12,10 +12,10 @@ import ( "github.com/streadway/amqp" + clients "github.com/RTradeLtd/Temporal/grpc-clients" "github.com/RTradeLtd/Temporal/rtns" "github.com/RTradeLtd/database/models" pb "github.com/RTradeLtd/grpc/krab" - "github.com/RTradeLtd/kaas" ) type contextKey string @@ -26,7 +26,7 @@ const ( // ProcessIPNSEntryCreationRequests is used to process IPNS entry creation requests func (qm *Manager) ProcessIPNSEntryCreationRequests(ctx context.Context, wg *sync.WaitGroup, msgs <-chan amqp.Delivery) error { - kb, err := kaas.NewClient(qm.cfg.Services) + kbPrimary, err := clients.NewKaasClient(qm.cfg.Services, false) if err != nil { return err } @@ -46,7 +46,7 @@ func (qm *Manager) ProcessIPNSEntryCreationRequests(ctx context.Context, wg *syn select { case d := <-msgs: wg.Add(1) - go qm.processIPNSEntryCreationRequest(d, wg, kb, publisher, ipnsManager) + go qm.processIPNSEntryCreationRequest(d, wg, kbPrimary, publisher, ipnsManager) case <-ctx.Done(): qm.Close() wg.Done() @@ -62,7 +62,7 @@ func (qm *Manager) ProcessIPNSEntryCreationRequests(ctx context.Context, wg *syn } } -func (qm *Manager) processIPNSEntryCreationRequest(d amqp.Delivery, wg *sync.WaitGroup, kb *kaas.Client, pub *rtns.Publisher, im *models.IpnsManager) { +func (qm *Manager) processIPNSEntryCreationRequest(d amqp.Delivery, wg *sync.WaitGroup, kb *clients.KaasClient, pub *rtns.Publisher, im *models.IpnsManager) { defer wg.Done() qm.l.Info("new ipns entry creation detected") ie := IPNSEntry{} diff --git a/queue/queue.go b/queue/queue.go index f7c1f66ec..77e63be35 100644 --- a/queue/queue.go +++ b/queue/queue.go @@ -7,10 +7,8 @@ import ( "encoding/json" "errors" "io/ioutil" - "os" "sync" - "github.com/RTradeLtd/Temporal/utils" "github.com/RTradeLtd/gorm" "go.uber.org/zap" @@ -18,19 +16,6 @@ import ( "github.com/streadway/amqp" ) -func (qm *Manager) parseQueueName(queue Queue) error { - host, err := os.Hostname() - if err != nil { - return err - } - // the following is to account for running multiple queue workers - // on a single host. - rand := utils.GenerateRandomUtils() - s := rand.GenerateString(5, utils.LetterBytes) - qm.QueueName = queue + Queue(host+s) - return nil -} - // New is used to instantiate a new connection to rabbitmq as a publisher or consumer func New(queue Queue, url string, publish bool, cfg *config.TemporalConfig, logger *zap.SugaredLogger) (*Manager, error) { conn, err := setupConnection(url, cfg) @@ -49,18 +34,6 @@ func New(queue Queue, url string, publish bool, cfg *config.TemporalConfig, logg if err := qm.openChannel(); err != nil { return nil, err } - // Declare Non Default exchanges for matching queues - switch queue { - case IpfsKeyCreationQueue: - // as this is an exchange based queue we need a unique queue name - if err := qm.parseQueueName(queue); err != nil { - return nil, err - } - // setup the actual exchange - if err = qm.setupExchange(queue); err != nil { - return nil, err - } - } // if we aren't publishing, and are consuming // setup a queue to receive messages on if !publish { @@ -143,27 +116,6 @@ func (qm *Manager) ConsumeMessages(ctx context.Context, wg *sync.WaitGroup, db * qm.db = db // embed config into queue manager qm.cfg = cfg - // if we are using an exchange, we form a relationship between a queue and an exchange - // this process is known as binding, and allows consumers to receive messages sent to an exchange - // We are primarily doing this to allow for multiple consumers, to receive the same message - // For example using the IpfsKeyExchange, this will setup message distribution such that - // a single key creation request, will be sent to all of our consumers ensuring that all of our nodes - // will have the same key in their keystore - switch qm.ExchangeName { - case IpfsKeyExchange: - if err := qm.channel.QueueBind( - qm.QueueName.String(), // name of the queue - "", // routing key - qm.ExchangeName, // exchange - false, // noWait - nil, // arguments - ); err != nil { - return err - } - default: - break - } - // we do not auto-ack, as if a consumer dies we don't want the message to be lost // not specifying the consumer name uses an automatically generated id msgs, err := qm.channel.Consume( @@ -179,13 +131,10 @@ func (qm *Manager) ConsumeMessages(ctx context.Context, wg *sync.WaitGroup, db * return err } - // exchange need special handling - switch qm.ExchangeName { - case IpfsKeyExchange: - return qm.ProcessIPFSKeyCreation(ctx, wg, msgs) - } // check the queue name switch qm.QueueName { + case IpfsKeyCreationQueue: + return qm.ProcessIPFSKeyCreation(ctx, wg, msgs) case IpfsPinQueue: return qm.ProccessIPFSPins(ctx, wg, msgs) case EmailSendQueue: @@ -199,34 +148,6 @@ func (qm *Manager) ConsumeMessages(ctx context.Context, wg *sync.WaitGroup, db * } } -//PublishMessageWithExchange is used to publish a message to a given exchange -func (qm *Manager) PublishMessageWithExchange(body interface{}, exchangeName string) error { - switch exchangeName { - case IpfsKeyExchange: - break - default: - return errors.New("invalid exchange name provided") - } - bodyMarshaled, err := json.Marshal(body) - if err != nil { - return err - } - if err = qm.channel.Publish( - exchangeName, // exchange - this determines which exchange will receive the message - "", // routing key - false, // mandatory - false, // immediate - amqp.Publishing{ - DeliveryMode: amqp.Persistent, // messages will persist through crashes, etc.. - ContentType: "text/plain", - Body: bodyMarshaled, - }, - ); err != nil { - return err - } - return nil -} - // PublishMessage is used to produce messages that are sent to the queue, with a worker queue (one consumer) func (qm *Manager) PublishMessage(body interface{}) error { bodyMarshaled, err := json.Marshal(body) diff --git a/queue/queue_test.go b/queue/queue_test.go index 9d46deb0d..1321ee799 100644 --- a/queue/queue_test.go +++ b/queue/queue_test.go @@ -2,8 +2,6 @@ package queue import ( "context" - "os" - "strings" "sync" "testing" "time" @@ -24,42 +22,6 @@ const ( testCfgPath = "../testenv/config.json" ) -func TestParseQueueName(t *testing.T) { - qm := Manager{} - if err := qm.parseQueueName(IpfsKeyCreationQueue); err != nil { - t.Fatal(err) - } - host, err := os.Hostname() - if err != nil { - t.Fatal(err) - } - if ok := strings.Contains(qm.QueueName.String(), host); !ok { - t.Fatal("failed to properly parse queue name") - } -} - -func TestParseQueueFull(t *testing.T) { - cfg, err := config.LoadConfig(testCfgPath) - if err != nil { - t.Fatal(err) - } - loggerConsumer, err := log.NewLogger("", true) - if err != nil { - t.Fatal(err) - } - qmConsumer, err := New(IpfsKeyCreationQueue, testRabbitAddress, false, cfg, loggerConsumer) - if err != nil { - t.Fatal(err) - } - host, err := os.Hostname() - if err != nil { - t.Fatal(err) - } - if ok := strings.Contains(qmConsumer.QueueName.String(), host); !ok { - t.Fatal("failed to properly parse queue name") - } -} - func TestQueue_Publish(t *testing.T) { type args struct { queueName Queue @@ -121,25 +83,6 @@ func TestQueue_Publish(t *testing.T) { } } -// Covers the default case in `setupExchange` -func TestQueue_ExchangeFail(t *testing.T) { - logger, err := log.NewLogger("", true) - if err != nil { - t.Fatal(err) - } - cfg, err := config.LoadConfig(testCfgPath) - if err != nil { - t.Fatal(err) - } - qmPublisher, err := New(IpfsPinQueue, testRabbitAddress, true, cfg, logger) - if err != nil { - t.Fatal(err) - } - if err = qmPublisher.setupExchange("bad-queue"); err == nil { - t.Fatal("error expected") - } -} - func TestRegisterChannelClosure(t *testing.T) { logger, err := log.NewLogger("", true) if err != nil { @@ -566,39 +509,33 @@ func TestQueue_IPFSKeyCreation(t *testing.T) { if err != nil { t.Fatal(err) } - if qmConsumer.ExchangeName != IpfsKeyExchange { - t.Fatal("failed to properly set exchange name on consumer") - } qmPublisher, err := New(IpfsKeyCreationQueue, testRabbitAddress, true, cfg, loggerPublisher) if err != nil { t.Fatal(err) } - if qmPublisher.ExchangeName != IpfsKeyExchange { - t.Fatal("failed to properly set exchange name on publisher") - } defer func() { if err := qmPublisher.Close(); err != nil { t.Error(err) } }() // test a normal publish - if err := qmPublisher.PublishMessageWithExchange(IPFSKeyCreation{ + if err := qmPublisher.PublishMessage(IPFSKeyCreation{ UserName: "testuser", Name: "testuser-mykey", Type: "rsa", Size: 2048, NetworkName: "public", - CreditCost: 0}, IpfsKeyExchange, + CreditCost: 0}, ); err != nil { t.Fatal(err) } - if err := qmPublisher.PublishMessageWithExchange(IPFSKeyCreation{ + if err := qmPublisher.PublishMessage(IPFSKeyCreation{ UserName: "testuser", Name: "mykey", Type: "rsa", Size: 2048, NetworkName: "public", - CreditCost: 0}, IpfsKeyExchange, + CreditCost: 0}, ); err != nil { t.Fatal(err) } @@ -638,28 +575,22 @@ func TestQueue_IPFSKeyCreation_Failure(t *testing.T) { if err != nil { t.Fatal(err) } - if qmConsumer.ExchangeName != IpfsKeyExchange { - t.Fatal("failed to properly set exchange name on consumer") - } qmPublisher, err := New(IpfsKeyCreationQueue, testRabbitAddress, true, cfg, loggerPublisher) if err != nil { t.Fatal(err) } - if qmPublisher.ExchangeName != IpfsKeyExchange { - t.Fatal("failed to properly set exchange name on publisher") - } defer func() { if err := qmPublisher.Close(); err != nil { t.Error(err) } }() - if err := qmPublisher.PublishMessageWithExchange(IPFSKeyCreation{ + if err := qmPublisher.PublishMessage(IPFSKeyCreation{ UserName: "testuser", Name: "mykey", Type: "rsa", Size: 2048, NetworkName: "public", - CreditCost: 0}, IpfsKeyExchange, + CreditCost: 0}, ); err != nil { t.Fatal(err) } diff --git a/testenv b/testenv index 647da574e..f5a83c0a1 160000 --- a/testenv +++ b/testenv @@ -1 +1 @@ -Subproject commit 647da574e26c82b8701bf4206fc3b95195de3fc7 +Subproject commit f5a83c0a1c9bf302c8a899517363d0d494c6973e diff --git a/vendor/github.com/RTradeLtd/config/types.go b/vendor/github.com/RTradeLtd/config/types.go index 1abb6012f..632b9c304 100644 --- a/vendor/github.com/RTradeLtd/config/types.go +++ b/vendor/github.com/RTradeLtd/config/types.go @@ -157,18 +157,26 @@ type Services struct { User string `json:"user"` Pass string `json:"pass"` } `json:"raven"` - Krab struct { - URL string `json:"url"` - TLS struct { - CertPath string `json:"cert_path"` - KeyFile string `json:"key_file"` - } - AuthKey string `json:"auth_key"` - LogFile string `json:"log_file"` - KeystorePassword string `json:"keystore_password"` - } `json:"krab"` + Krab `json:"krab"` + KrabFallback Krab `json:"krab_fallback"` +} + +// Krab is used to for key management +type Krab struct { + URL string `json:"url"` + TLS struct { + CertPath string `json:"cert_path"` + KeyFile string `json:"key_file"` + } + AuthKey string `json:"auth_key"` + LogFile string `json:"log_file"` + KeystorePassword string `json:"keystore_password"` } +// KrabFallback is a fallback configuration for +// connecting to a secondary krab server +type KrabFallback Krab + // Lens defines options for the Lens search engine type Lens struct { URL string `json:"url"` diff --git a/vendor/github.com/RTradeLtd/database/models/upload.go b/vendor/github.com/RTradeLtd/database/models/upload.go index 4bbdc418f..9b2d816d7 100644 --- a/vendor/github.com/RTradeLtd/database/models/upload.go +++ b/vendor/github.com/RTradeLtd/database/models/upload.go @@ -157,3 +157,15 @@ func (um *UploadManager) GetUploadsForUser(username string) ([]Upload, error) { } return uploads, nil } + +// ExtendGarbageCollectionPeriod is used to extend the garbage collection period for a particular upload +func (um *UploadManager) ExtendGarbageCollectionPeriod(username, hash, network string, holdTimeInMonths int) error { + upload, err := um.FindUploadByHashAndUserAndNetwork(username, hash, network) + if err != nil { + return err + } + // update garbage collection period + upload.GarbageCollectDate = upload.GarbageCollectDate.AddDate(0, holdTimeInMonths, 0) + // save the updated model + return um.DB.Model(upload).Update("garbage_collect_date", upload.GarbageCollectDate).Error +} diff --git a/vendor/github.com/RTradeLtd/database/models/user.go b/vendor/github.com/RTradeLtd/database/models/user.go index bca46afee..5ea9e8a52 100644 --- a/vendor/github.com/RTradeLtd/database/models/user.go +++ b/vendor/github.com/RTradeLtd/database/models/user.go @@ -10,6 +10,11 @@ import ( "golang.org/x/crypto/bcrypt" ) +var ( + // EmptyCustomerObjectHash is an empty customer object published to ipfs + EmptyCustomerObjectHash = "zdpuAnUGSDoNQoHQ2jpjhPePHEvg26mYLsAAGxr4jkzCWUpde" +) + // User is our user model for anyone who signs up with Temporal type User struct { gorm.Model @@ -22,6 +27,7 @@ type User struct { HashedPassword string `gorm:"type:varchar(255)"` Free bool `gorm:"type:boolean"` Credits float64 `gorm:"type:float;default:0"` + CustomerObjectHash string `gorm:"type:varchar(255)"` // IPFSKeyNames is an array of IPFS key name this user has created IPFSKeyNames pq.StringArray `gorm:"type:text[];column:ipfs_key_names"` // IPFSKeyIDs is an array of public key hashes for IPFS keys this user has created @@ -250,12 +256,13 @@ func (um *UserManager) NewUserAccount(username, password, email string) (*User, return nil, err } user = &User{ - UserName: username, - HashedPassword: hex.EncodeToString(hashedPass), - EmailAddress: email, - AccountEnabled: true, - AdminAccess: false, - Free: true, + UserName: username, + HashedPassword: hex.EncodeToString(hashedPass), + EmailAddress: email, + AccountEnabled: true, + AdminAccess: false, + Free: true, + CustomerObjectHash: EmptyCustomerObjectHash, } // create user model if check := um.DB.Create(user); check.Error != nil { @@ -433,3 +440,22 @@ func (um *UserManager) ToggleAdmin(username string) (bool, error) { } return true, nil } + +// GetCustomerObjectHash is used to retrieve the object hash of a customer +func (um *UserManager) GetCustomerObjectHash(username string) (string, error) { + user, err := um.FindByUserName(username) + if err != nil { + return "", err + } + return user.CustomerObjectHash, nil +} + +// UpdateCustomerObjectHash is used to update the customer object hash associated with the user +func (um *UserManager) UpdateCustomerObjectHash(username, newHash string) error { + user, err := um.FindByUserName(username) + if err != nil { + return err + } + user.CustomerObjectHash = newHash + return um.DB.Model(user).Update("customer_object_hash", newHash).Error +} diff --git a/vendor/github.com/RTradeLtd/database/utils/time.go b/vendor/github.com/RTradeLtd/database/utils/time.go index 0b5d76db5..9502e0429 100644 --- a/vendor/github.com/RTradeLtd/database/utils/time.go +++ b/vendor/github.com/RTradeLtd/database/utils/time.go @@ -9,5 +9,5 @@ Time related functionality // CalculateGarbageCollectDate is used to calculate the date at which a file // will be removed from our inventory. To prepare data for input use `strconv.Atoi(fmt.Sprintf("%v", .....")"` func CalculateGarbageCollectDate(holdTimeInMonths int) time.Time { - return time.Now().AddDate(0, holdTimeInMonths, 0) + return time.Now().UTC().AddDate(0, holdTimeInMonths, 0) } diff --git a/vendor/github.com/agl/ed25519/LICENSE b/vendor/github.com/agl/ed25519/LICENSE deleted file mode 100644 index 744875676..000000000 --- a/vendor/github.com/agl/ed25519/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2012 The Go Authors. All rights reserved. - -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 Inc. 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/github.com/agl/ed25519/ed25519.go b/vendor/github.com/agl/ed25519/ed25519.go deleted file mode 100644 index e5f873f52..000000000 --- a/vendor/github.com/agl/ed25519/ed25519.go +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright 2013 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 ed25519 implements the Ed25519 signature algorithm. See -// http://ed25519.cr.yp.to/. -package ed25519 - -// This code is a port of the public domain, "ref10" implementation of ed25519 -// from SUPERCOP. - -import ( - "crypto/sha512" - "crypto/subtle" - "io" - - "github.com/agl/ed25519/edwards25519" -) - -const ( - PublicKeySize = 32 - PrivateKeySize = 64 - SignatureSize = 64 -) - -// GenerateKey generates a public/private key pair using randomness from rand. -func GenerateKey(rand io.Reader) (publicKey *[PublicKeySize]byte, privateKey *[PrivateKeySize]byte, err error) { - privateKey = new([64]byte) - publicKey = new([32]byte) - _, err = io.ReadFull(rand, privateKey[:32]) - if err != nil { - return nil, nil, err - } - - h := sha512.New() - h.Write(privateKey[:32]) - digest := h.Sum(nil) - - digest[0] &= 248 - digest[31] &= 127 - digest[31] |= 64 - - var A edwards25519.ExtendedGroupElement - var hBytes [32]byte - copy(hBytes[:], digest) - edwards25519.GeScalarMultBase(&A, &hBytes) - A.ToBytes(publicKey) - - copy(privateKey[32:], publicKey[:]) - return -} - -// Sign signs the message with privateKey and returns a signature. -func Sign(privateKey *[PrivateKeySize]byte, message []byte) *[SignatureSize]byte { - h := sha512.New() - h.Write(privateKey[:32]) - - var digest1, messageDigest, hramDigest [64]byte - var expandedSecretKey [32]byte - h.Sum(digest1[:0]) - copy(expandedSecretKey[:], digest1[:]) - expandedSecretKey[0] &= 248 - expandedSecretKey[31] &= 63 - expandedSecretKey[31] |= 64 - - h.Reset() - h.Write(digest1[32:]) - h.Write(message) - h.Sum(messageDigest[:0]) - - var messageDigestReduced [32]byte - edwards25519.ScReduce(&messageDigestReduced, &messageDigest) - var R edwards25519.ExtendedGroupElement - edwards25519.GeScalarMultBase(&R, &messageDigestReduced) - - var encodedR [32]byte - R.ToBytes(&encodedR) - - h.Reset() - h.Write(encodedR[:]) - h.Write(privateKey[32:]) - h.Write(message) - h.Sum(hramDigest[:0]) - var hramDigestReduced [32]byte - edwards25519.ScReduce(&hramDigestReduced, &hramDigest) - - var s [32]byte - edwards25519.ScMulAdd(&s, &hramDigestReduced, &expandedSecretKey, &messageDigestReduced) - - signature := new([64]byte) - copy(signature[:], encodedR[:]) - copy(signature[32:], s[:]) - return signature -} - -// Verify returns true iff sig is a valid signature of message by publicKey. -func Verify(publicKey *[PublicKeySize]byte, message []byte, sig *[SignatureSize]byte) bool { - if sig[63]&224 != 0 { - return false - } - - var A edwards25519.ExtendedGroupElement - if !A.FromBytes(publicKey) { - return false - } - edwards25519.FeNeg(&A.X, &A.X) - edwards25519.FeNeg(&A.T, &A.T) - - h := sha512.New() - h.Write(sig[:32]) - h.Write(publicKey[:]) - h.Write(message) - var digest [64]byte - h.Sum(digest[:0]) - - var hReduced [32]byte - edwards25519.ScReduce(&hReduced, &digest) - - var R edwards25519.ProjectiveGroupElement - var b [32]byte - copy(b[:], sig[32:]) - edwards25519.GeDoubleScalarMultVartime(&R, &hReduced, &A, &b) - - var checkR [32]byte - R.ToBytes(&checkR) - return subtle.ConstantTimeCompare(sig[:32], checkR[:]) == 1 -} diff --git a/vendor/github.com/agl/ed25519/extra25519/extra25519.go b/vendor/github.com/agl/ed25519/extra25519/extra25519.go deleted file mode 100644 index b897ba538..000000000 --- a/vendor/github.com/agl/ed25519/extra25519/extra25519.go +++ /dev/null @@ -1,340 +0,0 @@ -// Copyright 2013 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 extra25519 - -import ( - "crypto/sha512" - - "github.com/agl/ed25519/edwards25519" -) - -// PrivateKeyToCurve25519 converts an ed25519 private key into a corresponding -// curve25519 private key such that the resulting curve25519 public key will -// equal the result from PublicKeyToCurve25519. -func PrivateKeyToCurve25519(curve25519Private *[32]byte, privateKey *[64]byte) { - h := sha512.New() - h.Write(privateKey[:32]) - digest := h.Sum(nil) - - digest[0] &= 248 - digest[31] &= 127 - digest[31] |= 64 - - copy(curve25519Private[:], digest) -} - -func edwardsToMontgomeryX(outX, y *edwards25519.FieldElement) { - // We only need the x-coordinate of the curve25519 point, which I'll - // call u. The isomorphism is u=(y+1)/(1-y), since y=Y/Z, this gives - // u=(Y+Z)/(Z-Y). We know that Z=1, thus u=(Y+1)/(1-Y). - var oneMinusY edwards25519.FieldElement - edwards25519.FeOne(&oneMinusY) - edwards25519.FeSub(&oneMinusY, &oneMinusY, y) - edwards25519.FeInvert(&oneMinusY, &oneMinusY) - - edwards25519.FeOne(outX) - edwards25519.FeAdd(outX, outX, y) - - edwards25519.FeMul(outX, outX, &oneMinusY) -} - -// PublicKeyToCurve25519 converts an Ed25519 public key into the curve25519 -// public key that would be generated from the same private key. -func PublicKeyToCurve25519(curve25519Public *[32]byte, publicKey *[32]byte) bool { - var A edwards25519.ExtendedGroupElement - if !A.FromBytes(publicKey) { - return false - } - - // A.Z = 1 as a postcondition of FromBytes. - var x edwards25519.FieldElement - edwardsToMontgomeryX(&x, &A.Y) - edwards25519.FeToBytes(curve25519Public, &x) - return true -} - -// sqrtMinusAPlus2 is sqrt(-(486662+2)) -var sqrtMinusAPlus2 = edwards25519.FieldElement{ - -12222970, -8312128, -11511410, 9067497, -15300785, -241793, 25456130, 14121551, -12187136, 3972024, -} - -// sqrtMinusHalf is sqrt(-1/2) -var sqrtMinusHalf = edwards25519.FieldElement{ - -17256545, 3971863, 28865457, -1750208, 27359696, -16640980, 12573105, 1002827, -163343, 11073975, -} - -// halfQMinus1Bytes is (2^255-20)/2 expressed in little endian form. -var halfQMinus1Bytes = [32]byte{ - 0xf6, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, -} - -// feBytesLess returns one if a <= b and zero otherwise. -func feBytesLE(a, b *[32]byte) int32 { - equalSoFar := int32(-1) - greater := int32(0) - - for i := uint(31); i < 32; i-- { - x := int32(a[i]) - y := int32(b[i]) - - greater = (^equalSoFar & greater) | (equalSoFar & ((x - y) >> 31)) - equalSoFar = equalSoFar & (((x ^ y) - 1) >> 31) - } - - return int32(^equalSoFar & 1 & greater) -} - -// ScalarBaseMult computes a curve25519 public key from a private key and also -// a uniform representative for that public key. Note that this function will -// fail and return false for about half of private keys. -// See http://elligator.cr.yp.to/elligator-20130828.pdf. -func ScalarBaseMult(publicKey, representative, privateKey *[32]byte) bool { - var maskedPrivateKey [32]byte - copy(maskedPrivateKey[:], privateKey[:]) - - maskedPrivateKey[0] &= 248 - maskedPrivateKey[31] &= 127 - maskedPrivateKey[31] |= 64 - - var A edwards25519.ExtendedGroupElement - edwards25519.GeScalarMultBase(&A, &maskedPrivateKey) - - var inv1 edwards25519.FieldElement - edwards25519.FeSub(&inv1, &A.Z, &A.Y) - edwards25519.FeMul(&inv1, &inv1, &A.X) - edwards25519.FeInvert(&inv1, &inv1) - - var t0, u edwards25519.FieldElement - edwards25519.FeMul(&u, &inv1, &A.X) - edwards25519.FeAdd(&t0, &A.Y, &A.Z) - edwards25519.FeMul(&u, &u, &t0) - - var v edwards25519.FieldElement - edwards25519.FeMul(&v, &t0, &inv1) - edwards25519.FeMul(&v, &v, &A.Z) - edwards25519.FeMul(&v, &v, &sqrtMinusAPlus2) - - var b edwards25519.FieldElement - edwards25519.FeAdd(&b, &u, &edwards25519.A) - - var c, b3, b7, b8 edwards25519.FieldElement - edwards25519.FeSquare(&b3, &b) // 2 - edwards25519.FeMul(&b3, &b3, &b) // 3 - edwards25519.FeSquare(&c, &b3) // 6 - edwards25519.FeMul(&b7, &c, &b) // 7 - edwards25519.FeMul(&b8, &b7, &b) // 8 - edwards25519.FeMul(&c, &b7, &u) - q58(&c, &c) - - var chi edwards25519.FieldElement - edwards25519.FeSquare(&chi, &c) - edwards25519.FeSquare(&chi, &chi) - - edwards25519.FeSquare(&t0, &u) - edwards25519.FeMul(&chi, &chi, &t0) - - edwards25519.FeSquare(&t0, &b7) // 14 - edwards25519.FeMul(&chi, &chi, &t0) - edwards25519.FeNeg(&chi, &chi) - - var chiBytes [32]byte - edwards25519.FeToBytes(&chiBytes, &chi) - // chi[1] is either 0 or 0xff - if chiBytes[1] == 0xff { - return false - } - - // Calculate r1 = sqrt(-u/(2*(u+A))) - var r1 edwards25519.FieldElement - edwards25519.FeMul(&r1, &c, &u) - edwards25519.FeMul(&r1, &r1, &b3) - edwards25519.FeMul(&r1, &r1, &sqrtMinusHalf) - - var maybeSqrtM1 edwards25519.FieldElement - edwards25519.FeSquare(&t0, &r1) - edwards25519.FeMul(&t0, &t0, &b) - edwards25519.FeAdd(&t0, &t0, &t0) - edwards25519.FeAdd(&t0, &t0, &u) - - edwards25519.FeOne(&maybeSqrtM1) - edwards25519.FeCMove(&maybeSqrtM1, &edwards25519.SqrtM1, edwards25519.FeIsNonZero(&t0)) - edwards25519.FeMul(&r1, &r1, &maybeSqrtM1) - - // Calculate r = sqrt(-(u+A)/(2u)) - var r edwards25519.FieldElement - edwards25519.FeSquare(&t0, &c) // 2 - edwards25519.FeMul(&t0, &t0, &c) // 3 - edwards25519.FeSquare(&t0, &t0) // 6 - edwards25519.FeMul(&r, &t0, &c) // 7 - - edwards25519.FeSquare(&t0, &u) // 2 - edwards25519.FeMul(&t0, &t0, &u) // 3 - edwards25519.FeMul(&r, &r, &t0) - - edwards25519.FeSquare(&t0, &b8) // 16 - edwards25519.FeMul(&t0, &t0, &b8) // 24 - edwards25519.FeMul(&t0, &t0, &b) // 25 - edwards25519.FeMul(&r, &r, &t0) - edwards25519.FeMul(&r, &r, &sqrtMinusHalf) - - edwards25519.FeSquare(&t0, &r) - edwards25519.FeMul(&t0, &t0, &u) - edwards25519.FeAdd(&t0, &t0, &t0) - edwards25519.FeAdd(&t0, &t0, &b) - edwards25519.FeOne(&maybeSqrtM1) - edwards25519.FeCMove(&maybeSqrtM1, &edwards25519.SqrtM1, edwards25519.FeIsNonZero(&t0)) - edwards25519.FeMul(&r, &r, &maybeSqrtM1) - - var vBytes [32]byte - edwards25519.FeToBytes(&vBytes, &v) - vInSquareRootImage := feBytesLE(&vBytes, &halfQMinus1Bytes) - edwards25519.FeCMove(&r, &r1, vInSquareRootImage) - - edwards25519.FeToBytes(publicKey, &u) - edwards25519.FeToBytes(representative, &r) - return true -} - -// q58 calculates out = z^((p-5)/8). -func q58(out, z *edwards25519.FieldElement) { - var t1, t2, t3 edwards25519.FieldElement - var i int - - edwards25519.FeSquare(&t1, z) // 2^1 - edwards25519.FeMul(&t1, &t1, z) // 2^1 + 2^0 - edwards25519.FeSquare(&t1, &t1) // 2^2 + 2^1 - edwards25519.FeSquare(&t2, &t1) // 2^3 + 2^2 - edwards25519.FeSquare(&t2, &t2) // 2^4 + 2^3 - edwards25519.FeMul(&t2, &t2, &t1) // 4,3,2,1 - edwards25519.FeMul(&t1, &t2, z) // 4..0 - edwards25519.FeSquare(&t2, &t1) // 5..1 - for i = 1; i < 5; i++ { // 9,8,7,6,5 - edwards25519.FeSquare(&t2, &t2) - } - edwards25519.FeMul(&t1, &t2, &t1) // 9,8,7,6,5,4,3,2,1,0 - edwards25519.FeSquare(&t2, &t1) // 10..1 - for i = 1; i < 10; i++ { // 19..10 - edwards25519.FeSquare(&t2, &t2) - } - edwards25519.FeMul(&t2, &t2, &t1) // 19..0 - edwards25519.FeSquare(&t3, &t2) // 20..1 - for i = 1; i < 20; i++ { // 39..20 - edwards25519.FeSquare(&t3, &t3) - } - edwards25519.FeMul(&t2, &t3, &t2) // 39..0 - edwards25519.FeSquare(&t2, &t2) // 40..1 - for i = 1; i < 10; i++ { // 49..10 - edwards25519.FeSquare(&t2, &t2) - } - edwards25519.FeMul(&t1, &t2, &t1) // 49..0 - edwards25519.FeSquare(&t2, &t1) // 50..1 - for i = 1; i < 50; i++ { // 99..50 - edwards25519.FeSquare(&t2, &t2) - } - edwards25519.FeMul(&t2, &t2, &t1) // 99..0 - edwards25519.FeSquare(&t3, &t2) // 100..1 - for i = 1; i < 100; i++ { // 199..100 - edwards25519.FeSquare(&t3, &t3) - } - edwards25519.FeMul(&t2, &t3, &t2) // 199..0 - edwards25519.FeSquare(&t2, &t2) // 200..1 - for i = 1; i < 50; i++ { // 249..50 - edwards25519.FeSquare(&t2, &t2) - } - edwards25519.FeMul(&t1, &t2, &t1) // 249..0 - edwards25519.FeSquare(&t1, &t1) // 250..1 - edwards25519.FeSquare(&t1, &t1) // 251..2 - edwards25519.FeMul(out, &t1, z) // 251..2,0 -} - -// chi calculates out = z^((p-1)/2). The result is either 1, 0, or -1 depending -// on whether z is a non-zero square, zero, or a non-square. -func chi(out, z *edwards25519.FieldElement) { - var t0, t1, t2, t3 edwards25519.FieldElement - var i int - - edwards25519.FeSquare(&t0, z) // 2^1 - edwards25519.FeMul(&t1, &t0, z) // 2^1 + 2^0 - edwards25519.FeSquare(&t0, &t1) // 2^2 + 2^1 - edwards25519.FeSquare(&t2, &t0) // 2^3 + 2^2 - edwards25519.FeSquare(&t2, &t2) // 4,3 - edwards25519.FeMul(&t2, &t2, &t0) // 4,3,2,1 - edwards25519.FeMul(&t1, &t2, z) // 4..0 - edwards25519.FeSquare(&t2, &t1) // 5..1 - for i = 1; i < 5; i++ { // 9,8,7,6,5 - edwards25519.FeSquare(&t2, &t2) - } - edwards25519.FeMul(&t1, &t2, &t1) // 9,8,7,6,5,4,3,2,1,0 - edwards25519.FeSquare(&t2, &t1) // 10..1 - for i = 1; i < 10; i++ { // 19..10 - edwards25519.FeSquare(&t2, &t2) - } - edwards25519.FeMul(&t2, &t2, &t1) // 19..0 - edwards25519.FeSquare(&t3, &t2) // 20..1 - for i = 1; i < 20; i++ { // 39..20 - edwards25519.FeSquare(&t3, &t3) - } - edwards25519.FeMul(&t2, &t3, &t2) // 39..0 - edwards25519.FeSquare(&t2, &t2) // 40..1 - for i = 1; i < 10; i++ { // 49..10 - edwards25519.FeSquare(&t2, &t2) - } - edwards25519.FeMul(&t1, &t2, &t1) // 49..0 - edwards25519.FeSquare(&t2, &t1) // 50..1 - for i = 1; i < 50; i++ { // 99..50 - edwards25519.FeSquare(&t2, &t2) - } - edwards25519.FeMul(&t2, &t2, &t1) // 99..0 - edwards25519.FeSquare(&t3, &t2) // 100..1 - for i = 1; i < 100; i++ { // 199..100 - edwards25519.FeSquare(&t3, &t3) - } - edwards25519.FeMul(&t2, &t3, &t2) // 199..0 - edwards25519.FeSquare(&t2, &t2) // 200..1 - for i = 1; i < 50; i++ { // 249..50 - edwards25519.FeSquare(&t2, &t2) - } - edwards25519.FeMul(&t1, &t2, &t1) // 249..0 - edwards25519.FeSquare(&t1, &t1) // 250..1 - for i = 1; i < 4; i++ { // 253..4 - edwards25519.FeSquare(&t1, &t1) - } - edwards25519.FeMul(out, &t1, &t0) // 253..4,2,1 -} - -// RepresentativeToPublicKey converts a uniform representative value for a -// curve25519 public key, as produced by ScalarBaseMult, to a curve25519 public -// key. -func RepresentativeToPublicKey(publicKey, representative *[32]byte) { - var rr2, v, e edwards25519.FieldElement - edwards25519.FeFromBytes(&rr2, representative) - - edwards25519.FeSquare2(&rr2, &rr2) - rr2[0]++ - edwards25519.FeInvert(&rr2, &rr2) - edwards25519.FeMul(&v, &edwards25519.A, &rr2) - edwards25519.FeNeg(&v, &v) - - var v2, v3 edwards25519.FieldElement - edwards25519.FeSquare(&v2, &v) - edwards25519.FeMul(&v3, &v, &v2) - edwards25519.FeAdd(&e, &v3, &v) - edwards25519.FeMul(&v2, &v2, &edwards25519.A) - edwards25519.FeAdd(&e, &v2, &e) - chi(&e, &e) - var eBytes [32]byte - edwards25519.FeToBytes(&eBytes, &e) - // eBytes[1] is either 0 (for e = 1) or 0xff (for e = -1) - eIsMinus1 := int32(eBytes[1]) & 1 - var negV edwards25519.FieldElement - edwards25519.FeNeg(&negV, &v) - edwards25519.FeCMove(&v, &negV, eIsMinus1) - - edwards25519.FeZero(&v2) - edwards25519.FeCMove(&v2, &edwards25519.A, eIsMinus1) - edwards25519.FeSub(&v, &v, &v2) - - edwards25519.FeToBytes(publicKey, &v) -} diff --git a/vendor/github.com/gin-gonic/gin/gin.go b/vendor/github.com/gin-gonic/gin/gin.go index cd47200f1..6e5ea6d79 100644 --- a/vendor/github.com/gin-gonic/gin/gin.go +++ b/vendor/github.com/gin-gonic/gin/gin.go @@ -355,8 +355,11 @@ func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) { // This can be done by setting c.Request.URL.Path to your new target. // Disclaimer: You can loop yourself to death with this, use wisely. func (engine *Engine) HandleContext(c *Context) { + oldIndexValue := c.index c.reset() engine.handleHTTPRequest(c) + + c.index = oldIndexValue } func (engine *Engine) handleHTTPRequest(c *Context) { diff --git a/vendor/github.com/gogo/protobuf/proto/decode.go b/vendor/github.com/gogo/protobuf/proto/decode.go index d9aa3c42d..63b0f08be 100644 --- a/vendor/github.com/gogo/protobuf/proto/decode.go +++ b/vendor/github.com/gogo/protobuf/proto/decode.go @@ -186,7 +186,6 @@ func (p *Buffer) DecodeVarint() (x uint64, err error) { if b&0x80 == 0 { goto done } - // x -= 0x80 << 63 // Always zero. return 0, errOverflow diff --git a/vendor/github.com/gogo/protobuf/proto/deprecated.go b/vendor/github.com/gogo/protobuf/proto/deprecated.go new file mode 100644 index 000000000..35b882c09 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/deprecated.go @@ -0,0 +1,63 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2018 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// 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 Inc. 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. + +package proto + +import "errors" + +// Deprecated: do not use. +type Stats struct{ Emalloc, Dmalloc, Encode, Decode, Chit, Cmiss, Size uint64 } + +// Deprecated: do not use. +func GetStats() Stats { return Stats{} } + +// Deprecated: do not use. +func MarshalMessageSet(interface{}) ([]byte, error) { + return nil, errors.New("proto: not implemented") +} + +// Deprecated: do not use. +func UnmarshalMessageSet([]byte, interface{}) error { + return errors.New("proto: not implemented") +} + +// Deprecated: do not use. +func MarshalMessageSetJSON(interface{}) ([]byte, error) { + return nil, errors.New("proto: not implemented") +} + +// Deprecated: do not use. +func UnmarshalMessageSetJSON([]byte, interface{}) error { + return errors.New("proto: not implemented") +} + +// Deprecated: do not use. +func RegisterMessageSetType(Message, int32, string) {} diff --git a/vendor/github.com/gogo/protobuf/proto/extensions.go b/vendor/github.com/gogo/protobuf/proto/extensions.go index 44ebd457c..686bd2a09 100644 --- a/vendor/github.com/gogo/protobuf/proto/extensions.go +++ b/vendor/github.com/gogo/protobuf/proto/extensions.go @@ -544,7 +544,7 @@ func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error } typ := reflect.TypeOf(extension.ExtensionType) if typ != reflect.TypeOf(value) { - return errors.New("proto: bad extension value type") + return fmt.Errorf("proto: bad extension value type. got: %T, want: %T", value, extension.ExtensionType) } // nil extension values need to be caught early, because the // encoder can't distinguish an ErrNil due to a nil extension diff --git a/vendor/github.com/gogo/protobuf/proto/lib.go b/vendor/github.com/gogo/protobuf/proto/lib.go index b2271d0b7..d17f80209 100644 --- a/vendor/github.com/gogo/protobuf/proto/lib.go +++ b/vendor/github.com/gogo/protobuf/proto/lib.go @@ -341,26 +341,6 @@ type Message interface { ProtoMessage() } -// Stats records allocation details about the protocol buffer encoders -// and decoders. Useful for tuning the library itself. -type Stats struct { - Emalloc uint64 // mallocs in encode - Dmalloc uint64 // mallocs in decode - Encode uint64 // number of encodes - Decode uint64 // number of decodes - Chit uint64 // number of cache hits - Cmiss uint64 // number of cache misses - Size uint64 // number of sizes -} - -// Set to true to enable stats collection. -const collectStats = false - -var stats Stats - -// GetStats returns a copy of the global Stats structure. -func GetStats() Stats { return stats } - // A Buffer is a buffer manager for marshaling and unmarshaling // protocol buffers. It may be reused between invocations to // reduce memory usage. It is not necessary to use a Buffer; diff --git a/vendor/github.com/gogo/protobuf/proto/message_set.go b/vendor/github.com/gogo/protobuf/proto/message_set.go index 3b6ca41d5..f48a75676 100644 --- a/vendor/github.com/gogo/protobuf/proto/message_set.go +++ b/vendor/github.com/gogo/protobuf/proto/message_set.go @@ -36,13 +36,7 @@ package proto */ import ( - "bytes" - "encoding/json" "errors" - "fmt" - "reflect" - "sort" - "sync" ) // errNoMessageTypeID occurs when a protocol buffer does not have a message type ID. @@ -145,46 +139,9 @@ func skipVarint(buf []byte) []byte { return buf[i+1:] } -// MarshalMessageSet encodes the extension map represented by m in the message set wire format. -// It is called by generated Marshal methods on protocol buffer messages with the message_set_wire_format option. -func MarshalMessageSet(exts interface{}) ([]byte, error) { - return marshalMessageSet(exts, false) -} - -// marshaMessageSet implements above function, with the opt to turn on / off deterministic during Marshal. -func marshalMessageSet(exts interface{}, deterministic bool) ([]byte, error) { - switch exts := exts.(type) { - case *XXX_InternalExtensions: - var u marshalInfo - siz := u.sizeMessageSet(exts) - b := make([]byte, 0, siz) - return u.appendMessageSet(b, exts, deterministic) - - case map[int32]Extension: - // This is an old-style extension map. - // Wrap it in a new-style XXX_InternalExtensions. - ie := XXX_InternalExtensions{ - p: &struct { - mu sync.Mutex - extensionMap map[int32]Extension - }{ - extensionMap: exts, - }, - } - - var u marshalInfo - siz := u.sizeMessageSet(&ie) - b := make([]byte, 0, siz) - return u.appendMessageSet(b, &ie, deterministic) - - default: - return nil, errors.New("proto: not an extension map") - } -} - -// UnmarshalMessageSet decodes the extension map encoded in buf in the message set wire format. +// unmarshalMessageSet decodes the extension map encoded in buf in the message set wire format. // It is called by Unmarshal methods on protocol buffer messages with the message_set_wire_format option. -func UnmarshalMessageSet(buf []byte, exts interface{}) error { +func unmarshalMessageSet(buf []byte, exts interface{}) error { var m map[int32]Extension switch exts := exts.(type) { case *XXX_InternalExtensions: @@ -222,93 +179,3 @@ func UnmarshalMessageSet(buf []byte, exts interface{}) error { } return nil } - -// MarshalMessageSetJSON encodes the extension map represented by m in JSON format. -// It is called by generated MarshalJSON methods on protocol buffer messages with the message_set_wire_format option. -func MarshalMessageSetJSON(exts interface{}) ([]byte, error) { - var m map[int32]Extension - switch exts := exts.(type) { - case *XXX_InternalExtensions: - var mu sync.Locker - m, mu = exts.extensionsRead() - if m != nil { - // Keep the extensions map locked until we're done marshaling to prevent - // races between marshaling and unmarshaling the lazily-{en,de}coded - // values. - mu.Lock() - defer mu.Unlock() - } - case map[int32]Extension: - m = exts - default: - return nil, errors.New("proto: not an extension map") - } - var b bytes.Buffer - b.WriteByte('{') - - // Process the map in key order for deterministic output. - ids := make([]int32, 0, len(m)) - for id := range m { - ids = append(ids, id) - } - sort.Sort(int32Slice(ids)) // int32Slice defined in text.go - - for i, id := range ids { - ext := m[id] - msd, ok := messageSetMap[id] - if !ok { - // Unknown type; we can't render it, so skip it. - continue - } - - if i > 0 && b.Len() > 1 { - b.WriteByte(',') - } - - fmt.Fprintf(&b, `"[%s]":`, msd.name) - - x := ext.value - if x == nil { - x = reflect.New(msd.t.Elem()).Interface() - if err := Unmarshal(ext.enc, x.(Message)); err != nil { - return nil, err - } - } - d, err := json.Marshal(x) - if err != nil { - return nil, err - } - b.Write(d) - } - b.WriteByte('}') - return b.Bytes(), nil -} - -// UnmarshalMessageSetJSON decodes the extension map encoded in buf in JSON format. -// It is called by generated UnmarshalJSON methods on protocol buffer messages with the message_set_wire_format option. -func UnmarshalMessageSetJSON(buf []byte, exts interface{}) error { - // Common-case fast path. - if len(buf) == 0 || bytes.Equal(buf, []byte("{}")) { - return nil - } - - // This is fairly tricky, and it's not clear that it is needed. - return errors.New("TODO: UnmarshalMessageSetJSON not yet implemented") -} - -// A global registry of types that can be used in a MessageSet. - -var messageSetMap = make(map[int32]messageSetDesc) - -type messageSetDesc struct { - t reflect.Type // pointer to struct - name string -} - -// RegisterMessageSetType is called from the generated code. -func RegisterMessageSetType(m Message, fieldNum int32, name string) { - messageSetMap[fieldNum] = messageSetDesc{ - t: reflect.TypeOf(m), - name: name, - } -} diff --git a/vendor/github.com/gogo/protobuf/proto/properties.go b/vendor/github.com/gogo/protobuf/proto/properties.go index 04dcb8d9e..c9e5fa020 100644 --- a/vendor/github.com/gogo/protobuf/proto/properties.go +++ b/vendor/github.com/gogo/protobuf/proto/properties.go @@ -391,9 +391,6 @@ func GetProperties(t reflect.Type) *StructProperties { sprop, ok := propertiesMap[t] propertiesMu.RUnlock() if ok { - if collectStats { - stats.Chit++ - } return sprop } @@ -406,14 +403,8 @@ func GetProperties(t reflect.Type) *StructProperties { // getPropertiesLocked requires that propertiesMu is held. func getPropertiesLocked(t reflect.Type) *StructProperties { if prop, ok := propertiesMap[t]; ok { - if collectStats { - stats.Chit++ - } return prop } - if collectStats { - stats.Cmiss++ - } prop := new(StructProperties) // in case of recursive protos, fill this in now. diff --git a/vendor/github.com/gogo/protobuf/proto/table_marshal.go b/vendor/github.com/gogo/protobuf/proto/table_marshal.go index ba58c49a4..9b1538d05 100644 --- a/vendor/github.com/gogo/protobuf/proto/table_marshal.go +++ b/vendor/github.com/gogo/protobuf/proto/table_marshal.go @@ -491,7 +491,7 @@ func (fi *marshalFieldInfo) computeMarshalFieldInfo(f *reflect.StructField) { func (fi *marshalFieldInfo) computeOneofFieldInfo(f *reflect.StructField, oneofImplementers []interface{}) { fi.field = toField(f) - fi.wiretag = 1<<31 - 1 // Use a large tag number, make oneofs sorted at the end. This tag will not appear on the wire. + fi.wiretag = math.MaxInt32 // Use a large tag number, make oneofs sorted at the end. This tag will not appear on the wire. fi.isPointer = true fi.sizer, fi.marshaler = makeOneOfMarshaler(fi, f) fi.oneofElems = make(map[reflect.Type]*marshalElemInfo) diff --git a/vendor/github.com/gogo/protobuf/proto/table_unmarshal.go b/vendor/github.com/gogo/protobuf/proto/table_unmarshal.go index e6b15c76c..bb2622f28 100644 --- a/vendor/github.com/gogo/protobuf/proto/table_unmarshal.go +++ b/vendor/github.com/gogo/protobuf/proto/table_unmarshal.go @@ -138,7 +138,7 @@ func (u *unmarshalInfo) unmarshal(m pointer, b []byte) error { u.computeUnmarshalInfo() } if u.isMessageSet { - return UnmarshalMessageSet(b, m.offset(u.extensions).toExtensions()) + return unmarshalMessageSet(b, m.offset(u.extensions).toExtensions()) } var reqMask uint64 // bitmask of required fields we've seen. var errLater error @@ -2142,7 +2142,7 @@ func encodeVarint(b []byte, x uint64) []byte { // If there is an error, it returns 0,0. func decodeVarint(b []byte) (uint64, int) { var x, y uint64 - if len(b) <= 0 { + if len(b) == 0 { goto bad } x = uint64(b[0]) diff --git a/vendor/github.com/hsanjuan/go-libp2p-gostream/package.json b/vendor/github.com/hsanjuan/go-libp2p-gostream/package.json index e16f38201..d2e376769 100644 --- a/vendor/github.com/hsanjuan/go-libp2p-gostream/package.json +++ b/vendor/github.com/hsanjuan/go-libp2p-gostream/package.json @@ -9,9 +9,9 @@ "gxDependencies": [ { "author": "whyrusleeping", - "hash": "QmYxivS34F2M2n44WQQnRHGAKS8aoRUxwGpi9wk4Cdn4Jf", + "hash": "QmebEmt23jQxrwnqBkFL4qbpE8EnnQunpv5U32LS5ESus1", "name": "go-libp2p", - "version": "6.0.30" + "version": "6.0.33" } ], "gxVersion": "0.10.0", @@ -19,6 +19,6 @@ "license": "MIT", "name": "go-libp2p-gostream", "releaseCmd": "git commit -a -m \"gx publish $VERSION\"", - "version": "0.0.22" + "version": "0.0.24" } diff --git a/vendor/github.com/hsanjuan/go-libp2p-http/package.json b/vendor/github.com/hsanjuan/go-libp2p-http/package.json index 67de89198..59015afe7 100644 --- a/vendor/github.com/hsanjuan/go-libp2p-http/package.json +++ b/vendor/github.com/hsanjuan/go-libp2p-http/package.json @@ -9,15 +9,15 @@ "gxDependencies": [ { "author": "whyrusleeping", - "hash": "QmYxivS34F2M2n44WQQnRHGAKS8aoRUxwGpi9wk4Cdn4Jf", + "hash": "QmebEmt23jQxrwnqBkFL4qbpE8EnnQunpv5U32LS5ESus1", "name": "go-libp2p", - "version": "6.0.30" + "version": "6.0.33" }, { "author": "hsanjuan", - "hash": "Qmd68MCJjKqg6DUeTjcPxmT8rZT2DgsvtiRuJUJ6uy3wUb", + "hash": "QmQdGrgaHjwQC4B7oNWh7HZh9vNvisUvgPbNU69ggu2Zg8", "name": "go-libp2p-gostream", - "version": "0.0.22" + "version": "0.0.24" } ], "gxVersion": "0.10.0", @@ -25,6 +25,6 @@ "license": "MIT", "name": "go-libp2p-http", "releaseCmd": "git commit -a -m \"gx publish $VERSION\"", - "version": "1.1.10" + "version": "1.1.12" } diff --git a/vendor/github.com/ipfs/go-ipfs-files/multipartfile.go b/vendor/github.com/ipfs/go-ipfs-files/multipartfile.go index b083e7049..17681653f 100644 --- a/vendor/github.com/ipfs/go-ipfs-files/multipartfile.go +++ b/vendor/github.com/ipfs/go-ipfs-files/multipartfile.go @@ -1,7 +1,6 @@ package files import ( - "errors" "io" "io/ioutil" "mime" @@ -22,94 +21,134 @@ const ( contentTypeHeader = "Content-Type" ) -var ErrPartOutsideParent = errors.New("file outside parent dir") -var ErrPartInChildTree = errors.New("file in child tree") +type multipartDirectory struct { + path string + walker *multipartWalker -// multipartFile implements Node, and is created from a `multipart.Part`. -type multipartFile struct { - Node + // part is the part describing the directory. It's nil when implicit. + part *multipart.Part +} - part *multipart.Part - reader *peekReader - mediatype string +type multipartWalker struct { + part *multipart.Part + reader *multipart.Reader } -func NewFileFromPartReader(reader *multipart.Reader, mediatype string) (Directory, error) { - if !isDirectory(mediatype) { - return nil, ErrNotDirectory - } +func (m *multipartWalker) consumePart() { + m.part = nil +} - f := &multipartFile{ - reader: &peekReader{r: reader}, - mediatype: mediatype, +func (m *multipartWalker) getPart() (*multipart.Part, error) { + if m.part != nil { + return m.part, nil + } + if m.reader == nil { + return nil, io.EOF } - return f, nil + var err error + m.part, err = m.reader.NextPart() + if err == io.EOF { + m.reader = nil + } + return m.part, err } -func newFileFromPart(parent string, part *multipart.Part, reader *peekReader) (string, Node, error) { - f := &multipartFile{ - part: part, - reader: reader, +func NewFileFromPartReader(reader *multipart.Reader, mediatype string) (Directory, error) { + if !isDirectory(mediatype) { + return nil, ErrNotDirectory } - dir, base := path.Split(f.fileName()) - dir = path.Clean(dir) - parent = path.Clean(parent) - if dir == "." { - dir = "" - } - if parent == "." { - parent = "" - } + return &multipartDirectory{ + path: "/", + walker: &multipartWalker{ + reader: reader, + }, + }, nil +} - if dir != parent { - if strings.HasPrefix(dir, parent) { - return "", nil, ErrPartInChildTree - } - return "", nil, ErrPartOutsideParent +func (w *multipartWalker) nextFile() (Node, error) { + part, err := w.getPart() + if err != nil { + return nil, err } + w.consumePart() contentType := part.Header.Get(contentTypeHeader) switch contentType { case applicationSymlink: out, err := ioutil.ReadAll(part) if err != nil { - return "", nil, err + return nil, err } - return base, NewLinkFile(string(out), nil), nil + return NewLinkFile(string(out), nil), nil case "": // default to application/octet-stream fallthrough case applicationFile: - return base, &ReaderFile{ + return &ReaderFile{ reader: part, abspath: part.Header.Get("abspath"), }, nil } - var err error - f.mediatype, _, err = mime.ParseMediaType(contentType) + mediatype, _, err := mime.ParseMediaType(contentType) if err != nil { - return "", nil, err + return nil, err } - if !isDirectory(f.mediatype) { - return base, &ReaderFile{ + if !isDirectory(mediatype) { + return &ReaderFile{ reader: part, abspath: part.Header.Get("abspath"), }, nil } - return base, f, nil + return &multipartDirectory{ + part: part, + path: fileName(part), + walker: w, + }, nil +} + +// fileName returns a normalized filename from a part. +func fileName(part *multipart.Part) string { + filename := part.FileName() + if escaped, err := url.QueryUnescape(filename); err == nil { + filename = escaped + } // if there is a unescape error, just treat the name as unescaped + + return path.Clean("/" + filename) +} + +// dirName appends a slash to the end of the filename, if not present. +// expects a _cleaned_ path. +func dirName(filename string) string { + if !strings.HasSuffix(filename, "/") { + filename += "/" + } + return filename } +// isDirectory checks if the media type is a valid directory media type. func isDirectory(mediatype string) bool { return mediatype == multipartFormdataType || mediatype == applicationDirectory } +// isChild checks if child is a child of parent directory. +// expects a _cleaned_ path. +func isChild(child, parent string) bool { + return strings.HasPrefix(child, dirName(parent)) +} + +// makeRelative makes the child path relative to the parent path. +// expects a _cleaned_ path. +func makeRelative(child, parent string) string { + return strings.TrimPrefix(child, dirName(parent)) +} + type multipartIterator struct { - f *multipartFile + f *multipartDirectory curFile Node curName string @@ -125,102 +164,73 @@ func (it *multipartIterator) Node() Node { } func (it *multipartIterator) Next() bool { - if it.f.reader == nil { + if it.f.walker.reader == nil || it.err != nil { return false } var part *multipart.Part for { - var err error - part, err = it.f.reader.NextPart() - if err != nil { - if err == io.EOF { - return false - } - it.err = err + part, it.err = it.f.walker.getPart() + if it.err != nil { return false } - name, cf, err := newFileFromPart(it.f.fileName(), part, it.f.reader) - if err == ErrPartOutsideParent { - break + name := fileName(part) + + // Is the file in a different directory? + if !isChild(name, it.f.path) { + return false } - if err != ErrPartInChildTree { - it.curFile = cf - it.curName = name - it.err = err - return err == nil + + // Have we already entered this directory? + if it.curName != "" && isChild(name, path.Join(it.f.path, it.curName)) { + it.f.walker.consumePart() + continue } - } - it.err = it.f.reader.put(part) - return false + // Make the path relative to the current directory. + name = makeRelative(name, it.f.path) + + // Check if we need to create a fake directory (more than one + // path component). + if idx := strings.IndexByte(name, '/'); idx >= 0 { + it.curName = name[:idx] + it.curFile = &multipartDirectory{ + path: path.Join(it.f.path, it.curName), + walker: it.f.walker, + } + return true + } + it.curName = name + + // Finally, advance to the next file. + it.curFile, it.err = it.f.walker.nextFile() + + return it.err == nil + } } func (it *multipartIterator) Err() error { + // We use EOF to signal that this iterator is done. That way, we don't + // need to check every time `Next` is called. + if it.err == io.EOF { + return nil + } return it.err } -func (f *multipartFile) Entries() DirIterator { +func (f *multipartDirectory) Entries() DirIterator { return &multipartIterator{f: f} } -func (f *multipartFile) fileName() string { - if f == nil || f.part == nil { - return "" - } - - filename, err := url.QueryUnescape(f.part.FileName()) - if err != nil { - // if there is a unescape error, just treat the name as unescaped - return f.part.FileName() - } - return filename -} - -func (f *multipartFile) Close() error { +func (f *multipartDirectory) Close() error { if f.part != nil { return f.part.Close() } return nil } -func (f *multipartFile) Size() (int64, error) { +func (f *multipartDirectory) Size() (int64, error) { return 0, ErrNotSupported } -type PartReader interface { - NextPart() (*multipart.Part, error) -} - -type peekReader struct { - r PartReader - next *multipart.Part -} - -func (pr *peekReader) NextPart() (*multipart.Part, error) { - if pr.next != nil { - p := pr.next - pr.next = nil - return p, nil - } - - if pr.r == nil { - return nil, io.EOF - } - - p, err := pr.r.NextPart() - if err == io.EOF { - pr.r = nil - } - return p, err -} - -func (pr *peekReader) put(p *multipart.Part) error { - if pr.next != nil { - return errors.New("cannot put multiple parts") - } - pr.next = p - return nil -} - -var _ Directory = &multipartFile{} +var _ Directory = &multipartDirectory{} diff --git a/vendor/github.com/ipfs/go-ipfs-files/package.json b/vendor/github.com/ipfs/go-ipfs-files/package.json index ef8a73dba..07fdc7a65 100644 --- a/vendor/github.com/ipfs/go-ipfs-files/package.json +++ b/vendor/github.com/ipfs/go-ipfs-files/package.json @@ -19,6 +19,6 @@ "license": "", "name": "go-ipfs-files", "releaseCmd": "git commit -a -m \"gx publish $VERSION\"", - "version": "2.0.4" + "version": "2.0.6" } diff --git a/vendor/github.com/libp2p/go-libp2p-autonat/package.json b/vendor/github.com/libp2p/go-libp2p-autonat/package.json index cc0af4f74..bbf132f2d 100644 --- a/vendor/github.com/libp2p/go-libp2p-autonat/package.json +++ b/vendor/github.com/libp2p/go-libp2p-autonat/package.json @@ -7,50 +7,50 @@ "gxDependencies": [ { "author": "whyrusleeping", - "hash": "QmaoXrM4Z41PD48JY36YqQGKQpLGjyLA2cKcLsES7YddAq", + "hash": "Qmd52WKRSwrBK5gUaJKawryZQ5by6UbNB8KVW2Zy6JtbyW", "name": "go-libp2p-host", - "version": "3.0.21" + "version": "3.0.24" }, { "author": "whyrusleeping", - "hash": "QmNgLg1NTw37iWbYPKcyK85YJ9Whs1MkPtJwhfqbNYAyKg", + "hash": "QmTGxDz2CjBucFzPNTiWwzQmTWdrBnzqbqrMucDYMsjuPb", "name": "go-libp2p-net", - "version": "3.0.22" + "version": "3.0.28" }, { "author": "whyrusleeping", - "hash": "QmY5Grm8pJdiSSVsYxx4uNRgweY72EmYwuSDbRnbFok3iY", + "hash": "QmTu65MVbemtUxJEWgsTtzv9Zv9P8rvmqNA4eG9TrTRGYc", "name": "go-libp2p-peer", - "version": "3.0.0" + "version": "3.1.1" }, { "author": "whyrusleeping", - "hash": "QmPiemjiKBC9VA7vZF82m4x1oygtg2c2YVqag8PX7dN1BD", + "hash": "QmRhFARzTHcFh8wUxwN5KvyTGq73FLC65EfFAhz8Ng7aGb", "name": "go-libp2p-peerstore", - "version": "2.0.13" + "version": "2.0.17" }, { - "hash": "QmcuXC5cxs79ro2cUuHs4HQ2bkDLJUYokwL8aivcX6HW3C", + "hash": "QmbkT7eMTyXfpeyB3ZMxxcxg7XH8t6uXp49jqzz4HB7BGF", "name": "go-log", - "version": "1.5.8" + "version": "1.5.9" }, { "author": "whyrusleeping", - "hash": "QmQLbY1oKd4eHrikizXXwYkxn6yujUNSUMimv3UCaWTSWX", + "hash": "QmSka7Ax3a1HhyGaC3mqqrWbDhHsTmyzvED4Xk6dfvPXbY", "name": "go-libp2p-blankhost", - "version": "0.3.21" + "version": "0.3.24" }, { "author": "whyrusleeping", - "hash": "QmegQFxhr1J6yZ1vDQuDmJi5jntmj6BL96S11HVtXNCaHb", + "hash": "QmU7iTrsNaJfu1Rf5DrvaJLH9wJtQwmP4Dj8oPduprAU68", "name": "go-libp2p-swarm", - "version": "3.0.28" + "version": "3.0.31" }, { "author": "whyrusleeping", - "hash": "QmdxUuburamoF6zF9qjeQC4WYcWGbWuRmdLacMEsW8ioD8", + "hash": "QmddjPSGZb3ieihSseFeCfVRpZzcqczPNsD2DvarSwnjJB", "name": "gogo-protobuf", - "version": "0.0.0" + "version": "1.2.1" }, { "author": "multiformats", @@ -64,6 +64,6 @@ "license": "", "name": "go-libp2p-autonat", "releaseCmd": "git commit -a -m \"gx publish $VERSION\"", - "version": "1.0.5" + "version": "1.0.9" } diff --git a/vendor/github.com/libp2p/go-libp2p-autonat/pb/Makefile b/vendor/github.com/libp2p/go-libp2p-autonat/pb/Makefile new file mode 100644 index 000000000..dd21e878f --- /dev/null +++ b/vendor/github.com/libp2p/go-libp2p-autonat/pb/Makefile @@ -0,0 +1,6 @@ +pbgos := $(patsubst %.proto,%.pb.go,$(wildcard *.proto)) + +all: $(pbgos) + +%.pb.go: %.proto + protoc --gogofast_out=. --proto_path=$(GOPATH)/src:. $< diff --git a/vendor/github.com/libp2p/go-libp2p-autonat/pb/autonat.pb.go b/vendor/github.com/libp2p/go-libp2p-autonat/pb/autonat.pb.go index 3f2db2e1a..3617b4615 100644 --- a/vendor/github.com/libp2p/go-libp2p-autonat/pb/autonat.pb.go +++ b/vendor/github.com/libp2p/go-libp2p-autonat/pb/autonat.pb.go @@ -3,11 +3,12 @@ package autonat_pb -import proto "github.com/gogo/protobuf/proto" -import fmt "fmt" -import math "math" - -import io "io" +import ( + fmt "fmt" + proto "github.com/gogo/protobuf/proto" + io "io" + math "math" +) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal @@ -31,6 +32,7 @@ var Message_MessageType_name = map[int32]string{ 0: "DIAL", 1: "DIAL_RESPONSE", } + var Message_MessageType_value = map[string]int32{ "DIAL": 0, "DIAL_RESPONSE": 1, @@ -41,9 +43,11 @@ func (x Message_MessageType) Enum() *Message_MessageType { *p = x return p } + func (x Message_MessageType) String() string { return proto.EnumName(Message_MessageType_name, int32(x)) } + func (x *Message_MessageType) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(Message_MessageType_value, data, "Message_MessageType") if err != nil { @@ -52,8 +56,9 @@ func (x *Message_MessageType) UnmarshalJSON(data []byte) error { *x = Message_MessageType(value) return nil } + func (Message_MessageType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_autonat_bd0ec7a019b57e9d, []int{0, 0} + return fileDescriptor_a04e278ef61ac07a, []int{0, 0} } type Message_ResponseStatus int32 @@ -73,6 +78,7 @@ var Message_ResponseStatus_name = map[int32]string{ 200: "E_BAD_REQUEST", 300: "E_INTERNAL_ERROR", } + var Message_ResponseStatus_value = map[string]int32{ "OK": 0, "E_DIAL_ERROR": 100, @@ -86,9 +92,11 @@ func (x Message_ResponseStatus) Enum() *Message_ResponseStatus { *p = x return p } + func (x Message_ResponseStatus) String() string { return proto.EnumName(Message_ResponseStatus_name, int32(x)) } + func (x *Message_ResponseStatus) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(Message_ResponseStatus_value, data, "Message_ResponseStatus") if err != nil { @@ -97,8 +105,9 @@ func (x *Message_ResponseStatus) UnmarshalJSON(data []byte) error { *x = Message_ResponseStatus(value) return nil } + func (Message_ResponseStatus) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_autonat_bd0ec7a019b57e9d, []int{0, 1} + return fileDescriptor_a04e278ef61ac07a, []int{0, 1} } type Message struct { @@ -114,7 +123,7 @@ func (m *Message) Reset() { *m = Message{} } func (m *Message) String() string { return proto.CompactTextString(m) } func (*Message) ProtoMessage() {} func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_autonat_bd0ec7a019b57e9d, []int{0} + return fileDescriptor_a04e278ef61ac07a, []int{0} } func (m *Message) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -131,8 +140,8 @@ func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return b[:n], nil } } -func (dst *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(dst, src) +func (m *Message) XXX_Merge(src proto.Message) { + xxx_messageInfo_Message.Merge(m, src) } func (m *Message) XXX_Size() int { return m.Size() @@ -176,7 +185,7 @@ func (m *Message_PeerInfo) Reset() { *m = Message_PeerInfo{} } func (m *Message_PeerInfo) String() string { return proto.CompactTextString(m) } func (*Message_PeerInfo) ProtoMessage() {} func (*Message_PeerInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_autonat_bd0ec7a019b57e9d, []int{0, 0} + return fileDescriptor_a04e278ef61ac07a, []int{0, 0} } func (m *Message_PeerInfo) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -193,8 +202,8 @@ func (m *Message_PeerInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, er return b[:n], nil } } -func (dst *Message_PeerInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message_PeerInfo.Merge(dst, src) +func (m *Message_PeerInfo) XXX_Merge(src proto.Message) { + xxx_messageInfo_Message_PeerInfo.Merge(m, src) } func (m *Message_PeerInfo) XXX_Size() int { return m.Size() @@ -230,7 +239,7 @@ func (m *Message_Dial) Reset() { *m = Message_Dial{} } func (m *Message_Dial) String() string { return proto.CompactTextString(m) } func (*Message_Dial) ProtoMessage() {} func (*Message_Dial) Descriptor() ([]byte, []int) { - return fileDescriptor_autonat_bd0ec7a019b57e9d, []int{0, 1} + return fileDescriptor_a04e278ef61ac07a, []int{0, 1} } func (m *Message_Dial) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -247,8 +256,8 @@ func (m *Message_Dial) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) return b[:n], nil } } -func (dst *Message_Dial) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message_Dial.Merge(dst, src) +func (m *Message_Dial) XXX_Merge(src proto.Message) { + xxx_messageInfo_Message_Dial.Merge(m, src) } func (m *Message_Dial) XXX_Size() int { return m.Size() @@ -279,7 +288,7 @@ func (m *Message_DialResponse) Reset() { *m = Message_DialResponse{} } func (m *Message_DialResponse) String() string { return proto.CompactTextString(m) } func (*Message_DialResponse) ProtoMessage() {} func (*Message_DialResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_autonat_bd0ec7a019b57e9d, []int{0, 2} + return fileDescriptor_a04e278ef61ac07a, []int{0, 2} } func (m *Message_DialResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -296,8 +305,8 @@ func (m *Message_DialResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte return b[:n], nil } } -func (dst *Message_DialResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message_DialResponse.Merge(dst, src) +func (m *Message_DialResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_Message_DialResponse.Merge(m, src) } func (m *Message_DialResponse) XXX_Size() int { return m.Size() @@ -330,13 +339,44 @@ func (m *Message_DialResponse) GetAddr() []byte { } func init() { + proto.RegisterEnum("autonat.pb.Message_MessageType", Message_MessageType_name, Message_MessageType_value) + proto.RegisterEnum("autonat.pb.Message_ResponseStatus", Message_ResponseStatus_name, Message_ResponseStatus_value) proto.RegisterType((*Message)(nil), "autonat.pb.Message") proto.RegisterType((*Message_PeerInfo)(nil), "autonat.pb.Message.PeerInfo") proto.RegisterType((*Message_Dial)(nil), "autonat.pb.Message.Dial") proto.RegisterType((*Message_DialResponse)(nil), "autonat.pb.Message.DialResponse") - proto.RegisterEnum("autonat.pb.Message_MessageType", Message_MessageType_name, Message_MessageType_value) - proto.RegisterEnum("autonat.pb.Message_ResponseStatus", Message_ResponseStatus_name, Message_ResponseStatus_value) } + +func init() { proto.RegisterFile("autonat.proto", fileDescriptor_a04e278ef61ac07a) } + +var fileDescriptor_a04e278ef61ac07a = []byte{ + // 372 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x90, 0xcf, 0x8a, 0xda, 0x50, + 0x14, 0xc6, 0xbd, 0x31, 0xb5, 0xf6, 0x18, 0xc3, 0xed, 0xa1, 0x85, 0x20, 0x25, 0x0d, 0x59, 0x49, + 0x29, 0x22, 0x76, 0x53, 0xba, 0x53, 0x72, 0x0b, 0xd2, 0x56, 0xed, 0x49, 0x5c, 0x87, 0x94, 0xdc, + 0x0e, 0x01, 0x31, 0x21, 0x89, 0x30, 0x6e, 0xe6, 0x89, 0x66, 0x3b, 0xef, 0xe0, 0x72, 0x1e, 0x61, + 0xf0, 0x49, 0x86, 0x5c, 0xa3, 0xa3, 0xe0, 0xac, 0xce, 0x1f, 0x7e, 0xdf, 0x39, 0x1f, 0x1f, 0x74, + 0xa3, 0x4d, 0x99, 0xae, 0xa3, 0x72, 0x90, 0xe5, 0x69, 0x99, 0x22, 0x9c, 0xc6, 0x7f, 0xee, 0x83, + 0x0e, 0x6f, 0xff, 0xc8, 0xa2, 0x88, 0x6e, 0x24, 0x7e, 0x03, 0xbd, 0xdc, 0x66, 0xd2, 0x62, 0x0e, + 0xeb, 0x9b, 0xa3, 0xcf, 0x83, 0x17, 0x6c, 0x50, 0x23, 0xc7, 0x1a, 0x6c, 0x33, 0x49, 0x0a, 0xc6, + 0xaf, 0xa0, 0xc7, 0x49, 0xb4, 0xb2, 0x34, 0x87, 0xf5, 0x3b, 0x23, 0xeb, 0x9a, 0xc8, 0x4b, 0xa2, + 0x15, 0x29, 0x0a, 0x3d, 0x30, 0xaa, 0x4a, 0xb2, 0xc8, 0xd2, 0x75, 0x21, 0xad, 0xa6, 0x52, 0x39, + 0xaf, 0xaa, 0x6a, 0x8e, 0x2e, 0x54, 0xbd, 0x21, 0xb4, 0x17, 0x52, 0xe6, 0xd3, 0xf5, 0xff, 0x14, + 0x4d, 0xd0, 0x92, 0x58, 0x59, 0x36, 0x48, 0x4b, 0x62, 0xfc, 0x00, 0x6f, 0xa2, 0x38, 0xce, 0x0b, + 0x4b, 0x73, 0x9a, 0x7d, 0x83, 0x0e, 0x43, 0xef, 0x3b, 0xe8, 0xd5, 0x3d, 0x1c, 0x82, 0x9e, 0x49, + 0x99, 0x2b, 0xbe, 0x33, 0xfa, 0x74, 0xed, 0xef, 0xf1, 0x32, 0x29, 0xb2, 0x77, 0x07, 0xc6, 0xb9, + 0x13, 0xfc, 0x01, 0xad, 0xa2, 0x8c, 0xca, 0x4d, 0x51, 0xc7, 0xe4, 0x5e, 0xbb, 0x71, 0xa4, 0x7d, + 0x45, 0x52, 0xad, 0x40, 0x1b, 0xe0, 0xd0, 0x05, 0xf2, 0xb6, 0x54, 0x89, 0xbd, 0xa3, 0xb3, 0x0d, + 0x22, 0xe8, 0x95, 0x5d, 0x95, 0x8a, 0x41, 0xaa, 0x77, 0xbf, 0x40, 0xe7, 0x2c, 0x74, 0x6c, 0x83, + 0xee, 0x4d, 0xc7, 0xbf, 0x79, 0x03, 0xdf, 0x43, 0xb7, 0xea, 0x42, 0x12, 0xfe, 0x62, 0x3e, 0xf3, + 0x05, 0x67, 0x6e, 0x02, 0xe6, 0xe5, 0x67, 0x6c, 0x81, 0x36, 0xff, 0xc5, 0x1b, 0xc8, 0xc1, 0x10, + 0xa1, 0xc2, 0x05, 0xd1, 0x9c, 0x78, 0x8c, 0x08, 0x66, 0xbd, 0x21, 0xf1, 0x73, 0xe9, 0x0b, 0x8f, + 0x4b, 0x44, 0xe8, 0x8a, 0x70, 0x32, 0xf6, 0x42, 0x12, 0x7f, 0x97, 0xc2, 0x0f, 0xf8, 0x8e, 0xe1, + 0x47, 0xe0, 0x22, 0x9c, 0xce, 0x02, 0x41, 0xb3, 0x93, 0xfa, 0x5e, 0x9b, 0x18, 0xbb, 0xbd, 0xcd, + 0x1e, 0xf7, 0x36, 0x7b, 0xda, 0xdb, 0xec, 0x39, 0x00, 0x00, 0xff, 0xff, 0x8e, 0xe2, 0x93, 0x4e, + 0x61, 0x02, 0x00, 0x00, +} + func (m *Message) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -497,6 +537,9 @@ func encodeVarintAutonat(dAtA []byte, offset int, v uint64) int { return offset + 1 } func (m *Message) Size() (n int) { + if m == nil { + return 0 + } var l int _ = l if m.Type != nil { @@ -517,6 +560,9 @@ func (m *Message) Size() (n int) { } func (m *Message_PeerInfo) Size() (n int) { + if m == nil { + return 0 + } var l int _ = l if m.Id != nil { @@ -536,6 +582,9 @@ func (m *Message_PeerInfo) Size() (n int) { } func (m *Message_Dial) Size() (n int) { + if m == nil { + return 0 + } var l int _ = l if m.Peer != nil { @@ -549,6 +598,9 @@ func (m *Message_Dial) Size() (n int) { } func (m *Message_DialResponse) Size() (n int) { + if m == nil { + return 0 + } var l int _ = l if m.Status != nil { @@ -596,7 +648,7 @@ func (m *Message) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - wire |= (uint64(b) & 0x7F) << shift + wire |= uint64(b&0x7F) << shift if b < 0x80 { break } @@ -624,7 +676,7 @@ func (m *Message) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - v |= (Message_MessageType(b) & 0x7F) << shift + v |= Message_MessageType(b&0x7F) << shift if b < 0x80 { break } @@ -644,7 +696,7 @@ func (m *Message) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= (int(b) & 0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } @@ -653,6 +705,9 @@ func (m *Message) Unmarshal(dAtA []byte) error { return ErrInvalidLengthAutonat } postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthAutonat + } if postIndex > l { return io.ErrUnexpectedEOF } @@ -677,7 +732,7 @@ func (m *Message) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= (int(b) & 0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } @@ -686,6 +741,9 @@ func (m *Message) Unmarshal(dAtA []byte) error { return ErrInvalidLengthAutonat } postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthAutonat + } if postIndex > l { return io.ErrUnexpectedEOF } @@ -705,6 +763,9 @@ func (m *Message) Unmarshal(dAtA []byte) error { if skippy < 0 { return ErrInvalidLengthAutonat } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthAutonat + } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } @@ -733,7 +794,7 @@ func (m *Message_PeerInfo) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - wire |= (uint64(b) & 0x7F) << shift + wire |= uint64(b&0x7F) << shift if b < 0x80 { break } @@ -761,7 +822,7 @@ func (m *Message_PeerInfo) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - byteLen |= (int(b) & 0x7F) << shift + byteLen |= int(b&0x7F) << shift if b < 0x80 { break } @@ -770,6 +831,9 @@ func (m *Message_PeerInfo) Unmarshal(dAtA []byte) error { return ErrInvalidLengthAutonat } postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthAutonat + } if postIndex > l { return io.ErrUnexpectedEOF } @@ -792,7 +856,7 @@ func (m *Message_PeerInfo) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - byteLen |= (int(b) & 0x7F) << shift + byteLen |= int(b&0x7F) << shift if b < 0x80 { break } @@ -801,6 +865,9 @@ func (m *Message_PeerInfo) Unmarshal(dAtA []byte) error { return ErrInvalidLengthAutonat } postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthAutonat + } if postIndex > l { return io.ErrUnexpectedEOF } @@ -816,6 +883,9 @@ func (m *Message_PeerInfo) Unmarshal(dAtA []byte) error { if skippy < 0 { return ErrInvalidLengthAutonat } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthAutonat + } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } @@ -844,7 +914,7 @@ func (m *Message_Dial) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - wire |= (uint64(b) & 0x7F) << shift + wire |= uint64(b&0x7F) << shift if b < 0x80 { break } @@ -872,7 +942,7 @@ func (m *Message_Dial) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= (int(b) & 0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } @@ -881,6 +951,9 @@ func (m *Message_Dial) Unmarshal(dAtA []byte) error { return ErrInvalidLengthAutonat } postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthAutonat + } if postIndex > l { return io.ErrUnexpectedEOF } @@ -900,6 +973,9 @@ func (m *Message_Dial) Unmarshal(dAtA []byte) error { if skippy < 0 { return ErrInvalidLengthAutonat } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthAutonat + } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } @@ -928,7 +1004,7 @@ func (m *Message_DialResponse) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - wire |= (uint64(b) & 0x7F) << shift + wire |= uint64(b&0x7F) << shift if b < 0x80 { break } @@ -956,7 +1032,7 @@ func (m *Message_DialResponse) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - v |= (Message_ResponseStatus(b) & 0x7F) << shift + v |= Message_ResponseStatus(b&0x7F) << shift if b < 0x80 { break } @@ -976,7 +1052,7 @@ func (m *Message_DialResponse) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } @@ -986,6 +1062,9 @@ func (m *Message_DialResponse) Unmarshal(dAtA []byte) error { return ErrInvalidLengthAutonat } postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthAutonat + } if postIndex > l { return io.ErrUnexpectedEOF } @@ -1006,7 +1085,7 @@ func (m *Message_DialResponse) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - byteLen |= (int(b) & 0x7F) << shift + byteLen |= int(b&0x7F) << shift if b < 0x80 { break } @@ -1015,6 +1094,9 @@ func (m *Message_DialResponse) Unmarshal(dAtA []byte) error { return ErrInvalidLengthAutonat } postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthAutonat + } if postIndex > l { return io.ErrUnexpectedEOF } @@ -1032,6 +1114,9 @@ func (m *Message_DialResponse) Unmarshal(dAtA []byte) error { if skippy < 0 { return ErrInvalidLengthAutonat } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthAutonat + } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } @@ -1099,10 +1184,13 @@ func skipAutonat(dAtA []byte) (n int, err error) { break } } - iNdEx += length if length < 0 { return 0, ErrInvalidLengthAutonat } + iNdEx += length + if iNdEx < 0 { + return 0, ErrInvalidLengthAutonat + } return iNdEx, nil case 3: for { @@ -1131,6 +1219,9 @@ func skipAutonat(dAtA []byte) (n int, err error) { return 0, err } iNdEx = start + next + if iNdEx < 0 { + return 0, ErrInvalidLengthAutonat + } } return iNdEx, nil case 4: @@ -1149,33 +1240,3 @@ var ( ErrInvalidLengthAutonat = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowAutonat = fmt.Errorf("proto: integer overflow") ) - -func init() { proto.RegisterFile("autonat.proto", fileDescriptor_autonat_bd0ec7a019b57e9d) } - -var fileDescriptor_autonat_bd0ec7a019b57e9d = []byte{ - // 372 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x90, 0xcf, 0x8a, 0xda, 0x50, - 0x14, 0xc6, 0xbd, 0x31, 0xb5, 0xf6, 0x18, 0xc3, 0xed, 0xa1, 0x85, 0x20, 0x25, 0x0d, 0x59, 0x49, - 0x29, 0x22, 0x76, 0x53, 0xba, 0x53, 0x72, 0x0b, 0xd2, 0x56, 0xed, 0x49, 0x5c, 0x87, 0x94, 0xdc, - 0x0e, 0x01, 0x31, 0x21, 0x89, 0x30, 0x6e, 0xe6, 0x89, 0x66, 0x3b, 0xef, 0xe0, 0x72, 0x1e, 0x61, - 0xf0, 0x49, 0x86, 0x5c, 0xa3, 0xa3, 0xe0, 0xac, 0xce, 0x1f, 0x7e, 0xdf, 0x39, 0x1f, 0x1f, 0x74, - 0xa3, 0x4d, 0x99, 0xae, 0xa3, 0x72, 0x90, 0xe5, 0x69, 0x99, 0x22, 0x9c, 0xc6, 0x7f, 0xee, 0x83, - 0x0e, 0x6f, 0xff, 0xc8, 0xa2, 0x88, 0x6e, 0x24, 0x7e, 0x03, 0xbd, 0xdc, 0x66, 0xd2, 0x62, 0x0e, - 0xeb, 0x9b, 0xa3, 0xcf, 0x83, 0x17, 0x6c, 0x50, 0x23, 0xc7, 0x1a, 0x6c, 0x33, 0x49, 0x0a, 0xc6, - 0xaf, 0xa0, 0xc7, 0x49, 0xb4, 0xb2, 0x34, 0x87, 0xf5, 0x3b, 0x23, 0xeb, 0x9a, 0xc8, 0x4b, 0xa2, - 0x15, 0x29, 0x0a, 0x3d, 0x30, 0xaa, 0x4a, 0xb2, 0xc8, 0xd2, 0x75, 0x21, 0xad, 0xa6, 0x52, 0x39, - 0xaf, 0xaa, 0x6a, 0x8e, 0x2e, 0x54, 0xbd, 0x21, 0xb4, 0x17, 0x52, 0xe6, 0xd3, 0xf5, 0xff, 0x14, - 0x4d, 0xd0, 0x92, 0x58, 0x59, 0x36, 0x48, 0x4b, 0x62, 0xfc, 0x00, 0x6f, 0xa2, 0x38, 0xce, 0x0b, - 0x4b, 0x73, 0x9a, 0x7d, 0x83, 0x0e, 0x43, 0xef, 0x3b, 0xe8, 0xd5, 0x3d, 0x1c, 0x82, 0x9e, 0x49, - 0x99, 0x2b, 0xbe, 0x33, 0xfa, 0x74, 0xed, 0xef, 0xf1, 0x32, 0x29, 0xb2, 0x77, 0x07, 0xc6, 0xb9, - 0x13, 0xfc, 0x01, 0xad, 0xa2, 0x8c, 0xca, 0x4d, 0x51, 0xc7, 0xe4, 0x5e, 0xbb, 0x71, 0xa4, 0x7d, - 0x45, 0x52, 0xad, 0x40, 0x1b, 0xe0, 0xd0, 0x05, 0xf2, 0xb6, 0x54, 0x89, 0xbd, 0xa3, 0xb3, 0x0d, - 0x22, 0xe8, 0x95, 0x5d, 0x95, 0x8a, 0x41, 0xaa, 0x77, 0xbf, 0x40, 0xe7, 0x2c, 0x74, 0x6c, 0x83, - 0xee, 0x4d, 0xc7, 0xbf, 0x79, 0x03, 0xdf, 0x43, 0xb7, 0xea, 0x42, 0x12, 0xfe, 0x62, 0x3e, 0xf3, - 0x05, 0x67, 0x6e, 0x02, 0xe6, 0xe5, 0x67, 0x6c, 0x81, 0x36, 0xff, 0xc5, 0x1b, 0xc8, 0xc1, 0x10, - 0xa1, 0xc2, 0x05, 0xd1, 0x9c, 0x78, 0x8c, 0x08, 0x66, 0xbd, 0x21, 0xf1, 0x73, 0xe9, 0x0b, 0x8f, - 0x4b, 0x44, 0xe8, 0x8a, 0x70, 0x32, 0xf6, 0x42, 0x12, 0x7f, 0x97, 0xc2, 0x0f, 0xf8, 0x8e, 0xe1, - 0x47, 0xe0, 0x22, 0x9c, 0xce, 0x02, 0x41, 0xb3, 0x93, 0xfa, 0x5e, 0x9b, 0x18, 0xbb, 0xbd, 0xcd, - 0x1e, 0xf7, 0x36, 0x7b, 0xda, 0xdb, 0xec, 0x39, 0x00, 0x00, 0xff, 0xff, 0x8e, 0xe2, 0x93, 0x4e, - 0x61, 0x02, 0x00, 0x00, -} diff --git a/vendor/github.com/libp2p/go-libp2p-crypto/.gitignore b/vendor/github.com/libp2p/go-libp2p-crypto/.gitignore new file mode 100644 index 000000000..cc53fd51b --- /dev/null +++ b/vendor/github.com/libp2p/go-libp2p-crypto/.gitignore @@ -0,0 +1,7 @@ +.DS_Store + +# vim +.swp +*~ +*.swp +*.swo diff --git a/vendor/github.com/libp2p/go-libp2p-crypto/.travis.yml b/vendor/github.com/libp2p/go-libp2p-crypto/.travis.yml index 0f8252229..9a7e494f5 100644 --- a/vendor/github.com/libp2p/go-libp2p-crypto/.travis.yml +++ b/vendor/github.com/libp2p/go-libp2p-crypto/.travis.yml @@ -2,7 +2,7 @@ language: go sudo: true go: - - 1.9.x + - 1.11.x install: - make deps diff --git a/vendor/github.com/libp2p/go-libp2p-crypto/README.md b/vendor/github.com/libp2p/go-libp2p-crypto/README.md index ce38d68c4..ac1b554aa 100644 --- a/vendor/github.com/libp2p/go-libp2p-crypto/README.md +++ b/vendor/github.com/libp2p/go-libp2p-crypto/README.md @@ -1,8 +1,7 @@ # go-libp2p-crypto - -[![](https://img.shields.io/badge/made%20by-Protocol%20Labs-blue.svg?style=flat-square)](http://ipn.io) -[![](https://img.shields.io/badge/project-libp2p-blue.svg?style=flat-square)](http://github.com/libp2p/libp2p) -[![](https://img.shields.io/badge/freenode-%23ipfs-blue.svg?style=flat-square)](http://webchat.freenode.net/?channels=%23ipfs) +[![](https://img.shields.io/badge/project-libp2p-yellow.svg?style=flat-square)](http://libp2p.io/) +[![](https://img.shields.io/badge/pm-waffle-yellow.svg?style=flat-square)](http://github.com/libp2p/libp2p) +[![](https://img.shields.io/badge/freenode-%23libp2p-yellow.svg?style=flat-square)](http://webchat.freenode.net/?channels=%23libp2p) [![standard-readme compliant](https://img.shields.io/badge/standard--readme-OK-green.svg?style=flat-square)](https://github.com/RichardLitt/standard-readme) [![GoDoc](https://godoc.org/github.com/libp2p/go-libp2p-crypto?status.svg)](https://godoc.org/github.com/ipfs/go-libp2p-crypto) [![Coverage Status](https://coveralls.io/repos/github/ipfs/go-libp2p-crypto/badge.svg?branch=master)](https://coveralls.io/github/ipfs/go-libp2p-crypto?branch=master) @@ -36,10 +35,6 @@ Check out our [contributing document](https://github.com/libp2p/community/blob/m Small note: If editing the README, please conform to the [standard-readme](https://github.com/RichardLitt/standard-readme) specification. -### Want to hack on IPFS? - -[![](https://cdn.rawgit.com/jbenet/contribute-ipfs-gif/master/img/contribute.gif)](https://github.com/ipfs/community/blob/master/contributing.md) - ## License [MIT](LICENSE) © 2016 Jeromy Johnson diff --git a/vendor/github.com/libp2p/go-libp2p-crypto/ecdsa.go b/vendor/github.com/libp2p/go-libp2p-crypto/ecdsa.go new file mode 100644 index 000000000..80229a45f --- /dev/null +++ b/vendor/github.com/libp2p/go-libp2p-crypto/ecdsa.go @@ -0,0 +1,186 @@ +package crypto + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/x509" + "encoding/asn1" + "errors" + "io" + "math/big" + + pb "github.com/libp2p/go-libp2p-crypto/pb" + + sha256 "github.com/minio/sha256-simd" +) + +// ECDSAPrivateKey is an implementation of an ECDSA private key +type ECDSAPrivateKey struct { + priv *ecdsa.PrivateKey +} + +// ECDSAPublicKey is an implementation of an ECDSA public key +type ECDSAPublicKey struct { + pub *ecdsa.PublicKey +} + +// ECDSASig holds the r and s values of an ECDSA signature +type ECDSASig struct { + R, S *big.Int +} + +var ( + // ErrNotECDSAPubKey is returned when the public key passed is not an ecdsa public key + ErrNotECDSAPubKey = errors.New("not an ecdsa public key") + // ErrNilSig is returned when the signature is nil + ErrNilSig = errors.New("sig is nil") + // ErrNilPrivateKey is returned when a nil private key is provided + ErrNilPrivateKey = errors.New("private key is nil") + // ECDSACurve is the default ecdsa curve used + ECDSACurve = elliptic.P256() +) + +// GenerateECDSAKeyPair generates a new ecdsa private and public key +func GenerateECDSAKeyPair(src io.Reader) (PrivKey, PubKey, error) { + return GenerateECDSAKeyPairWithCurve(ECDSACurve, src) +} + +// GenerateECDSAKeyPairWithCurve generates a new ecdsa private and public key with a speicified curve +func GenerateECDSAKeyPairWithCurve(curve elliptic.Curve, src io.Reader) (PrivKey, PubKey, error) { + priv, err := ecdsa.GenerateKey(curve, src) + if err != nil { + return nil, nil, err + } + + return &ECDSAPrivateKey{priv}, &ECDSAPublicKey{&priv.PublicKey}, nil +} + +// ECDSAKeyPairFromKey generates a new ecdsa private and public key from an input private key +func ECDSAKeyPairFromKey(priv *ecdsa.PrivateKey) (PrivKey, PubKey, error) { + if priv == nil { + return nil, nil, ErrNilPrivateKey + } + + return &ECDSAPrivateKey{priv}, &ECDSAPublicKey{&priv.PublicKey}, nil +} + +// MarshalECDSAPrivateKey returns x509 bytes from a private key +func MarshalECDSAPrivateKey(ePriv ECDSAPrivateKey) ([]byte, error) { + return x509.MarshalECPrivateKey(ePriv.priv) +} + +// MarshalECDSAPublicKey returns x509 bytes from a public key +func MarshalECDSAPublicKey(ePub ECDSAPublicKey) ([]byte, error) { + return x509.MarshalPKIXPublicKey(ePub.pub) +} + +// UnmarshalECDSAPrivateKey returns a private key from x509 bytes +func UnmarshalECDSAPrivateKey(data []byte) (PrivKey, error) { + priv, err := x509.ParseECPrivateKey(data) + if err != nil { + return nil, err + } + + return &ECDSAPrivateKey{priv}, nil +} + +// UnmarshalECDSAPublicKey returns the public key from x509 bytes +func UnmarshalECDSAPublicKey(data []byte) (PubKey, error) { + pubIfc, err := x509.ParsePKIXPublicKey(data) + if err != nil { + return nil, err + } + + pub, ok := pubIfc.(*ecdsa.PublicKey) + if !ok { + return nil, ErrNotECDSAPubKey + } + + return &ECDSAPublicKey{pub}, nil +} + +// Bytes returns the private key as protobuf bytes +func (ePriv *ECDSAPrivateKey) Bytes() ([]byte, error) { + return MarshalPrivateKey(ePriv) +} + +// Type returns the key type +func (ePriv *ECDSAPrivateKey) Type() pb.KeyType { + return pb.KeyType_ECDSA +} + +// Raw returns x509 bytes from a private key +func (ePriv *ECDSAPrivateKey) Raw() ([]byte, error) { + return x509.MarshalECPrivateKey(ePriv.priv) +} + +// Equals compares to private keys +func (ePriv *ECDSAPrivateKey) Equals(o Key) bool { + oPriv, ok := o.(*ECDSAPrivateKey) + if !ok { + return false + } + + return ePriv.priv.D.Cmp(oPriv.priv.D) == 0 +} + +// Sign returns the signature of the input data +func (ePriv *ECDSAPrivateKey) Sign(data []byte) ([]byte, error) { + hash := sha256.Sum256(data) + r, s, err := ecdsa.Sign(rand.Reader, ePriv.priv, hash[:]) + if err != nil { + return nil, err + } + + return asn1.Marshal(ECDSASig{ + R: r, + S: s, + }) +} + +// GetPublic returns a public key +func (ePriv *ECDSAPrivateKey) GetPublic() PubKey { + return &ECDSAPublicKey{&ePriv.priv.PublicKey} +} + +// Bytes returns the public key as protobuf bytes +func (ePub *ECDSAPublicKey) Bytes() ([]byte, error) { + return MarshalPublicKey(ePub) +} + +// Type returns the key type +func (ePub *ECDSAPublicKey) Type() pb.KeyType { + return pb.KeyType_ECDSA +} + +// Raw returns x509 bytes from a public key +func (ePub ECDSAPublicKey) Raw() ([]byte, error) { + return x509.MarshalPKIXPublicKey(ePub.pub) +} + +// Equals compares to public keys +func (ePub *ECDSAPublicKey) Equals(o Key) bool { + oPub, ok := o.(*ECDSAPublicKey) + if !ok { + return false + } + + return ePub.pub.X != nil && ePub.pub.Y != nil && oPub.pub.X != nil && oPub.pub.Y != nil && + 0 == ePub.pub.X.Cmp(oPub.pub.X) && 0 == ePub.pub.Y.Cmp(oPub.pub.Y) +} + +// Verify compares data to a signature +func (ePub *ECDSAPublicKey) Verify(data, sigBytes []byte) (bool, error) { + sig := new(ECDSASig) + if _, err := asn1.Unmarshal(sigBytes, sig); err != nil { + return false, err + } + if sig == nil { + return false, ErrNilSig + } + + hash := sha256.Sum256(data) + + return ecdsa.Verify(ePub.pub, hash[:], sig.R, sig.S), nil +} diff --git a/vendor/github.com/libp2p/go-libp2p-crypto/ed25519.go b/vendor/github.com/libp2p/go-libp2p-crypto/ed25519.go index 45c0f8631..960ad3139 100644 --- a/vendor/github.com/libp2p/go-libp2p-crypto/ed25519.go +++ b/vendor/github.com/libp2p/go-libp2p-crypto/ed25519.go @@ -2,23 +2,26 @@ package crypto import ( "bytes" + "errors" "fmt" "io" - "github.com/agl/ed25519" - extra "github.com/agl/ed25519/extra25519" pb "github.com/libp2p/go-libp2p-crypto/pb" + + "golang.org/x/crypto/ed25519" ) +// Ed25519PrivateKey is an ed25519 private key. type Ed25519PrivateKey struct { - sk *[64]byte - pk *[32]byte + k ed25519.PrivateKey } +// Ed25519PublicKey is an ed25519 public key. type Ed25519PublicKey struct { - k *[32]byte + k ed25519.PublicKey } +// GenerateEd25519Key generate a new ed25519 private and public key pair. func GenerateEd25519Key(src io.Reader) (PrivKey, PubKey, error) { pub, priv, err := ed25519.GenerateKey(src) if err != nil { @@ -26,8 +29,7 @@ func GenerateEd25519Key(src io.Reader) (PrivKey, PubKey, error) { } return &Ed25519PrivateKey{ - sk: priv, - pk: pub, + k: priv, }, &Ed25519PublicKey{ k: pub, @@ -35,106 +37,119 @@ func GenerateEd25519Key(src io.Reader) (PrivKey, PubKey, error) { nil } +// Type of the private key (Ed25519). func (k *Ed25519PrivateKey) Type() pb.KeyType { return pb.KeyType_Ed25519 } +// Bytes marshals an ed25519 private key to protobuf bytes. func (k *Ed25519PrivateKey) Bytes() ([]byte, error) { return MarshalPrivateKey(k) } +// Raw private key bytes. func (k *Ed25519PrivateKey) Raw() ([]byte, error) { - buf := make([]byte, 96) - copy(buf, k.sk[:]) - copy(buf[64:], k.pk[:]) + // The Ed25519 private key contains two 32-bytes curve points, the private + // key and the public key. + // It makes it more efficient to get the public key without re-computing an + // elliptic curve multiplication. + buf := make([]byte, len(k.k)) + copy(buf, k.k) return buf, nil } +func (k *Ed25519PrivateKey) pubKeyBytes() []byte { + return k.k[ed25519.PrivateKeySize-ed25519.PublicKeySize:] +} + +// Equals compares two ed25519 private keys. func (k *Ed25519PrivateKey) Equals(o Key) bool { edk, ok := o.(*Ed25519PrivateKey) if !ok { return false } - return bytes.Equal((*k.sk)[:], (*edk.sk)[:]) && bytes.Equal((*k.pk)[:], (*edk.pk)[:]) + return bytes.Equal(k.k, edk.k) } +// GetPublic returns an ed25519 public key from a private key. func (k *Ed25519PrivateKey) GetPublic() PubKey { - return &Ed25519PublicKey{k.pk} + return &Ed25519PublicKey{k: k.pubKeyBytes()} } +// Sign returns a signature from an input message. func (k *Ed25519PrivateKey) Sign(msg []byte) ([]byte, error) { - out := ed25519.Sign(k.sk, msg) - return (*out)[:], nil -} - -func (k *Ed25519PrivateKey) ToCurve25519() *[32]byte { - var sk [32]byte - extra.PrivateKeyToCurve25519(&sk, k.sk) - return &sk + return ed25519.Sign(k.k, msg), nil } +// Type of the public key (Ed25519). func (k *Ed25519PublicKey) Type() pb.KeyType { return pb.KeyType_Ed25519 } +// Bytes returns a ed25519 public key as protobuf bytes. func (k *Ed25519PublicKey) Bytes() ([]byte, error) { return MarshalPublicKey(k) } +// Raw public key bytes. func (k *Ed25519PublicKey) Raw() ([]byte, error) { - return (*k.k)[:], nil + return k.k, nil } +// Equals compares two ed25519 public keys. func (k *Ed25519PublicKey) Equals(o Key) bool { edk, ok := o.(*Ed25519PublicKey) if !ok { return false } - return bytes.Equal((*k.k)[:], (*edk.k)[:]) + return bytes.Equal(k.k, edk.k) } +// Verify checks a signature agains the input data. func (k *Ed25519PublicKey) Verify(data []byte, sig []byte) (bool, error) { - var asig [64]byte - copy(asig[:], sig) - return ed25519.Verify(k.k, data, &asig), nil -} - -func (k *Ed25519PublicKey) ToCurve25519() (*[32]byte, error) { - var pk [32]byte - success := extra.PublicKeyToCurve25519(&pk, k.k) - if !success { - return nil, fmt.Errorf("Error converting ed25519 pubkey to curve25519 pubkey") - } - return &pk, nil + return ed25519.Verify(k.k, data, sig), nil } +// UnmarshalEd25519PublicKey returns a public key from input bytes. func UnmarshalEd25519PublicKey(data []byte) (PubKey, error) { if len(data) != 32 { - return nil, fmt.Errorf("expect ed25519 public key data size to be 32") + return nil, errors.New("expect ed25519 public key data size to be 32") } - var pub [32]byte - copy(pub[:], data) - return &Ed25519PublicKey{ - k: &pub, + k: ed25519.PublicKey(data), }, nil } +// UnmarshalEd25519PrivateKey returns a private key from input bytes. func UnmarshalEd25519PrivateKey(data []byte) (PrivKey, error) { - if len(data) != 96 { - return nil, fmt.Errorf("expected ed25519 data size to be 96") + switch len(data) { + case ed25519.PrivateKeySize + ed25519.PublicKeySize: + // Remove the redundant public key. See issue #36. + redundantPk := data[ed25519.PrivateKeySize:] + pk := data[ed25519.PrivateKeySize-ed25519.PublicKeySize : ed25519.PrivateKeySize] + if !bytes.Equal(pk, redundantPk) { + return nil, errors.New("expected redundant ed25519 public key to be redundant") + } + + // No point in storing the extra data. + newKey := make([]byte, ed25519.PrivateKeySize) + copy(newKey, data[:ed25519.PrivateKeySize]) + data = newKey + case ed25519.PrivateKeySize: + default: + return nil, fmt.Errorf( + "expected ed25519 data size to be %d or %d, got %d", + ed25519.PrivateKeySize, + ed25519.PrivateKeySize+ed25519.PublicKeySize, + len(data), + ) } - var priv [64]byte - var pub [32]byte - copy(priv[:], data) - copy(pub[:], data[64:]) return &Ed25519PrivateKey{ - sk: &priv, - pk: &pub, + k: ed25519.PrivateKey(data), }, nil } diff --git a/vendor/github.com/libp2p/go-libp2p-crypto/key.go b/vendor/github.com/libp2p/go-libp2p-crypto/key.go index 884bf214c..9900772d4 100644 --- a/vendor/github.com/libp2p/go-libp2p-crypto/key.go +++ b/vendor/github.com/libp2p/go-libp2p-crypto/key.go @@ -5,18 +5,16 @@ package crypto import ( "bytes" - "encoding/base64" - "errors" - "fmt" - "io" - "crypto/elliptic" "crypto/hmac" "crypto/rand" - "crypto/rsa" "crypto/sha1" "crypto/sha512" + "encoding/base64" + "errors" + "fmt" "hash" + "io" pb "github.com/libp2p/go-libp2p-crypto/pb" @@ -24,19 +22,28 @@ import ( sha256 "github.com/minio/sha256-simd" ) -var ErrBadKeyType = errors.New("invalid or unsupported key type") - const ( + // RSA is an enum for the supported RSA key type RSA = iota + // Ed25519 is an enum for the supported Ed25519 key type Ed25519 + // Secp256k1 is an enum for the supported Secp256k1 key type Secp256k1 + // ECDSA is an enum for the supported ECDSA key type + ECDSA ) -var KeyTypes = []int{ - RSA, - Ed25519, - Secp256k1, -} +var ( + // ErrBadKeyType is returned when a key is not supported + ErrBadKeyType = errors.New("invalid or unsupported key type") + // KeyTypes is a list of supported keys + KeyTypes = []int{ + RSA, + Ed25519, + Secp256k1, + ECDSA, + } +) // PubKeyUnmarshaller is a func that creates a PubKey from a given slice of bytes type PubKeyUnmarshaller func(data []byte) (PubKey, error) @@ -44,16 +51,20 @@ type PubKeyUnmarshaller func(data []byte) (PubKey, error) // PrivKeyUnmarshaller is a func that creates a PrivKey from a given slice of bytes type PrivKeyUnmarshaller func(data []byte) (PrivKey, error) +// PubKeyUnmarshallers is a map of unmarshallers by key type var PubKeyUnmarshallers = map[pb.KeyType]PubKeyUnmarshaller{ pb.KeyType_RSA: UnmarshalRsaPublicKey, pb.KeyType_Ed25519: UnmarshalEd25519PublicKey, pb.KeyType_Secp256k1: UnmarshalSecp256k1PublicKey, + pb.KeyType_ECDSA: UnmarshalECDSAPublicKey, } +// PrivKeyUnmarshallers is a map of unmarshallers by key type var PrivKeyUnmarshallers = map[pb.KeyType]PrivKeyUnmarshaller{ pb.KeyType_RSA: UnmarshalRsaPrivateKey, pb.KeyType_Ed25519: UnmarshalEd25519PrivateKey, pb.KeyType_Secp256k1: UnmarshalSecp256k1PrivateKey, + pb.KeyType_ECDSA: UnmarshalECDSAPrivateKey, } // Key represents a crypto key that can be compared to another key @@ -87,6 +98,7 @@ type PrivKey interface { GetPublic() PubKey } +// PubKey is a public key type PubKey interface { Key @@ -94,33 +106,31 @@ type PubKey interface { Verify(data []byte, sig []byte) (bool, error) } -// Given a public key, generates the shared key. +// GenSharedKey generates the shared key from a given private key type GenSharedKey func([]byte) ([]byte, error) +// GenerateKeyPair generates a private and public key func GenerateKeyPair(typ, bits int) (PrivKey, PubKey, error) { return GenerateKeyPairWithReader(typ, bits, rand.Reader) } -// Generates a keypair of the given type and bitsize +// GenerateKeyPairWithReader returns a keypair of the given type and bitsize func GenerateKeyPairWithReader(typ, bits int, src io.Reader) (PrivKey, PubKey, error) { switch typ { case RSA: - priv, err := rsa.GenerateKey(src, bits) - if err != nil { - return nil, nil, err - } - pk := &priv.PublicKey - return &RsaPrivateKey{sk: priv}, &RsaPublicKey{pk}, nil + return GenerateRSAKeyPair(bits, src) case Ed25519: return GenerateEd25519Key(src) case Secp256k1: return GenerateSecp256k1Key(src) + case ECDSA: + return GenerateECDSAKeyPair(src) default: return nil, nil, ErrBadKeyType } } -// Generates an ephemeral public key and returns a function that will compute +// GenerateEKeyPair returns an ephemeral public key and returns a function that will compute // the shared secret key. Used in the identify module. // // Focuses only on ECDH now, but can be made more general in the future. @@ -147,11 +157,11 @@ func GenerateEKeyPair(curveName string) ([]byte, GenSharedKey, error) { // Verify and unpack node's public key. x, y := elliptic.Unmarshal(curve, theirPub) if x == nil { - return nil, fmt.Errorf("Malformed public key: %d %v", len(theirPub), theirPub) + return nil, fmt.Errorf("malformed public key: %d %v", len(theirPub), theirPub) } if !curve.IsOnCurve(x, y) { - return nil, errors.New("Invalid public key.") + return nil, errors.New("invalid public key") } // Generate shared secret. @@ -163,13 +173,14 @@ func GenerateEKeyPair(curveName string) ([]byte, GenSharedKey, error) { return pubKey, done, nil } +// StretchedKeys ... type StretchedKeys struct { IV []byte MacKey []byte CipherKey []byte } -// Generates a set of keys for each party by stretching the shared key. +// KeyStretcher returns a set of keys for each party by stretching the shared key. // (myIV, theirIV, myCipherKey, theirCipherKey, myMACKey, theirMACKey) func KeyStretcher(cipherType string, hashType string, secret []byte) (StretchedKeys, StretchedKeys) { var cipherKeySize int @@ -207,6 +218,7 @@ func KeyStretcher(cipherType string, hashType string, secret []byte) (StretchedK } m := hmac.New(h, secret) + // note: guaranteed to never return an error m.Write(seed) a := m.Sum(nil) @@ -214,8 +226,11 @@ func KeyStretcher(cipherType string, hashType string, secret []byte) (StretchedK j := 0 for j < len(result) { m.Reset() + + // note: guaranteed to never return an error. m.Write(a) m.Write(seed) + b := m.Sum(nil) todo := len(b) @@ -229,7 +244,10 @@ func KeyStretcher(cipherType string, hashType string, secret []byte) (StretchedK j += todo m.Reset() + + // note: guaranteed to never return an error. m.Write(a) + a = m.Sum(nil) } diff --git a/vendor/github.com/libp2p/go-libp2p-crypto/package.json b/vendor/github.com/libp2p/go-libp2p-crypto/package.json index 3e9a2292a..9320858f3 100644 --- a/vendor/github.com/libp2p/go-libp2p-crypto/package.json +++ b/vendor/github.com/libp2p/go-libp2p-crypto/package.json @@ -7,18 +7,6 @@ "dvcsimport": "github.com/libp2p/go-libp2p-crypto" }, "gxDependencies": [ - { - "author": "whyrusleeping", - "hash": "QmdxUuburamoF6zF9qjeQC4WYcWGbWuRmdLacMEsW8ioD8", - "name": "gogo-protobuf", - "version": "0.0.0" - }, - { - "author": "whyrusleeping", - "hash": "QmQ51pHe6u7CWodkUGDLqaCEMchkbMt7VEZnECF5mp6tVb", - "name": "ed25519", - "version": "0.0.0" - }, { "author": "btcsuite", "hash": "QmWq5PJgAQKDWQerAijYUVKW8mN5MDatK5j7VMp8rizKQd", @@ -27,9 +15,21 @@ }, { "author": "minio", - "hash": "QmXTpwq2AkzQsPjKqFQDNY2bMdsAT53hUBETeyj8QRHTZU", + "hash": "QmcTzQXRcU2vf8yX5EEboz1BSvWC7wWmeYAKVQmhp8WZYU", "name": "sha256-simd", - "version": "0.1.1" + "version": "0.1.2" + }, + { + "author": "whyrusleeping", + "hash": "QmdxUuburamoF6zF9qjeQC4WYcWGbWuRmdLacMEsW8ioD8", + "name": "gogo-protobuf", + "version": "0.0.0" + }, + { + "author": "golang", + "hash": "QmW7VUmSvhvSGbYbdsh7uRjhGmsYkc9fL8aJ5CorxxrU5N", + "name": "go-crypto", + "version": "0.2.1" } ], "gxVersion": "0.4.0", @@ -37,6 +37,6 @@ "license": "MIT", "name": "go-libp2p-crypto", "releaseCmd": "git commit -a -m \"gx publish $VERSION\"", - "version": "2.0.1" + "version": "2.0.5" } diff --git a/vendor/github.com/libp2p/go-libp2p-crypto/pb/crypto.pb.go b/vendor/github.com/libp2p/go-libp2p-crypto/pb/crypto.pb.go index aa9100957..1967a8b62 100644 --- a/vendor/github.com/libp2p/go-libp2p-crypto/pb/crypto.pb.go +++ b/vendor/github.com/libp2p/go-libp2p-crypto/pb/crypto.pb.go @@ -27,17 +27,20 @@ const ( KeyType_RSA KeyType = 0 KeyType_Ed25519 KeyType = 1 KeyType_Secp256k1 KeyType = 2 + KeyType_ECDSA KeyType = 3 ) var KeyType_name = map[int32]string{ 0: "RSA", 1: "Ed25519", 2: "Secp256k1", + 3: "ECDSA", } var KeyType_value = map[string]int32{ "RSA": 0, "Ed25519": 1, "Secp256k1": 2, + "ECDSA": 3, } func (x KeyType) Enum() *KeyType { @@ -57,7 +60,7 @@ func (x *KeyType) UnmarshalJSON(data []byte) error { return nil } func (KeyType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_crypto_1dd381b574a62cc7, []int{0} + return fileDescriptor_crypto_916f6c71dcfaadb2, []int{0} } type PublicKey struct { @@ -71,7 +74,7 @@ func (m *PublicKey) Reset() { *m = PublicKey{} } func (m *PublicKey) String() string { return proto.CompactTextString(m) } func (*PublicKey) ProtoMessage() {} func (*PublicKey) Descriptor() ([]byte, []int) { - return fileDescriptor_crypto_1dd381b574a62cc7, []int{0} + return fileDescriptor_crypto_916f6c71dcfaadb2, []int{0} } func (m *PublicKey) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -125,7 +128,7 @@ func (m *PrivateKey) Reset() { *m = PrivateKey{} } func (m *PrivateKey) String() string { return proto.CompactTextString(m) } func (*PrivateKey) ProtoMessage() {} func (*PrivateKey) Descriptor() ([]byte, []int) { - return fileDescriptor_crypto_1dd381b574a62cc7, []int{1} + return fileDescriptor_crypto_916f6c71dcfaadb2, []int{1} } func (m *PrivateKey) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -594,20 +597,21 @@ var ( ErrIntOverflowCrypto = fmt.Errorf("proto: integer overflow") ) -func init() { proto.RegisterFile("crypto.proto", fileDescriptor_crypto_1dd381b574a62cc7) } +func init() { proto.RegisterFile("crypto.proto", fileDescriptor_crypto_916f6c71dcfaadb2) } -var fileDescriptor_crypto_1dd381b574a62cc7 = []byte{ - // 183 bytes of a gzipped FileDescriptorProto +var fileDescriptor_crypto_916f6c71dcfaadb2 = []byte{ + // 194 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x49, 0x2e, 0xaa, 0x2c, 0x28, 0xc9, 0xd7, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x84, 0xf1, 0x92, 0x94, 0x82, 0xb9, 0x38, 0x03, 0x4a, 0x93, 0x72, 0x32, 0x93, 0xbd, 0x53, 0x2b, 0x85, 0x74, 0xb8, 0x58, 0x42, 0x2a, 0x0b, 0x52, 0x25, 0x18, 0x15, 0x98, 0x34, 0xf8, 0x8c, 0x84, 0xf4, 0xe0, 0xca, 0xf4, 0xbc, 0x53, 0x2b, 0x41, 0x32, 0x4e, 0x2c, 0x27, 0xee, 0xc9, 0x33, 0x04, 0x81, 0x55, 0x09, 0x49, 0x70, 0xb1, 0xb8, 0x24, 0x96, 0x24, 0x4a, 0x30, 0x29, 0x30, 0x69, 0xf0, 0xc0, 0x64, 0x40, 0x22, 0x4a, 0x21, - 0x5c, 0x5c, 0x01, 0x45, 0x99, 0x65, 0x89, 0x25, 0xa9, 0x54, 0x34, 0x55, 0x4b, 0x8f, 0x8b, 0x1d, + 0x5c, 0x5c, 0x01, 0x45, 0x99, 0x65, 0x89, 0x25, 0xa9, 0x54, 0x34, 0x55, 0xcb, 0x92, 0x8b, 0x1d, 0xaa, 0x41, 0x88, 0x9d, 0x8b, 0x39, 0x28, 0xd8, 0x51, 0x80, 0x41, 0x88, 0x9b, 0x8b, 0xdd, 0x35, 0xc5, 0xc8, 0xd4, 0xd4, 0xd0, 0x52, 0x80, 0x51, 0x88, 0x97, 0x8b, 0x33, 0x38, 0x35, 0xb9, 0xc0, - 0xc8, 0xd4, 0x2c, 0xdb, 0x50, 0x80, 0xc9, 0x49, 0xe0, 0xc4, 0x23, 0x39, 0xc6, 0x0b, 0x8f, 0xe4, - 0x18, 0x1f, 0x3c, 0x92, 0x63, 0x9c, 0xf0, 0x58, 0x8e, 0x01, 0x10, 0x00, 0x00, 0xff, 0xff, 0xb9, - 0x28, 0x49, 0x72, 0x06, 0x01, 0x00, 0x00, + 0xc8, 0xd4, 0x2c, 0xdb, 0x50, 0x80, 0x49, 0x88, 0x93, 0x8b, 0xd5, 0xd5, 0xd9, 0x25, 0xd8, 0x51, + 0x80, 0xd9, 0x49, 0xe0, 0xc4, 0x23, 0x39, 0xc6, 0x0b, 0x8f, 0xe4, 0x18, 0x1f, 0x3c, 0x92, 0x63, + 0x9c, 0xf0, 0x58, 0x8e, 0x01, 0x10, 0x00, 0x00, 0xff, 0xff, 0xf1, 0xcc, 0xed, 0xac, 0x11, 0x01, + 0x00, 0x00, } diff --git a/vendor/github.com/libp2p/go-libp2p-crypto/pb/crypto.proto b/vendor/github.com/libp2p/go-libp2p-crypto/pb/crypto.proto index 72778f972..cb5cee8a2 100644 --- a/vendor/github.com/libp2p/go-libp2p-crypto/pb/crypto.proto +++ b/vendor/github.com/libp2p/go-libp2p-crypto/pb/crypto.proto @@ -6,6 +6,7 @@ enum KeyType { RSA = 0; Ed25519 = 1; Secp256k1 = 2; + ECDSA = 3; } message PublicKey { diff --git a/vendor/github.com/libp2p/go-libp2p-crypto/rsa.go b/vendor/github.com/libp2p/go-libp2p-crypto/rsa.go index 8a9e58a73..e1ab22d6f 100644 --- a/vendor/github.com/libp2p/go-libp2p-crypto/rsa.go +++ b/vendor/github.com/libp2p/go-libp2p-crypto/rsa.go @@ -6,21 +6,43 @@ import ( "crypto/rsa" "crypto/x509" "errors" + "io" pb "github.com/libp2p/go-libp2p-crypto/pb" sha256 "github.com/minio/sha256-simd" ) +// ErrRsaKeyTooSmall is returned when trying to generate or parse an RSA key +// that's smaller than 512 bits. Keys need to be larger enough to sign a 256bit +// hash so this is a reasonable absolute minimum. +var ErrRsaKeyTooSmall = errors.New("rsa keys must be >= 512 bits to be useful") + +// RsaPrivateKey is an rsa private key type RsaPrivateKey struct { sk *rsa.PrivateKey pk *rsa.PublicKey } +// RsaPublicKey is an rsa public key type RsaPublicKey struct { k *rsa.PublicKey } +// GenerateRSAKeyPair generates a new rsa private and public key +func GenerateRSAKeyPair(bits int, src io.Reader) (PrivKey, PubKey, error) { + if bits < 512 { + return nil, nil, ErrRsaKeyTooSmall + } + priv, err := rsa.GenerateKey(src, bits) + if err != nil { + return nil, nil, err + } + pk := &priv.PublicKey + return &RsaPrivateKey{sk: priv}, &RsaPublicKey{pk}, nil +} + +// Verify compares a signature against input data func (pk *RsaPublicKey) Verify(data, sig []byte) (bool, error) { hashed := sha256.Sum256(data) err := rsa.VerifyPKCS1v15(pk.k, crypto.SHA256, hashed[:], sig) @@ -34,6 +56,7 @@ func (pk *RsaPublicKey) Type() pb.KeyType { return pb.KeyType_RSA } +// Bytes returns protobuf bytes of a public key func (pk *RsaPublicKey) Bytes() ([]byte, error) { return MarshalPublicKey(pk) } @@ -42,6 +65,7 @@ func (pk *RsaPublicKey) Raw() ([]byte, error) { return x509.MarshalPKIXPublicKey(pk.k) } +// Encrypt returns encrypted bytes from the inpu data func (pk *RsaPublicKey) Encrypt(b []byte) ([]byte, error) { return rsa.EncryptPKCS1v15(rand.Reader, pk.k, b) } @@ -51,11 +75,13 @@ func (pk *RsaPublicKey) Equals(k Key) bool { return KeyEqual(pk, k) } +// Sign returns a signature of the input data func (sk *RsaPrivateKey) Sign(message []byte) ([]byte, error) { hashed := sha256.Sum256(message) return rsa.SignPKCS1v15(rand.Reader, sk.sk, crypto.SHA256, hashed[:]) } +// GetPublic returns a public key func (sk *RsaPrivateKey) GetPublic() PubKey { if sk.pk == nil { sk.pk = &sk.sk.PublicKey @@ -63,6 +89,7 @@ func (sk *RsaPrivateKey) GetPublic() PubKey { return &RsaPublicKey{sk.pk} } +// Decrypt returns decrypted bytes of the input encrypted bytes func (sk *RsaPrivateKey) Decrypt(b []byte) ([]byte, error) { return rsa.DecryptPKCS1v15(rand.Reader, sk.sk, b) } @@ -71,6 +98,7 @@ func (sk *RsaPrivateKey) Type() pb.KeyType { return pb.KeyType_RSA } +// Bytes returns protobuf bytes from a private key func (sk *RsaPrivateKey) Bytes() ([]byte, error) { return MarshalPrivateKey(sk) } @@ -85,18 +113,24 @@ func (sk *RsaPrivateKey) Equals(k Key) bool { return KeyEqual(sk, k) } +// UnmarshalRsaPrivateKey returns a private key from the input x509 bytes func UnmarshalRsaPrivateKey(b []byte) (PrivKey, error) { sk, err := x509.ParsePKCS1PrivateKey(b) if err != nil { return nil, err } + if sk.N.BitLen() < 512 { + return nil, ErrRsaKeyTooSmall + } return &RsaPrivateKey{sk: sk}, nil } +// MarshalRsaPrivateKey returns the x509 bytes of the private key func MarshalRsaPrivateKey(k *RsaPrivateKey) []byte { return x509.MarshalPKCS1PrivateKey(k.sk) } +// UnmarshalRsaPublicKey returns a public key from the input x509 bytes func UnmarshalRsaPublicKey(b []byte) (PubKey, error) { pub, err := x509.ParsePKIXPublicKey(b) if err != nil { @@ -104,11 +138,15 @@ func UnmarshalRsaPublicKey(b []byte) (PubKey, error) { } pk, ok := pub.(*rsa.PublicKey) if !ok { - return nil, errors.New("Not actually an rsa public key.") + return nil, errors.New("not actually an rsa public key") + } + if pk.N.BitLen() < 512 { + return nil, ErrRsaKeyTooSmall } return &RsaPublicKey{pk}, nil } +// MarshalRsaPublicKey returns the x509 bytes from the public key func MarshalRsaPublicKey(k *RsaPublicKey) ([]byte, error) { return x509.MarshalPKIXPublicKey(k.k) } diff --git a/vendor/github.com/libp2p/go-libp2p-crypto/secp256k1.go b/vendor/github.com/libp2p/go-libp2p-crypto/secp256k1.go index 0b7fa3094..8bca33e7c 100644 --- a/vendor/github.com/libp2p/go-libp2p-crypto/secp256k1.go +++ b/vendor/github.com/libp2p/go-libp2p-crypto/secp256k1.go @@ -4,14 +4,19 @@ import ( "fmt" "io" - btcec "github.com/btcsuite/btcd/btcec" pb "github.com/libp2p/go-libp2p-crypto/pb" + + btcec "github.com/btcsuite/btcd/btcec" sha256 "github.com/minio/sha256-simd" ) +// Secp256k1PrivateKey is an Secp256k1 private key type Secp256k1PrivateKey btcec.PrivateKey + +// Secp256k1PublicKey is an Secp256k1 public key type Secp256k1PublicKey btcec.PublicKey +// GenerateSecp256k1Key generates a new Secp256k1 private and public key pair func GenerateSecp256k1Key(src io.Reader) (PrivKey, PubKey, error) { privk, err := btcec.NewPrivateKey(btcec.S256()) if err != nil { @@ -22,6 +27,7 @@ func GenerateSecp256k1Key(src io.Reader) (PrivKey, PubKey, error) { return k, k.GetPublic(), nil } +// UnmarshalSecp256k1PrivateKey returns a private key from bytes func UnmarshalSecp256k1PrivateKey(data []byte) (PrivKey, error) { if len(data) != btcec.PrivKeyBytesLen { return nil, fmt.Errorf("expected secp256k1 data size to be %d", btcec.PrivKeyBytesLen) @@ -31,6 +37,7 @@ func UnmarshalSecp256k1PrivateKey(data []byte) (PrivKey, error) { return (*Secp256k1PrivateKey)(privk), nil } +// UnmarshalSecp256k1PublicKey returns a public key from bytes func UnmarshalSecp256k1PublicKey(data []byte) (PubKey, error) { k, err := btcec.ParsePubKey(data, btcec.S256()) if err != nil { @@ -40,18 +47,22 @@ func UnmarshalSecp256k1PublicKey(data []byte) (PubKey, error) { return (*Secp256k1PublicKey)(k), nil } -func (sk *Secp256k1PrivateKey) Type() pb.KeyType { - return pb.KeyType_Secp256k1 +// Bytes returns protobuf bytes from a private key +func (k *Secp256k1PrivateKey) Bytes() ([]byte, error) { + return MarshalPrivateKey(k) } -func (sk *Secp256k1PrivateKey) Bytes() ([]byte, error) { - return MarshalPrivateKey(sk) +// Type returns the private key type +func (k *Secp256k1PrivateKey) Type() pb.KeyType { + return pb.KeyType_Secp256k1 } +// Raw returns the bytes of the key func (k *Secp256k1PrivateKey) Raw() ([]byte, error) { return (*btcec.PrivateKey)(k).Serialize(), nil } +// Equals compares two private keys func (k *Secp256k1PrivateKey) Equals(o Key) bool { sk, ok := o.(*Secp256k1PrivateKey) if !ok { @@ -61,6 +72,7 @@ func (k *Secp256k1PrivateKey) Equals(o Key) bool { return k.D.Cmp(sk.D) == 0 } +// Sign returns a signature from input data func (k *Secp256k1PrivateKey) Sign(data []byte) ([]byte, error) { hash := sha256.Sum256(data) sig, err := (*btcec.PrivateKey)(k).Sign(hash[:]) @@ -71,22 +83,27 @@ func (k *Secp256k1PrivateKey) Sign(data []byte) ([]byte, error) { return sig.Serialize(), nil } +// GetPublic returns a public key func (k *Secp256k1PrivateKey) GetPublic() PubKey { return (*Secp256k1PublicKey)((*btcec.PrivateKey)(k).PubKey()) } -func (sk *Secp256k1PublicKey) Type() pb.KeyType { - return pb.KeyType_Secp256k1 +// Bytes returns protobuf bytes from a public key +func (k *Secp256k1PublicKey) Bytes() ([]byte, error) { + return MarshalPublicKey(k) } -func (sk *Secp256k1PublicKey) Bytes() ([]byte, error) { - return MarshalPublicKey(sk) +// Type returns the public key type +func (k *Secp256k1PublicKey) Type() pb.KeyType { + return pb.KeyType_Secp256k1 } +// Raw returns the bytes of the key func (k *Secp256k1PublicKey) Raw() ([]byte, error) { return (*btcec.PublicKey)(k).SerializeCompressed(), nil } +// Equals compares two public keys func (k *Secp256k1PublicKey) Equals(o Key) bool { sk, ok := o.(*Secp256k1PublicKey) if !ok { @@ -96,6 +113,7 @@ func (k *Secp256k1PublicKey) Equals(o Key) bool { return (*btcec.PublicKey)(k).IsEqual((*btcec.PublicKey)(sk)) } +// Verify compares a signature against the input data func (k *Secp256k1PublicKey) Verify(data []byte, sigStr []byte) (bool, error) { sig, err := btcec.ParseDERSignature(sigStr, btcec.S256()) if err != nil { diff --git a/vendor/github.com/libp2p/go-libp2p-discovery/package.json b/vendor/github.com/libp2p/go-libp2p-discovery/package.json index 73fa87c90..31ee9a574 100644 --- a/vendor/github.com/libp2p/go-libp2p-discovery/package.json +++ b/vendor/github.com/libp2p/go-libp2p-discovery/package.json @@ -7,14 +7,14 @@ "gxDependencies": [ { "author": "whyrusleeping", - "hash": "QmPiemjiKBC9VA7vZF82m4x1oygtg2c2YVqag8PX7dN1BD", + "hash": "QmRhFARzTHcFh8wUxwN5KvyTGq73FLC65EfFAhz8Ng7aGb", "name": "go-libp2p-peerstore", - "version": "2.0.13" + "version": "2.0.17" }, { - "hash": "QmTiRqrF5zkdZyrdsL5qndG1UbeWi8k8N2pYxCtXWrahR2", + "hash": "QmWaDSNoSdSXU9b6udyaq9T8y6LkzMwqWxECznFqvtcTsk", "name": "go-libp2p-routing", - "version": "2.7.7" + "version": "2.7.10" }, { "author": "whyrusleeping", @@ -29,33 +29,33 @@ "version": "1.0.9" }, { - "hash": "QmcuXC5cxs79ro2cUuHs4HQ2bkDLJUYokwL8aivcX6HW3C", + "hash": "QmbkT7eMTyXfpeyB3ZMxxcxg7XH8t6uXp49jqzz4HB7BGF", "name": "go-log", - "version": "1.5.8" + "version": "1.5.9" }, { "author": "whyrusleeping", - "hash": "QmQLbY1oKd4eHrikizXXwYkxn6yujUNSUMimv3UCaWTSWX", + "hash": "QmSka7Ax3a1HhyGaC3mqqrWbDhHsTmyzvED4Xk6dfvPXbY", "name": "go-libp2p-blankhost", - "version": "0.3.21" + "version": "0.3.24" }, { "author": "whyrusleeping", - "hash": "QmegQFxhr1J6yZ1vDQuDmJi5jntmj6BL96S11HVtXNCaHb", + "hash": "QmU7iTrsNaJfu1Rf5DrvaJLH9wJtQwmP4Dj8oPduprAU68", "name": "go-libp2p-swarm", - "version": "3.0.28" + "version": "3.0.31" }, { "author": "whyrusleeping", - "hash": "QmY5Grm8pJdiSSVsYxx4uNRgweY72EmYwuSDbRnbFok3iY", + "hash": "QmTu65MVbemtUxJEWgsTtzv9Zv9P8rvmqNA4eG9TrTRGYc", "name": "go-libp2p-peer", - "version": "3.0.0" + "version": "3.1.1" }, { "author": "whyrusleeping", - "hash": "QmaoXrM4Z41PD48JY36YqQGKQpLGjyLA2cKcLsES7YddAq", + "hash": "Qmd52WKRSwrBK5gUaJKawryZQ5by6UbNB8KVW2Zy6JtbyW", "name": "go-libp2p-host", - "version": "3.0.21" + "version": "3.0.24" } ], "gxVersion": "0.12.1", @@ -63,6 +63,6 @@ "license": "", "name": "go-libp2p-discovery", "releaseCmd": "git commit -a -m \"gx publish $VERSION\"", - "version": "1.0.5" + "version": "1.0.10" } diff --git a/vendor/github.com/libp2p/go-libp2p-discovery/routing.go b/vendor/github.com/libp2p/go-libp2p-discovery/routing.go index f79726c93..3f6a9738e 100644 --- a/vendor/github.com/libp2p/go-libp2p-discovery/routing.go +++ b/vendor/github.com/libp2p/go-libp2p-discovery/routing.go @@ -26,13 +26,19 @@ func (d *RoutingDiscovery) Advertise(ctx context.Context, ns string, opts ...Opt return 0, err } - err = d.Provide(ctx, cid, true) + // this context requires a timeout; it determines how long the DHT looks for + // closest peers to the key/CID before it goes on to provide the record to them. + // Not setting a timeout here will make the DHT wander forever. + pctx, cancel := context.WithTimeout(ctx, 60*time.Second) + defer cancel() + + err = d.Provide(pctx, cid, true) if err != nil { return 0, err } - // this is the dht provide validity - return 24 * time.Hour, nil + // the DHT provider record validity is 24hrs, but it is recommnded to republish every 6hrs + return 6 * time.Hour, nil } func (d *RoutingDiscovery) FindPeers(ctx context.Context, ns string, opts ...Option) (<-chan pstore.PeerInfo, error) { @@ -56,7 +62,7 @@ func (d *RoutingDiscovery) FindPeers(ctx context.Context, ns string, opts ...Opt } func nsToCid(ns string) (cid.Cid, error) { - h, err := mh.Encode([]byte(ns), mh.SHA2_256) + h, err := mh.Sum([]byte(ns), mh.SHA2_256, -1) if err != nil { return cid.Undef, err } diff --git a/vendor/github.com/libp2p/go-libp2p-peer/package.json b/vendor/github.com/libp2p/go-libp2p-peer/package.json index 5ff4c0562..d2267258a 100644 --- a/vendor/github.com/libp2p/go-libp2p-peer/package.json +++ b/vendor/github.com/libp2p/go-libp2p-peer/package.json @@ -9,9 +9,9 @@ "gxDependencies": [ { "author": "whyrusleeping", - "hash": "QmNiJiXwWE3kRhZrC5ej3kSjWHm337pYfhjLGSCDNKJP2s", + "hash": "QmTW4SdgBWq9GjsBsHeUx8WuGxzhgzAf88UMH2w62PC8yK", "name": "go-libp2p-crypto", - "version": "2.0.4" + "version": "2.0.7" }, { "author": "multiformats", @@ -31,6 +31,6 @@ "license": "MIT", "name": "go-libp2p-peer", "releaseCmd": "git commit -a -m \"gx publish $VERSION\"", - "version": "3.0.0" + "version": "3.1.1" } diff --git a/vendor/github.com/libp2p/go-libp2p-peer/peer.go b/vendor/github.com/libp2p/go-libp2p-peer/peer.go index 5becf8f5b..6189d1d4c 100644 --- a/vendor/github.com/libp2p/go-libp2p-peer/peer.go +++ b/vendor/github.com/libp2p/go-libp2p-peer/peer.go @@ -14,10 +14,25 @@ import ( var ( // ErrEmptyPeerID is an error for empty peer ID. ErrEmptyPeerID = errors.New("empty peer ID") - // ErrNoPublickKey is an error for peer IDs that don't embed public keys + // ErrNoPublicKey is an error for peer IDs that don't embed public keys ErrNoPublicKey = errors.New("public key is not embedded in peer ID") ) +// AdvancedEnableInlining enables automatically inlining keys shorter than +// 42 bytes into the peer ID (using the "identity" multihash function). +// +// WARNING: This flag will likely be set to false in the future and eventually +// be removed in favor of using a hash function specified by the key itself. +// See: https://github.com/libp2p/specs/issues/138 +// +// DO NOT change this flag unless you know what you're doing. +// +// This currently defaults to true for backwards compatibility but will likely +// be set to false by default when an upgrade path is determined. +var AdvancedEnableInlining = true + +const maxInlineKeyLength = 42 + // ID is a libp2p peer identity. type ID string @@ -141,7 +156,11 @@ func IDFromPublicKey(pk ic.PubKey) (ID, error) { if err != nil { return "", err } - hash, _ := mh.Sum(b, mh.SHA2_256, -1) + var alg uint64 = mh.SHA2_256 + if AdvancedEnableInlining && len(b) <= maxInlineKeyLength { + alg = mh.ID + } + hash, _ := mh.Sum(b, alg, -1) return ID(hash), nil } diff --git a/vendor/github.com/libp2p/go-reuseport-transport/package.json b/vendor/github.com/libp2p/go-reuseport-transport/package.json index b35f215f0..259e44637 100644 --- a/vendor/github.com/libp2p/go-reuseport-transport/package.json +++ b/vendor/github.com/libp2p/go-reuseport-transport/package.json @@ -8,15 +8,9 @@ }, "gxDependencies": [ { - "hash": "QmcuXC5cxs79ro2cUuHs4HQ2bkDLJUYokwL8aivcX6HW3C", + "hash": "QmbkT7eMTyXfpeyB3ZMxxcxg7XH8t6uXp49jqzz4HB7BGF", "name": "go-log", - "version": "1.5.8" - }, - { - "author": "whyrusleeping", - "hash": "QmPYNfPvCAqTa84qbW14zAfFV1sDEovTd919wdPM6pGsRJ", - "name": "go-reuseport", - "version": "0.2.0" + "version": "1.5.9" }, { "author": "multiformats", @@ -29,6 +23,12 @@ "hash": "QmZcLBXKaFe8ND5YHPkJRAwmhJGrVsi1JqDZNyJ4nRK5Mj", "name": "go-multiaddr-net", "version": "1.7.1" + }, + { + "author": "whyrusleeping", + "hash": "Qme8kdM7thoCqLqd7GYCRqipoZJS64rhJo5MBcTpyWfsL9", + "name": "go-reuseport", + "version": "0.2.2" } ], "gxVersion": "0.12.1", @@ -36,6 +36,6 @@ "license": "", "name": "go-reuseport-transport", "releaseCmd": "git commit -a -m \"gx publish $VERSION\"", - "version": "0.2.0" + "version": "0.2.2" } diff --git a/vendor/github.com/streadway/amqp/.gitignore b/vendor/github.com/streadway/amqp/.gitignore index ba8a70568..667fb50c5 100644 --- a/vendor/github.com/streadway/amqp/.gitignore +++ b/vendor/github.com/streadway/amqp/.gitignore @@ -2,3 +2,11 @@ certs/* spec/spec examples/simple-consumer/simple-consumer examples/simple-producer/simple-producer + +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +.idea/**/contentModel.xml diff --git a/vendor/github.com/streadway/amqp/auth.go b/vendor/github.com/streadway/amqp/auth.go index ebc765b6a..7c4a30f21 100644 --- a/vendor/github.com/streadway/amqp/auth.go +++ b/vendor/github.com/streadway/amqp/auth.go @@ -32,6 +32,23 @@ func (auth *PlainAuth) Response() string { return fmt.Sprintf("\000%s\000%s", auth.Username, auth.Password) } +// AMQPlainAuth is an historically developed +// alternative to PlainAuth +type AMQPlainAuth struct { + Username string + Password string +} + +// Mechanism returns "AMQPLAIN" +func (auth *AMQPlainAuth) Mechanism() string { + return "AMQPLAIN" +} + +// Response returns the null character delimited encoding for the SASL PLAIN Mechanism. +func (auth *AMQPlainAuth) Response() string { + return fmt.Sprintf("LOGIN:%sPASSWORD:%s", auth.Username, auth.Password) +} + // Finds the first mechanism preferred by the client that the server supports. func pickSASLMechanism(client []Authentication, serverMechanisms []string) (auth Authentication, ok bool) { for _, auth = range client { diff --git a/vendor/github.com/streadway/amqp/channel.go b/vendor/github.com/streadway/amqp/channel.go index 3898ed785..a39371c7e 100644 --- a/vendor/github.com/streadway/amqp/channel.go +++ b/vendor/github.com/streadway/amqp/channel.go @@ -59,7 +59,7 @@ type Channel struct { cancels []chan string // Allocated when in confirm mode in order to track publish counter and order confirms - confirms *confirms + confirms *Confirms confirming bool // Selects on any errors from shutdown during RPC @@ -1588,3 +1588,8 @@ func (ch *Channel) Reject(tag uint64, requeue bool) error { Requeue: requeue, }) } + +// Confirms returns control structure over confirm mode +func (ch *Channel) Confirms() *Confirms { + return ch.confirms +} diff --git a/vendor/github.com/streadway/amqp/confirms.go b/vendor/github.com/streadway/amqp/confirms.go index 06cbaa711..b87b8dbf1 100644 --- a/vendor/github.com/streadway/amqp/confirms.go +++ b/vendor/github.com/streadway/amqp/confirms.go @@ -2,8 +2,8 @@ package amqp import "sync" -// confirms resequences and notifies one or multiple publisher confirmation listeners -type confirms struct { +// Confirms resequences and notifies one or multiple publisher confirmation listeners +type Confirms struct { m sync.Mutex listeners []chan Confirmation sequencer map[uint64]Confirmation @@ -12,23 +12,33 @@ type confirms struct { } // newConfirms allocates a confirms -func newConfirms() *confirms { - return &confirms{ +func newConfirms() *Confirms { + return &Confirms{ sequencer: map[uint64]Confirmation{}, published: 0, expecting: 1, } } -func (c *confirms) Listen(l chan Confirmation) { +// Published returns sequential number of published messages +func (c *Confirms) Published() uint64 { + c.m.Lock() + defer c.m.Unlock() + + return c.published +} + +// Listen is used to listen on incoming confirmations +// of publishes +func (c *Confirms) Listen(l chan Confirmation) { c.m.Lock() defer c.m.Unlock() c.listeners = append(c.listeners, l) } -// publish increments the publishing counter -func (c *confirms) Publish() uint64 { +// Publish increments the publishing counter +func (c *Confirms) Publish() uint64 { c.m.Lock() defer c.m.Unlock() @@ -38,7 +48,7 @@ func (c *confirms) Publish() uint64 { // confirm confirms one publishing, increments the expecting delivery tag, and // removes bookkeeping for that delivery tag. -func (c *confirms) confirm(confirmation Confirmation) { +func (c *Confirms) confirm(confirmation Confirmation) { delete(c.sequencer, c.expecting) c.expecting++ for _, l := range c.listeners { @@ -47,7 +57,7 @@ func (c *confirms) confirm(confirmation Confirmation) { } // resequence confirms any out of order delivered confirmations -func (c *confirms) resequence() { +func (c *Confirms) resequence() { for c.expecting <= c.published { sequenced, found := c.sequencer[c.expecting] if !found { @@ -57,8 +67,8 @@ func (c *confirms) resequence() { } } -// one confirms one publishing and all following in the publishing sequence -func (c *confirms) One(confirmed Confirmation) { +// One confirms one publishing and all following in the publishing sequence +func (c *Confirms) One(confirmed Confirmation) { c.m.Lock() defer c.m.Unlock() @@ -70,8 +80,8 @@ func (c *confirms) One(confirmed Confirmation) { c.resequence() } -// multiple confirms all publishings up until the delivery tag -func (c *confirms) Multiple(confirmed Confirmation) { +// Multiple confirms all publishings up until the delivery tag +func (c *Confirms) Multiple(confirmed Confirmation) { c.m.Lock() defer c.m.Unlock() @@ -82,7 +92,7 @@ func (c *confirms) Multiple(confirmed Confirmation) { } // Close closes all listeners, discarding any out of sequence confirmations -func (c *confirms) Close() error { +func (c *Confirms) Close() error { c.m.Lock() defer c.m.Unlock() diff --git a/vendor/github.com/streadway/amqp/connection.go b/vendor/github.com/streadway/amqp/connection.go index ca1372d0f..b9d8e8eee 100644 --- a/vendor/github.com/streadway/amqp/connection.go +++ b/vendor/github.com/streadway/amqp/connection.go @@ -111,21 +111,23 @@ type readDeadliner interface { SetReadDeadline(time.Time) error } -// defaultDial establishes a connection when config.Dial is not provided -func defaultDial(network, addr string) (net.Conn, error) { - conn, err := net.DialTimeout(network, addr, defaultConnectionTimeout) - if err != nil { - return nil, err - } +// DefaultDial establishes a connection when config.Dial is not provided +func DefaultDial(connectionTimeout time.Duration) func(network, addr string) (net.Conn, error) { + return func(network, addr string) (net.Conn, error) { + conn, err := net.DialTimeout(network, addr, connectionTimeout) + if err != nil { + return nil, err + } - // Heartbeating hasn't started yet, don't stall forever on a dead server. - // A deadline is set for TLS and AMQP handshaking. After AMQP is established, - // the deadline is cleared in openComplete. - if err := conn.SetDeadline(time.Now().Add(defaultConnectionTimeout)); err != nil { - return nil, err - } + // Heartbeating hasn't started yet, don't stall forever on a dead server. + // A deadline is set for TLS and AMQP handshaking. After AMQP is established, + // the deadline is cleared in openComplete. + if err := conn.SetDeadline(time.Now().Add(connectionTimeout)); err != nil { + return nil, err + } - return conn, nil + return conn, nil + } } // Dial accepts a string in the AMQP URI format and returns a new Connection @@ -180,7 +182,7 @@ func DialConfig(url string, config Config) (*Connection, error) { dialer := config.Dial if dialer == nil { - dialer = defaultDial + dialer = DefaultDial(defaultConnectionTimeout) } conn, err = dialer("tcp", addr) @@ -201,6 +203,7 @@ func DialConfig(url string, config Config) (*Connection, error) { client := tls.Client(conn, config.TLSClientConfig) if err := client.Handshake(); err != nil { + conn.Close() return nil, err } @@ -317,7 +320,7 @@ including the underlying io, Channels, Notify listeners and Channel consumers will also be closed. */ func (c *Connection) Close() error { - if c.isClosed() { + if c.IsClosed() { return ErrClosed } @@ -332,7 +335,7 @@ func (c *Connection) Close() error { } func (c *Connection) closeWith(err *Error) error { - if c.isClosed() { + if c.IsClosed() { return ErrClosed } @@ -346,12 +349,14 @@ func (c *Connection) closeWith(err *Error) error { ) } -func (c *Connection) isClosed() bool { +// IsClosed returns true if the connection is marked as closed, otherwise false +// is returned. +func (c *Connection) IsClosed() bool { return (atomic.LoadInt32(&c.closed) == 1) } func (c *Connection) send(f frame) error { - if c.isClosed() { + if c.IsClosed() { return ErrClosed } @@ -591,7 +596,7 @@ func (c *Connection) allocateChannel() (*Channel, error) { c.m.Lock() defer c.m.Unlock() - if c.isClosed() { + if c.IsClosed() { return nil, ErrClosed } diff --git a/vendor/github.com/streadway/amqp/uri.go b/vendor/github.com/streadway/amqp/uri.go index 35fefdc2f..b5a820255 100644 --- a/vendor/github.com/streadway/amqp/uri.go +++ b/vendor/github.com/streadway/amqp/uri.go @@ -125,6 +125,15 @@ func (uri URI) PlainAuth() *PlainAuth { } } +// AMQPlainAuth returns a username and password +// parsed from the URI +func (uri URI) AMQPlainAuth() *AMQPlainAuth { + return &AMQPlainAuth{ + Username: uri.Username, + Password: uri.Password, + } +} + func (uri URI) String() string { authority, err := url.Parse("") if err != nil { diff --git a/vendor/github.com/streadway/amqp/write.go b/vendor/github.com/streadway/amqp/write.go index 58ed20d67..94a46d115 100644 --- a/vendor/github.com/streadway/amqp/write.go +++ b/vendor/github.com/streadway/amqp/write.go @@ -308,6 +308,11 @@ func writeField(w io.Writer, value interface{}) (err error) { binary.BigEndian.PutUint16(buf[1:3], uint16(v)) enc = buf[:3] + case int: + buf[0] = 'I' + binary.BigEndian.PutUint32(buf[1:5], uint32(v)) + enc = buf[:5] + case int32: buf[0] = 'I' binary.BigEndian.PutUint32(buf[1:5], uint32(v)) diff --git a/vendor/golang.org/x/crypto/ed25519/ed25519.go b/vendor/golang.org/x/crypto/ed25519/ed25519.go new file mode 100644 index 000000000..d6f683ba3 --- /dev/null +++ b/vendor/golang.org/x/crypto/ed25519/ed25519.go @@ -0,0 +1,217 @@ +// Copyright 2016 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 ed25519 implements the Ed25519 signature algorithm. See +// https://ed25519.cr.yp.to/. +// +// These functions are also compatible with the “Ed25519” function defined in +// RFC 8032. However, unlike RFC 8032's formulation, this package's private key +// representation includes a public key suffix to make multiple signing +// operations with the same key more efficient. This package refers to the RFC +// 8032 private key as the “seed”. +package ed25519 + +// This code is a port of the public domain, “ref10” implementation of ed25519 +// from SUPERCOP. + +import ( + "bytes" + "crypto" + cryptorand "crypto/rand" + "crypto/sha512" + "errors" + "io" + "strconv" + + "golang.org/x/crypto/ed25519/internal/edwards25519" +) + +const ( + // PublicKeySize is the size, in bytes, of public keys as used in this package. + PublicKeySize = 32 + // PrivateKeySize is the size, in bytes, of private keys as used in this package. + PrivateKeySize = 64 + // SignatureSize is the size, in bytes, of signatures generated and verified by this package. + SignatureSize = 64 + // SeedSize is the size, in bytes, of private key seeds. These are the private key representations used by RFC 8032. + SeedSize = 32 +) + +// PublicKey is the type of Ed25519 public keys. +type PublicKey []byte + +// PrivateKey is the type of Ed25519 private keys. It implements crypto.Signer. +type PrivateKey []byte + +// Public returns the PublicKey corresponding to priv. +func (priv PrivateKey) Public() crypto.PublicKey { + publicKey := make([]byte, PublicKeySize) + copy(publicKey, priv[32:]) + return PublicKey(publicKey) +} + +// Seed returns the private key seed corresponding to priv. It is provided for +// interoperability with RFC 8032. RFC 8032's private keys correspond to seeds +// in this package. +func (priv PrivateKey) Seed() []byte { + seed := make([]byte, SeedSize) + copy(seed, priv[:32]) + return seed +} + +// Sign signs the given message with priv. +// Ed25519 performs two passes over messages to be signed and therefore cannot +// handle pre-hashed messages. Thus opts.HashFunc() must return zero to +// indicate the message hasn't been hashed. This can be achieved by passing +// crypto.Hash(0) as the value for opts. +func (priv PrivateKey) Sign(rand io.Reader, message []byte, opts crypto.SignerOpts) (signature []byte, err error) { + if opts.HashFunc() != crypto.Hash(0) { + return nil, errors.New("ed25519: cannot sign hashed message") + } + + return Sign(priv, message), nil +} + +// GenerateKey generates a public/private key pair using entropy from rand. +// If rand is nil, crypto/rand.Reader will be used. +func GenerateKey(rand io.Reader) (PublicKey, PrivateKey, error) { + if rand == nil { + rand = cryptorand.Reader + } + + seed := make([]byte, SeedSize) + if _, err := io.ReadFull(rand, seed); err != nil { + return nil, nil, err + } + + privateKey := NewKeyFromSeed(seed) + publicKey := make([]byte, PublicKeySize) + copy(publicKey, privateKey[32:]) + + return publicKey, privateKey, nil +} + +// NewKeyFromSeed calculates a private key from a seed. It will panic if +// len(seed) is not SeedSize. This function is provided for interoperability +// with RFC 8032. RFC 8032's private keys correspond to seeds in this +// package. +func NewKeyFromSeed(seed []byte) PrivateKey { + if l := len(seed); l != SeedSize { + panic("ed25519: bad seed length: " + strconv.Itoa(l)) + } + + digest := sha512.Sum512(seed) + digest[0] &= 248 + digest[31] &= 127 + digest[31] |= 64 + + var A edwards25519.ExtendedGroupElement + var hBytes [32]byte + copy(hBytes[:], digest[:]) + edwards25519.GeScalarMultBase(&A, &hBytes) + var publicKeyBytes [32]byte + A.ToBytes(&publicKeyBytes) + + privateKey := make([]byte, PrivateKeySize) + copy(privateKey, seed) + copy(privateKey[32:], publicKeyBytes[:]) + + return privateKey +} + +// Sign signs the message with privateKey and returns a signature. It will +// panic if len(privateKey) is not PrivateKeySize. +func Sign(privateKey PrivateKey, message []byte) []byte { + if l := len(privateKey); l != PrivateKeySize { + panic("ed25519: bad private key length: " + strconv.Itoa(l)) + } + + h := sha512.New() + h.Write(privateKey[:32]) + + var digest1, messageDigest, hramDigest [64]byte + var expandedSecretKey [32]byte + h.Sum(digest1[:0]) + copy(expandedSecretKey[:], digest1[:]) + expandedSecretKey[0] &= 248 + expandedSecretKey[31] &= 63 + expandedSecretKey[31] |= 64 + + h.Reset() + h.Write(digest1[32:]) + h.Write(message) + h.Sum(messageDigest[:0]) + + var messageDigestReduced [32]byte + edwards25519.ScReduce(&messageDigestReduced, &messageDigest) + var R edwards25519.ExtendedGroupElement + edwards25519.GeScalarMultBase(&R, &messageDigestReduced) + + var encodedR [32]byte + R.ToBytes(&encodedR) + + h.Reset() + h.Write(encodedR[:]) + h.Write(privateKey[32:]) + h.Write(message) + h.Sum(hramDigest[:0]) + var hramDigestReduced [32]byte + edwards25519.ScReduce(&hramDigestReduced, &hramDigest) + + var s [32]byte + edwards25519.ScMulAdd(&s, &hramDigestReduced, &expandedSecretKey, &messageDigestReduced) + + signature := make([]byte, SignatureSize) + copy(signature[:], encodedR[:]) + copy(signature[32:], s[:]) + + return signature +} + +// Verify reports whether sig is a valid signature of message by publicKey. It +// will panic if len(publicKey) is not PublicKeySize. +func Verify(publicKey PublicKey, message, sig []byte) bool { + if l := len(publicKey); l != PublicKeySize { + panic("ed25519: bad public key length: " + strconv.Itoa(l)) + } + + if len(sig) != SignatureSize || sig[63]&224 != 0 { + return false + } + + var A edwards25519.ExtendedGroupElement + var publicKeyBytes [32]byte + copy(publicKeyBytes[:], publicKey) + if !A.FromBytes(&publicKeyBytes) { + return false + } + edwards25519.FeNeg(&A.X, &A.X) + edwards25519.FeNeg(&A.T, &A.T) + + h := sha512.New() + h.Write(sig[:32]) + h.Write(publicKey[:]) + h.Write(message) + var digest [64]byte + h.Sum(digest[:0]) + + var hReduced [32]byte + edwards25519.ScReduce(&hReduced, &digest) + + var R edwards25519.ProjectiveGroupElement + var s [32]byte + copy(s[:], sig[32:]) + + // https://tools.ietf.org/html/rfc8032#section-5.1.7 requires that s be in + // the range [0, order) in order to prevent signature malleability. + if !edwards25519.ScMinimal(&s) { + return false + } + + edwards25519.GeDoubleScalarMultVartime(&R, &hReduced, &A, &s) + + var checkR [32]byte + R.ToBytes(&checkR) + return bytes.Equal(sig[:32], checkR[:]) +} diff --git a/vendor/github.com/agl/ed25519/edwards25519/const.go b/vendor/golang.org/x/crypto/ed25519/internal/edwards25519/const.go similarity index 99% rename from vendor/github.com/agl/ed25519/edwards25519/const.go rename to vendor/golang.org/x/crypto/ed25519/internal/edwards25519/const.go index ea5b77a71..e39f086c1 100644 --- a/vendor/github.com/agl/ed25519/edwards25519/const.go +++ b/vendor/golang.org/x/crypto/ed25519/internal/edwards25519/const.go @@ -1,25 +1,34 @@ -// Copyright 2013 The Go Authors. All rights reserved. +// Copyright 2016 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 edwards25519 +// These values are from the public domain, “ref10” implementation of ed25519 +// from SUPERCOP. + +// d is a constant in the Edwards curve equation. var d = FieldElement{ -10913610, 13857413, -15372611, 6949391, 114729, -8787816, -6275908, -3247719, -18696448, -12055116, } +// d2 is 2*d. var d2 = FieldElement{ -21827239, -5839606, -30745221, 13898782, 229458, 15978800, -12551817, -6495438, 29715968, 9444199, } +// SqrtM1 is the square-root of -1 in the field. var SqrtM1 = FieldElement{ -32595792, -7943725, 9377950, 3500415, 12389472, -272473, -25146209, -2005654, 326686, 11406482, } +// A is a constant in the Montgomery-form of curve25519. var A = FieldElement{ 486662, 0, 0, 0, 0, 0, 0, 0, 0, 0, } +// bi contains precomputed multiples of the base-point. See the Ed25519 paper +// for a discussion about how these values are used. var bi = [8]PreComputedGroupElement{ { FieldElement{25967493, -14356035, 29566456, 3660896, -12694345, 4014787, 27544626, -11754271, -6079156, 2047605}, @@ -63,6 +72,8 @@ var bi = [8]PreComputedGroupElement{ }, } +// base contains precomputed multiples of the base-point. See the Ed25519 paper +// for a discussion about how these values are used. var base = [32][8]PreComputedGroupElement{ { { diff --git a/vendor/github.com/agl/ed25519/edwards25519/edwards25519.go b/vendor/golang.org/x/crypto/ed25519/internal/edwards25519/edwards25519.go similarity index 98% rename from vendor/github.com/agl/ed25519/edwards25519/edwards25519.go rename to vendor/golang.org/x/crypto/ed25519/internal/edwards25519/edwards25519.go index 907981855..fd03c252a 100644 --- a/vendor/github.com/agl/ed25519/edwards25519/edwards25519.go +++ b/vendor/golang.org/x/crypto/ed25519/internal/edwards25519/edwards25519.go @@ -1,13 +1,12 @@ -// Copyright 2013 The Go Authors. All rights reserved. +// Copyright 2016 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 edwards25519 implements operations in GF(2**255-19) and on an -// Edwards curve that is isomorphic to curve25519. See -// http://ed25519.cr.yp.to/. package edwards25519 -// This code is a port of the public domain, "ref10" implementation of ed25519 +import "encoding/binary" + +// This code is a port of the public domain, “ref10” implementation of ed25519 // from SUPERCOP. // FieldElement represents an element of the field GF(2^255 - 19). An element @@ -373,7 +372,7 @@ func FeCombine(h *FieldElement, h0, h1, h2, h3, h4, h5, h6, h7, h8, h9 int64) { // 10 of them are 2-way parallelizable and vectorizable. // Can get away with 11 carries, but then data flow is much deeper. // -// With tighter constraints on inputs can squeeze carries into int32. +// With tighter constraints on inputs, can squeeze carries into int32. func FeMul(h, f, g *FieldElement) { f0 := int64(f[0]) f1 := int64(f[1]) @@ -928,7 +927,8 @@ func GeDoubleScalarMultVartime(r *ProjectiveGroupElement, a *[32]byte, A *Extend } } -// equal returns 1 if b == c and 0 otherwise. +// equal returns 1 if b == c and 0 otherwise, assuming that b and c are +// non-negative. func equal(b, c int32) int32 { x := uint32(b ^ c) x-- @@ -1771,3 +1771,23 @@ func ScReduce(out *[32]byte, s *[64]byte) { out[30] = byte(s11 >> 9) out[31] = byte(s11 >> 17) } + +// order is the order of Curve25519 in little-endian form. +var order = [4]uint64{0x5812631a5cf5d3ed, 0x14def9dea2f79cd6, 0, 0x1000000000000000} + +// ScMinimal returns true if the given scalar is less than the order of the +// curve. +func ScMinimal(scalar *[32]byte) bool { + for i := 3; ; i-- { + v := binary.LittleEndian.Uint64(scalar[i*8:]) + if v > order[i] { + return false + } else if v < order[i] { + break + } else if i == 0 { + return false + } + } + + return true +} diff --git a/vendor/golang.org/x/net/html/parse.go b/vendor/golang.org/x/net/html/parse.go index 488e8d3cd..ca2cb5875 100644 --- a/vendor/golang.org/x/net/html/parse.go +++ b/vendor/golang.org/x/net/html/parse.go @@ -439,9 +439,6 @@ func (p *parser) resetInsertionMode() { case a.Select: if !last { for ancestor, first := n, p.oe[0]; ancestor != first; { - if ancestor == first { - break - } ancestor = p.oe[p.oe.index(ancestor)-1] switch ancestor.DataAtom { case a.Template: diff --git a/vendor/golang.org/x/sys/cpu/byteorder.go b/vendor/golang.org/x/sys/cpu/byteorder.go new file mode 100644 index 000000000..da6b9e436 --- /dev/null +++ b/vendor/golang.org/x/sys/cpu/byteorder.go @@ -0,0 +1,30 @@ +// Copyright 2019 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 cpu + +import ( + "encoding/binary" + "runtime" +) + +// hostByteOrder returns binary.LittleEndian on little-endian machines and +// binary.BigEndian on big-endian machines. +func hostByteOrder() binary.ByteOrder { + switch runtime.GOARCH { + case "386", "amd64", "amd64p32", + "arm", "arm64", + "mipsle", "mips64le", "mips64p32le", + "ppc64le", + "riscv", "riscv64": + return binary.LittleEndian + case "armbe", "arm64be", + "mips", "mips64", "mips64p32", + "ppc", "ppc64", + "s390", "s390x", + "sparc", "sparc64": + return binary.BigEndian + } + panic("unknown architecture") +} diff --git a/vendor/golang.org/x/sys/cpu/cpu_linux.go b/vendor/golang.org/x/sys/cpu/cpu_linux.go index a8452e094..5ed69644b 100644 --- a/vendor/golang.org/x/sys/cpu/cpu_linux.go +++ b/vendor/golang.org/x/sys/cpu/cpu_linux.go @@ -7,9 +7,7 @@ package cpu import ( - "encoding/binary" "io/ioutil" - "runtime" ) const ( @@ -18,7 +16,7 @@ const ( procAuxv = "/proc/self/auxv" - uintSize uint = 32 << (^uint(0) >> 63) + uintSize = int(32 << (^uint(0) >> 63)) ) // For those platforms don't have a 'cpuid' equivalent we use HWCAP/HWCAP2 @@ -33,22 +31,18 @@ func init() { panic("read proc auxv failed: " + err.Error()) } - pb := int(uintSize / 8) - - for i := 0; i < len(buf)-pb*2; i += pb * 2 { + bo := hostByteOrder() + for len(buf) >= 2*(uintSize/8) { var tag, val uint switch uintSize { case 32: - tag = uint(binary.LittleEndian.Uint32(buf[i:])) - val = uint(binary.LittleEndian.Uint32(buf[i+pb:])) + tag = uint(bo.Uint32(buf[0:])) + val = uint(bo.Uint32(buf[4:])) + buf = buf[8:] case 64: - if runtime.GOARCH == "ppc64" { - tag = uint(binary.BigEndian.Uint64(buf[i:])) - val = uint(binary.BigEndian.Uint64(buf[i+pb:])) - } else { - tag = uint(binary.LittleEndian.Uint64(buf[i:])) - val = uint(binary.LittleEndian.Uint64(buf[i+pb:])) - } + tag = uint(bo.Uint64(buf[0:])) + val = uint(bo.Uint64(buf[8:])) + buf = buf[16:] } switch tag { case _AT_HWCAP: diff --git a/vendor/golang.org/x/sys/cpu/cpu_arm64.go b/vendor/golang.org/x/sys/cpu/cpu_linux_arm64.go similarity index 100% rename from vendor/golang.org/x/sys/cpu/cpu_arm64.go rename to vendor/golang.org/x/sys/cpu/cpu_linux_arm64.go diff --git a/vendor/golang.org/x/sys/cpu/cpu_other_arm64.go b/vendor/golang.org/x/sys/cpu/cpu_other_arm64.go new file mode 100644 index 000000000..dd1e76dc9 --- /dev/null +++ b/vendor/golang.org/x/sys/cpu/cpu_other_arm64.go @@ -0,0 +1,11 @@ +// Copyright 2019 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. + +// +build !linux,arm64 + +package cpu + +const cacheLineSize = 64 + +func doinit() {} diff --git a/vendor/golang.org/x/sys/unix/README.md b/vendor/golang.org/x/sys/unix/README.md index 2bf415fb1..eb2f78ae2 100644 --- a/vendor/golang.org/x/sys/unix/README.md +++ b/vendor/golang.org/x/sys/unix/README.md @@ -32,7 +32,7 @@ To build the files for your current OS and architecture, make sure GOOS and GOARCH are set correctly and run `mkall.sh`. This will generate the files for your specific system. Running `mkall.sh -n` shows the commands that will be run. -Requirements: bash, perl, go +Requirements: bash, go ### New Build System (currently for `GOOS == "linux"`) @@ -52,14 +52,14 @@ system and have your GOOS and GOARCH set accordingly. Running `mkall.sh` will then generate all of the files for all of the GOOS/GOARCH pairs in the new build system. Running `mkall.sh -n` shows the commands that will be run. -Requirements: bash, perl, go, docker +Requirements: bash, go, docker ## Component files This section describes the various files used in the code generation process. It also contains instructions on how to modify these files to add a new architecture/OS or to add additional syscalls, types, or constants. Note that -if you are using the new build system, the scripts cannot be called normally. +if you are using the new build system, the scripts/programs cannot be called normally. They must be called from within the docker container. ### asm files @@ -81,8 +81,8 @@ each GOOS/GOARCH pair. ### mksysnum -Mksysnum is a script located at `${GOOS}/mksysnum.pl` (or `mksysnum_${GOOS}.pl` -for the old system). This script takes in a list of header files containing the +Mksysnum is a Go program located at `${GOOS}/mksysnum.go` (or `mksysnum_${GOOS}.go` +for the old system). This program takes in a list of header files containing the syscall number declarations and parses them to produce the corresponding list of Go numeric constants. See `zsysnum_${GOOS}_${GOARCH}.go` for the generated constants. @@ -92,14 +92,14 @@ new installation of the target OS (or updating the source checkouts for the new build system). However, depending on the OS, you make need to update the parsing in mksysnum. -### mksyscall.pl +### mksyscall.go The `syscall.go`, `syscall_${GOOS}.go`, `syscall_${GOOS}_${GOARCH}.go` are hand-written Go files which implement system calls (for unix, the specific OS, or the specific OS/Architecture pair respectively) that need special handling and list `//sys` comments giving prototypes for ones that can be generated. -The mksyscall.pl script takes the `//sys` and `//sysnb` comments and converts +The mksyscall.go program takes the `//sys` and `//sysnb` comments and converts them into syscalls. This requires the name of the prototype in the comment to match a syscall number in the `zsysnum_${GOOS}_${GOARCH}.go` file. The function prototype can be exported (capitalized) or not. @@ -160,7 +160,7 @@ signal numbers, and constants. Generated by `mkerrors.sh` (see above). ### `zsyscall_${GOOS}_${GOARCH}.go` A file containing all the generated syscalls for a specific GOOS and GOARCH. -Generated by `mksyscall.pl` (see above). +Generated by `mksyscall.go` (see above). ### `zsysnum_${GOOS}_${GOARCH}.go` diff --git a/vendor/golang.org/x/sys/unix/mkall.sh b/vendor/golang.org/x/sys/unix/mkall.sh index d74115a8a..75152f99b 100755 --- a/vendor/golang.org/x/sys/unix/mkall.sh +++ b/vendor/golang.org/x/sys/unix/mkall.sh @@ -170,7 +170,7 @@ openbsd_arm) mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" ;; solaris_amd64) - mksyscall="./mksyscall_solaris.pl" + mksyscall="go run mksyscall_solaris.go" mkerrors="$mkerrors -m64" mksysnum= mktypes="GOARCH=$GOARCH go tool cgo -godefs" diff --git a/vendor/golang.org/x/sys/unix/mksyscall.go b/vendor/golang.org/x/sys/unix/mksyscall.go index 890652ca8..e06e4253e 100644 --- a/vendor/golang.org/x/sys/unix/mksyscall.go +++ b/vendor/golang.org/x/sys/unix/mksyscall.go @@ -88,6 +88,10 @@ func parseParam(p string) Param { func main() { // Get the OS and architecture (using GOARCH_TARGET if it exists) goos := os.Getenv("GOOS") + if goos == "" { + fmt.Fprintln(os.Stderr, "GOOS not defined in environment") + os.Exit(1) + } goarch := os.Getenv("GOARCH_TARGET") if goarch == "" { goarch = os.Getenv("GOARCH") diff --git a/vendor/golang.org/x/sys/unix/mksyscall_solaris.go b/vendor/golang.org/x/sys/unix/mksyscall_solaris.go new file mode 100644 index 000000000..3d864738b --- /dev/null +++ b/vendor/golang.org/x/sys/unix/mksyscall_solaris.go @@ -0,0 +1,335 @@ +// Copyright 2019 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. + +// +build ignore + +/* + This program reads a file containing function prototypes + (like syscall_solaris.go) and generates system call bodies. + The prototypes are marked by lines beginning with "//sys" + and read like func declarations if //sys is replaced by func, but: + * The parameter lists must give a name for each argument. + This includes return parameters. + * The parameter lists must give a type for each argument: + the (x, y, z int) shorthand is not allowed. + * If the return parameter is an error number, it must be named err. + * If go func name needs to be different than its libc name, + * or the function is not in libc, name could be specified + * at the end, after "=" sign, like + //sys getsockopt(s int, level int, name int, val uintptr, vallen *_Socklen) (err error) = libsocket.getsockopt +*/ + +package main + +import ( + "bufio" + "flag" + "fmt" + "os" + "regexp" + "strings" +) + +var ( + b32 = flag.Bool("b32", false, "32bit big-endian") + l32 = flag.Bool("l32", false, "32bit little-endian") + tags = flag.String("tags", "", "build tags") +) + +// cmdLine returns this programs's commandline arguments +func cmdLine() string { + return "go run mksyscall_solaris.go " + strings.Join(os.Args[1:], " ") +} + +// buildTags returns build tags +func buildTags() string { + return *tags +} + +// Param is function parameter +type Param struct { + Name string + Type string +} + +// usage prints the program usage +func usage() { + fmt.Fprintf(os.Stderr, "usage: go run mksyscall_solaris.go [-b32 | -l32] [-tags x,y] [file ...]\n") + os.Exit(1) +} + +// parseParamList parses parameter list and returns a slice of parameters +func parseParamList(list string) []string { + list = strings.TrimSpace(list) + if list == "" { + return []string{} + } + return regexp.MustCompile(`\s*,\s*`).Split(list, -1) +} + +// parseParam splits a parameter into name and type +func parseParam(p string) Param { + ps := regexp.MustCompile(`^(\S*) (\S*)$`).FindStringSubmatch(p) + if ps == nil { + fmt.Fprintf(os.Stderr, "malformed parameter: %s\n", p) + os.Exit(1) + } + return Param{ps[1], ps[2]} +} + +func main() { + flag.Usage = usage + flag.Parse() + if len(flag.Args()) <= 0 { + fmt.Fprintf(os.Stderr, "no files to parse provided\n") + usage() + } + + endianness := "" + if *b32 { + endianness = "big-endian" + } else if *l32 { + endianness = "little-endian" + } + + pack := "" + text := "" + dynimports := "" + linknames := "" + var vars []string + for _, path := range flag.Args() { + file, err := os.Open(path) + if err != nil { + fmt.Fprintf(os.Stderr, err.Error()) + os.Exit(1) + } + s := bufio.NewScanner(file) + for s.Scan() { + t := s.Text() + t = strings.TrimSpace(t) + t = regexp.MustCompile(`\s+`).ReplaceAllString(t, ` `) + if p := regexp.MustCompile(`^package (\S+)$`).FindStringSubmatch(t); p != nil && pack == "" { + pack = p[1] + } + nonblock := regexp.MustCompile(`^\/\/sysnb `).FindStringSubmatch(t) + if regexp.MustCompile(`^\/\/sys `).FindStringSubmatch(t) == nil && nonblock == nil { + continue + } + + // Line must be of the form + // func Open(path string, mode int, perm int) (fd int, err error) + // Split into name, in params, out params. + f := regexp.MustCompile(`^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*(?:(\w*)\.)?(\w*))?$`).FindStringSubmatch(t) + if f == nil { + fmt.Fprintf(os.Stderr, "%s:%s\nmalformed //sys declaration\n", path, t) + os.Exit(1) + } + funct, inps, outps, modname, sysname := f[2], f[3], f[4], f[5], f[6] + + // Split argument lists on comma. + in := parseParamList(inps) + out := parseParamList(outps) + + inps = strings.Join(in, ", ") + outps = strings.Join(out, ", ") + + // Try in vain to keep people from editing this file. + // The theory is that they jump into the middle of the file + // without reading the header. + text += "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n" + + // So file name. + if modname == "" { + modname = "libc" + } + + // System call name. + if sysname == "" { + sysname = funct + } + + // System call pointer variable name. + sysvarname := fmt.Sprintf("proc%s", sysname) + + strconvfunc := "BytePtrFromString" + strconvtype := "*byte" + + sysname = strings.ToLower(sysname) // All libc functions are lowercase. + + // Runtime import of function to allow cross-platform builds. + dynimports += fmt.Sprintf("//go:cgo_import_dynamic libc_%s %s \"%s.so\"\n", sysname, sysname, modname) + // Link symbol to proc address variable. + linknames += fmt.Sprintf("//go:linkname %s libc_%s\n", sysvarname, sysname) + // Library proc address variable. + vars = append(vars, sysvarname) + + // Go function header. + outlist := strings.Join(out, ", ") + if outlist != "" { + outlist = fmt.Sprintf(" (%s)", outlist) + } + if text != "" { + text += "\n" + } + text += fmt.Sprintf("func %s(%s)%s {\n", funct, strings.Join(in, ", "), outlist) + + // Check if err return available + errvar := "" + for _, param := range out { + p := parseParam(param) + if p.Type == "error" { + errvar = p.Name + continue + } + } + + // Prepare arguments to Syscall. + var args []string + n := 0 + for _, param := range in { + p := parseParam(param) + if regexp.MustCompile(`^\*`).FindStringSubmatch(p.Type) != nil { + args = append(args, "uintptr(unsafe.Pointer("+p.Name+"))") + } else if p.Type == "string" && errvar != "" { + text += fmt.Sprintf("\tvar _p%d %s\n", n, strconvtype) + text += fmt.Sprintf("\t_p%d, %s = %s(%s)\n", n, errvar, strconvfunc, p.Name) + text += fmt.Sprintf("\tif %s != nil {\n\t\treturn\n\t}\n", errvar) + args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n)) + n++ + } else if p.Type == "string" { + fmt.Fprintf(os.Stderr, path+":"+funct+" uses string arguments, but has no error return\n") + text += fmt.Sprintf("\tvar _p%d %s\n", n, strconvtype) + text += fmt.Sprintf("\t_p%d, _ = %s(%s)\n", n, strconvfunc, p.Name) + args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n)) + n++ + } else if s := regexp.MustCompile(`^\[\](.*)`).FindStringSubmatch(p.Type); s != nil { + // Convert slice into pointer, length. + // Have to be careful not to take address of &a[0] if len == 0: + // pass nil in that case. + text += fmt.Sprintf("\tvar _p%d *%s\n", n, s[1]) + text += fmt.Sprintf("\tif len(%s) > 0 {\n\t\t_p%d = &%s[0]\n\t}\n", p.Name, n, p.Name) + args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n), fmt.Sprintf("uintptr(len(%s))", p.Name)) + n++ + } else if p.Type == "int64" && endianness != "" { + if endianness == "big-endian" { + args = append(args, fmt.Sprintf("uintptr(%s>>32)", p.Name), fmt.Sprintf("uintptr(%s)", p.Name)) + } else { + args = append(args, fmt.Sprintf("uintptr(%s)", p.Name), fmt.Sprintf("uintptr(%s>>32)", p.Name)) + } + } else if p.Type == "bool" { + text += fmt.Sprintf("\tvar _p%d uint32\n", n) + text += fmt.Sprintf("\tif %s {\n\t\t_p%d = 1\n\t} else {\n\t\t_p%d = 0\n\t}\n", p.Name, n, n) + args = append(args, fmt.Sprintf("uintptr(_p%d)", n)) + n++ + } else { + args = append(args, fmt.Sprintf("uintptr(%s)", p.Name)) + } + } + nargs := len(args) + + // Determine which form to use; pad args with zeros. + asm := "sysvicall6" + if nonblock != nil { + asm = "rawSysvicall6" + } + if len(args) <= 6 { + for len(args) < 6 { + args = append(args, "0") + } + } else { + fmt.Fprintf(os.Stderr, "%s: too many arguments to system call\n", path) + os.Exit(1) + } + + // Actual call. + arglist := strings.Join(args, ", ") + call := fmt.Sprintf("%s(uintptr(unsafe.Pointer(&%s)), %d, %s)", asm, sysvarname, nargs, arglist) + + // Assign return values. + body := "" + ret := []string{"_", "_", "_"} + doErrno := false + for i := 0; i < len(out); i++ { + p := parseParam(out[i]) + reg := "" + if p.Name == "err" { + reg = "e1" + ret[2] = reg + doErrno = true + } else { + reg = fmt.Sprintf("r%d", i) + ret[i] = reg + } + if p.Type == "bool" { + reg = fmt.Sprintf("%d != 0", reg) + } + if p.Type == "int64" && endianness != "" { + // 64-bit number in r1:r0 or r0:r1. + if i+2 > len(out) { + fmt.Fprintf(os.Stderr, "%s: not enough registers for int64 return\n", path) + os.Exit(1) + } + if endianness == "big-endian" { + reg = fmt.Sprintf("int64(r%d)<<32 | int64(r%d)", i, i+1) + } else { + reg = fmt.Sprintf("int64(r%d)<<32 | int64(r%d)", i+1, i) + } + ret[i] = fmt.Sprintf("r%d", i) + ret[i+1] = fmt.Sprintf("r%d", i+1) + } + if reg != "e1" { + body += fmt.Sprintf("\t%s = %s(%s)\n", p.Name, p.Type, reg) + } + } + if ret[0] == "_" && ret[1] == "_" && ret[2] == "_" { + text += fmt.Sprintf("\t%s\n", call) + } else { + text += fmt.Sprintf("\t%s, %s, %s := %s\n", ret[0], ret[1], ret[2], call) + } + text += body + + if doErrno { + text += "\tif e1 != 0 {\n" + text += "\t\terr = e1\n" + text += "\t}\n" + } + text += "\treturn\n" + text += "}\n" + } + if err := s.Err(); err != nil { + fmt.Fprintf(os.Stderr, err.Error()) + os.Exit(1) + } + file.Close() + } + imp := "" + if pack != "unix" { + imp = "import \"golang.org/x/sys/unix\"\n" + + } + vardecls := "\t" + strings.Join(vars, ",\n\t") + vardecls += " syscallFunc" + fmt.Printf(srcTemplate, cmdLine(), buildTags(), pack, imp, dynimports, linknames, vardecls, text) +} + +const srcTemplate = `// %s +// Code generated by the command above; see README.md. DO NOT EDIT. + +// +build %s + +package %s + +import ( + "syscall" + "unsafe" +) +%s +%s +%s +var ( +%s +) + +%s +` diff --git a/vendor/golang.org/x/sys/unix/mksyscall_solaris.pl b/vendor/golang.org/x/sys/unix/mksyscall_solaris.pl deleted file mode 100755 index a354df5a6..000000000 --- a/vendor/golang.org/x/sys/unix/mksyscall_solaris.pl +++ /dev/null @@ -1,294 +0,0 @@ -#!/usr/bin/env perl -# Copyright 2009 The Go Authors. All rights reserved. -# Use of this source code is governed by a BSD-style -# license that can be found in the LICENSE file. - -# This program reads a file containing function prototypes -# (like syscall_solaris.go) and generates system call bodies. -# The prototypes are marked by lines beginning with "//sys" -# and read like func declarations if //sys is replaced by func, but: -# * The parameter lists must give a name for each argument. -# This includes return parameters. -# * The parameter lists must give a type for each argument: -# the (x, y, z int) shorthand is not allowed. -# * If the return parameter is an error number, it must be named err. -# * If go func name needs to be different than its libc name, -# * or the function is not in libc, name could be specified -# * at the end, after "=" sign, like -# //sys getsockopt(s int, level int, name int, val uintptr, vallen *_Socklen) (err error) = libsocket.getsockopt - -use strict; - -my $cmdline = "mksyscall_solaris.pl " . join(' ', @ARGV); -my $errors = 0; -my $_32bit = ""; -my $tags = ""; # build tags - -binmode STDOUT; - -if($ARGV[0] eq "-b32") { - $_32bit = "big-endian"; - shift; -} elsif($ARGV[0] eq "-l32") { - $_32bit = "little-endian"; - shift; -} -if($ARGV[0] eq "-tags") { - shift; - $tags = $ARGV[0]; - shift; -} - -if($ARGV[0] =~ /^-/) { - print STDERR "usage: mksyscall_solaris.pl [-b32 | -l32] [-tags x,y] [file ...]\n"; - exit 1; -} - -sub parseparamlist($) { - my ($list) = @_; - $list =~ s/^\s*//; - $list =~ s/\s*$//; - if($list eq "") { - return (); - } - return split(/\s*,\s*/, $list); -} - -sub parseparam($) { - my ($p) = @_; - if($p !~ /^(\S*) (\S*)$/) { - print STDERR "$ARGV:$.: malformed parameter: $p\n"; - $errors = 1; - return ("xx", "int"); - } - return ($1, $2); -} - -my $package = ""; -my $text = ""; -my $dynimports = ""; -my $linknames = ""; -my @vars = (); -while(<>) { - chomp; - s/\s+/ /g; - s/^\s+//; - s/\s+$//; - $package = $1 if !$package && /^package (\S+)$/; - my $nonblock = /^\/\/sysnb /; - next if !/^\/\/sys / && !$nonblock; - - # Line must be of the form - # func Open(path string, mode int, perm int) (fd int, err error) - # Split into name, in params, out params. - if(!/^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*(?:(\w*)\.)?(\w*))?$/) { - print STDERR "$ARGV:$.: malformed //sys declaration\n"; - $errors = 1; - next; - } - my ($nb, $func, $in, $out, $modname, $sysname) = ($1, $2, $3, $4, $5, $6); - - # Split argument lists on comma. - my @in = parseparamlist($in); - my @out = parseparamlist($out); - - # Try in vain to keep people from editing this file. - # The theory is that they jump into the middle of the file - # without reading the header. - $text .= "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n"; - - # So file name. - if($modname eq "") { - $modname = "libc"; - } - - # System call name. - if($sysname eq "") { - $sysname = "$func"; - } - - # System call pointer variable name. - my $sysvarname = "proc$sysname"; - - my $strconvfunc = "BytePtrFromString"; - my $strconvtype = "*byte"; - - $sysname =~ y/A-Z/a-z/; # All libc functions are lowercase. - - # Runtime import of function to allow cross-platform builds. - $dynimports .= "//go:cgo_import_dynamic libc_${sysname} ${sysname} \"$modname.so\"\n"; - # Link symbol to proc address variable. - $linknames .= "//go:linkname ${sysvarname} libc_${sysname}\n"; - # Library proc address variable. - push @vars, $sysvarname; - - # Go function header. - $out = join(', ', @out); - if($out ne "") { - $out = " ($out)"; - } - if($text ne "") { - $text .= "\n" - } - $text .= sprintf "func %s(%s)%s {\n", $func, join(', ', @in), $out; - - # Check if err return available - my $errvar = ""; - foreach my $p (@out) { - my ($name, $type) = parseparam($p); - if($type eq "error") { - $errvar = $name; - last; - } - } - - # Prepare arguments to Syscall. - my @args = (); - my $n = 0; - foreach my $p (@in) { - my ($name, $type) = parseparam($p); - if($type =~ /^\*/) { - push @args, "uintptr(unsafe.Pointer($name))"; - } elsif($type eq "string" && $errvar ne "") { - $text .= "\tvar _p$n $strconvtype\n"; - $text .= "\t_p$n, $errvar = $strconvfunc($name)\n"; - $text .= "\tif $errvar != nil {\n\t\treturn\n\t}\n"; - push @args, "uintptr(unsafe.Pointer(_p$n))"; - $n++; - } elsif($type eq "string") { - print STDERR "$ARGV:$.: $func uses string arguments, but has no error return\n"; - $text .= "\tvar _p$n $strconvtype\n"; - $text .= "\t_p$n, _ = $strconvfunc($name)\n"; - push @args, "uintptr(unsafe.Pointer(_p$n))"; - $n++; - } elsif($type =~ /^\[\](.*)/) { - # Convert slice into pointer, length. - # Have to be careful not to take address of &a[0] if len == 0: - # pass nil in that case. - $text .= "\tvar _p$n *$1\n"; - $text .= "\tif len($name) > 0 {\n\t\t_p$n = \&$name\[0]\n\t}\n"; - push @args, "uintptr(unsafe.Pointer(_p$n))", "uintptr(len($name))"; - $n++; - } elsif($type eq "int64" && $_32bit ne "") { - if($_32bit eq "big-endian") { - push @args, "uintptr($name >> 32)", "uintptr($name)"; - } else { - push @args, "uintptr($name)", "uintptr($name >> 32)"; - } - } elsif($type eq "bool") { - $text .= "\tvar _p$n uint32\n"; - $text .= "\tif $name {\n\t\t_p$n = 1\n\t} else {\n\t\t_p$n = 0\n\t}\n"; - push @args, "uintptr(_p$n)"; - $n++; - } else { - push @args, "uintptr($name)"; - } - } - my $nargs = @args; - - # Determine which form to use; pad args with zeros. - my $asm = "sysvicall6"; - if ($nonblock) { - $asm = "rawSysvicall6"; - } - if(@args <= 6) { - while(@args < 6) { - push @args, "0"; - } - } else { - print STDERR "$ARGV:$.: too many arguments to system call\n"; - } - - # Actual call. - my $args = join(', ', @args); - my $call = "$asm(uintptr(unsafe.Pointer(&$sysvarname)), $nargs, $args)"; - - # Assign return values. - my $body = ""; - my $failexpr = ""; - my @ret = ("_", "_", "_"); - my @pout= (); - my $do_errno = 0; - for(my $i=0; $i<@out; $i++) { - my $p = $out[$i]; - my ($name, $type) = parseparam($p); - my $reg = ""; - if($name eq "err") { - $reg = "e1"; - $ret[2] = $reg; - $do_errno = 1; - } else { - $reg = sprintf("r%d", $i); - $ret[$i] = $reg; - } - if($type eq "bool") { - $reg = "$reg != 0"; - } - if($type eq "int64" && $_32bit ne "") { - # 64-bit number in r1:r0 or r0:r1. - if($i+2 > @out) { - print STDERR "$ARGV:$.: not enough registers for int64 return\n"; - } - if($_32bit eq "big-endian") { - $reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i, $i+1); - } else { - $reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i+1, $i); - } - $ret[$i] = sprintf("r%d", $i); - $ret[$i+1] = sprintf("r%d", $i+1); - } - if($reg ne "e1") { - $body .= "\t$name = $type($reg)\n"; - } - } - if ($ret[0] eq "_" && $ret[1] eq "_" && $ret[2] eq "_") { - $text .= "\t$call\n"; - } else { - $text .= "\t$ret[0], $ret[1], $ret[2] := $call\n"; - } - $text .= $body; - - if ($do_errno) { - $text .= "\tif e1 != 0 {\n"; - $text .= "\t\terr = e1\n"; - $text .= "\t}\n"; - } - $text .= "\treturn\n"; - $text .= "}\n"; -} - -if($errors) { - exit 1; -} - -print <