more vendoring

This commit is contained in:
Jeromy
2015-11-15 11:56:01 -08:00
parent e142795053
commit 216db146ca
146 changed files with 8557 additions and 79 deletions

View File

@@ -9,13 +9,13 @@ import (
"sync" "sync"
"time" "time"
ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
manet "QmanZCL6SXRfafiUEMCBLq2QR171uQSdXQ8YAdHXLd8Cwr/go-multiaddr-net"
"github.com/cryptix/mdns" "github.com/cryptix/mdns"
ma "github.com/jbenet/go-multiaddr"
manet "github.com/jbenet/go-multiaddr-net"
logging "QmWRypnfEwrgH4k93KEHN5hng7VjKYkWmzDYRuTZeh2Mgh/go-log"
"github.com/ipfs/go-libp2p/p2p/host" "github.com/ipfs/go-libp2p/p2p/host"
"github.com/ipfs/go-libp2p/p2p/peer" "github.com/ipfs/go-libp2p/p2p/peer"
logging "QmWRypnfEwrgH4k93KEHN5hng7VjKYkWmzDYRuTZeh2Mgh/go-log"
) )
var log = logging.Logger("mdns") var log = logging.Logger("mdns")

View File

@@ -4,9 +4,9 @@ import (
"io" "io"
logging "QmWRypnfEwrgH4k93KEHN5hng7VjKYkWmzDYRuTZeh2Mgh/go-log" logging "QmWRypnfEwrgH4k93KEHN5hng7VjKYkWmzDYRuTZeh2Mgh/go-log"
ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
metrics "github.com/ipfs/go-libp2p/p2p/metrics" metrics "github.com/ipfs/go-libp2p/p2p/metrics"
mstream "github.com/ipfs/go-libp2p/p2p/metrics/stream" mstream "github.com/ipfs/go-libp2p/p2p/metrics/stream"
ma "github.com/jbenet/go-multiaddr"
goprocess "github.com/jbenet/goprocess" goprocess "github.com/jbenet/goprocess"
context "golang.org/x/net/context" context "golang.org/x/net/context"

View File

@@ -3,7 +3,7 @@ package basichost
import ( import (
"sync" "sync"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
goprocess "github.com/jbenet/goprocess" goprocess "github.com/jbenet/goprocess"
context "golang.org/x/net/context" context "golang.org/x/net/context"

View File

@@ -2,11 +2,11 @@ package host
import ( import (
logging "QmWRypnfEwrgH4k93KEHN5hng7VjKYkWmzDYRuTZeh2Mgh/go-log" logging "QmWRypnfEwrgH4k93KEHN5hng7VjKYkWmzDYRuTZeh2Mgh/go-log"
ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
metrics "github.com/ipfs/go-libp2p/p2p/metrics" metrics "github.com/ipfs/go-libp2p/p2p/metrics"
inet "github.com/ipfs/go-libp2p/p2p/net" inet "github.com/ipfs/go-libp2p/p2p/net"
peer "github.com/ipfs/go-libp2p/p2p/peer" peer "github.com/ipfs/go-libp2p/p2p/peer"
protocol "github.com/ipfs/go-libp2p/p2p/protocol" protocol "github.com/ipfs/go-libp2p/p2p/protocol"
ma "github.com/jbenet/go-multiaddr"
context "golang.org/x/net/context" context "golang.org/x/net/context"
msmux "github.com/whyrusleeping/go-multistream" msmux "github.com/whyrusleeping/go-multistream"

View File

@@ -5,7 +5,7 @@ import (
"time" "time"
logging "QmWRypnfEwrgH4k93KEHN5hng7VjKYkWmzDYRuTZeh2Mgh/go-log" logging "QmWRypnfEwrgH4k93KEHN5hng7VjKYkWmzDYRuTZeh2Mgh/go-log"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
context "golang.org/x/net/context" context "golang.org/x/net/context"
lgbl "util/eventlog/loggables" lgbl "util/eventlog/loggables"

View File

@@ -8,14 +8,14 @@ import (
"sync" "sync"
"time" "time"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
manet "github.com/jbenet/go-multiaddr-net" manet "QmanZCL6SXRfafiUEMCBLq2QR171uQSdXQ8YAdHXLd8Cwr/go-multiaddr-net"
logging "QmWRypnfEwrgH4k93KEHN5hng7VjKYkWmzDYRuTZeh2Mgh/go-log"
nat "github.com/fd/go-nat" nat "github.com/fd/go-nat"
goprocess "github.com/jbenet/goprocess" goprocess "github.com/jbenet/goprocess"
periodic "github.com/jbenet/goprocess/periodic" periodic "github.com/jbenet/goprocess/periodic"
notifier "thirdparty/notifier" notifier "thirdparty/notifier"
logging "QmWRypnfEwrgH4k93KEHN5hng7VjKYkWmzDYRuTZeh2Mgh/go-log"
) )
var ( var (

View File

@@ -6,15 +6,15 @@ import (
"net" "net"
"time" "time"
mpool "github.com/jbenet/go-msgio/mpool" logging "QmWRypnfEwrgH4k93KEHN5hng7VjKYkWmzDYRuTZeh2Mgh/go-log"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
manet "github.com/jbenet/go-multiaddr-net" manet "QmanZCL6SXRfafiUEMCBLq2QR171uQSdXQ8YAdHXLd8Cwr/go-multiaddr-net"
context "golang.org/x/net/context"
ic "github.com/ipfs/go-libp2p/p2p/crypto" ic "github.com/ipfs/go-libp2p/p2p/crypto"
peer "github.com/ipfs/go-libp2p/p2p/peer" peer "github.com/ipfs/go-libp2p/p2p/peer"
mpool "github.com/jbenet/go-msgio/mpool"
context "golang.org/x/net/context"
u "util" u "util"
lgbl "util/eventlog/loggables" lgbl "util/eventlog/loggables"
logging "QmWRypnfEwrgH4k93KEHN5hng7VjKYkWmzDYRuTZeh2Mgh/go-log"
) )
var log = logging.Logger("conn") var log = logging.Logger("conn")

View File

@@ -5,8 +5,8 @@ import (
"math/rand" "math/rand"
"strings" "strings"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
manet "github.com/jbenet/go-multiaddr-net" manet "QmanZCL6SXRfafiUEMCBLq2QR171uQSdXQ8YAdHXLd8Cwr/go-multiaddr-net"
context "golang.org/x/net/context" context "golang.org/x/net/context"
lgbl "util/eventlog/loggables" lgbl "util/eventlog/loggables"

View File

@@ -13,7 +13,7 @@ import (
peer "github.com/ipfs/go-libp2p/p2p/peer" peer "github.com/ipfs/go-libp2p/p2p/peer"
tu "util/testutil" tu "util/testutil"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
context "golang.org/x/net/context" context "golang.org/x/net/context"
) )

View File

@@ -10,7 +10,7 @@ import (
transport "github.com/ipfs/go-libp2p/p2p/net/transport" transport "github.com/ipfs/go-libp2p/p2p/net/transport"
peer "github.com/ipfs/go-libp2p/p2p/peer" peer "github.com/ipfs/go-libp2p/p2p/peer"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
) )
type PeerConn interface { type PeerConn interface {

View File

@@ -5,7 +5,7 @@ import (
"io" "io"
"net" "net"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
tec "github.com/jbenet/go-temp-err-catcher" tec "github.com/jbenet/go-temp-err-catcher"
"github.com/jbenet/goprocess" "github.com/jbenet/goprocess"
goprocessctx "github.com/jbenet/goprocess/context" goprocessctx "github.com/jbenet/goprocess/context"

View File

@@ -5,7 +5,7 @@ import (
"net" "net"
"time" "time"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
context "golang.org/x/net/context" context "golang.org/x/net/context"
ic "github.com/ipfs/go-libp2p/p2p/crypto" ic "github.com/ipfs/go-libp2p/p2p/crypto"

View File

@@ -5,8 +5,8 @@ import (
"strings" "strings"
"sync" "sync"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
manet "github.com/jbenet/go-multiaddr-net" manet "QmanZCL6SXRfafiUEMCBLq2QR171uQSdXQ8YAdHXLd8Cwr/go-multiaddr-net"
) )
type Filters struct { type Filters struct {

View File

@@ -6,7 +6,7 @@ import (
conn "github.com/ipfs/go-libp2p/p2p/net/conn" conn "github.com/ipfs/go-libp2p/p2p/net/conn"
peer "github.com/ipfs/go-libp2p/p2p/peer" peer "github.com/ipfs/go-libp2p/p2p/peer"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
"github.com/jbenet/goprocess" "github.com/jbenet/goprocess"
context "golang.org/x/net/context" context "golang.org/x/net/context"
) )

View File

@@ -14,7 +14,7 @@ import (
"io" "io"
"time" "time"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
) )
type Mocknet interface { type Mocknet interface {

View File

@@ -8,7 +8,7 @@ import (
inet "github.com/ipfs/go-libp2p/p2p/net" inet "github.com/ipfs/go-libp2p/p2p/net"
peer "github.com/ipfs/go-libp2p/p2p/peer" peer "github.com/ipfs/go-libp2p/p2p/peer"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
process "github.com/jbenet/goprocess" process "github.com/jbenet/goprocess"
) )

View File

@@ -13,7 +13,7 @@ import (
p2putil "github.com/ipfs/go-libp2p/p2p/test/util" p2putil "github.com/ipfs/go-libp2p/p2p/test/util"
testutil "util/testutil" testutil "util/testutil"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
"github.com/jbenet/goprocess" "github.com/jbenet/goprocess"
goprocessctx "github.com/jbenet/goprocess/context" goprocessctx "github.com/jbenet/goprocess/context"
context "golang.org/x/net/context" context "golang.org/x/net/context"

View File

@@ -4,10 +4,10 @@ import (
"testing" "testing"
"time" "time"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
context "golang.org/x/net/context"
inet "github.com/ipfs/go-libp2p/p2p/net" inet "github.com/ipfs/go-libp2p/p2p/net"
peer "github.com/ipfs/go-libp2p/p2p/peer" peer "github.com/ipfs/go-libp2p/p2p/peer"
context "golang.org/x/net/context"
) )
func TestNotifications(t *testing.T) { func TestNotifications(t *testing.T) {

View File

@@ -8,7 +8,7 @@ import (
inet "github.com/ipfs/go-libp2p/p2p/net" inet "github.com/ipfs/go-libp2p/p2p/net"
peer "github.com/ipfs/go-libp2p/p2p/peer" peer "github.com/ipfs/go-libp2p/p2p/peer"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
"github.com/jbenet/goprocess" "github.com/jbenet/goprocess"
goprocessctx "github.com/jbenet/goprocess/context" goprocessctx "github.com/jbenet/goprocess/context"
context "golang.org/x/net/context" context "golang.org/x/net/context"

View File

@@ -5,8 +5,8 @@ import (
logging "QmWRypnfEwrgH4k93KEHN5hng7VjKYkWmzDYRuTZeh2Mgh/go-log" logging "QmWRypnfEwrgH4k93KEHN5hng7VjKYkWmzDYRuTZeh2Mgh/go-log"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
manet "github.com/jbenet/go-multiaddr-net" manet "QmanZCL6SXRfafiUEMCBLq2QR171uQSdXQ8YAdHXLd8Cwr/go-multiaddr-net"
context "golang.org/x/net/context" context "golang.org/x/net/context"
) )

View File

@@ -3,8 +3,8 @@ package addrutil
import ( import (
"testing" "testing"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
manet "github.com/jbenet/go-multiaddr-net" manet "QmanZCL6SXRfafiUEMCBLq2QR171uQSdXQ8YAdHXLd8Cwr/go-multiaddr-net"
) )
func newMultiaddr(t *testing.T, s string) ma.Multiaddr { func newMultiaddr(t *testing.T, s string) ma.Multiaddr {

View File

@@ -13,8 +13,8 @@ import (
testutil "util/testutil" testutil "util/testutil"
ci "util/testutil/ci" ci "util/testutil/ci"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
manet "github.com/jbenet/go-multiaddr-net" manet "QmanZCL6SXRfafiUEMCBLq2QR171uQSdXQ8YAdHXLd8Cwr/go-multiaddr-net"
context "golang.org/x/net/context" context "golang.org/x/net/context"
) )

View File

@@ -5,7 +5,7 @@ import (
peer "github.com/ipfs/go-libp2p/p2p/peer" peer "github.com/ipfs/go-libp2p/p2p/peer"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
context "golang.org/x/net/context" context "golang.org/x/net/context"
) )

View File

@@ -9,7 +9,7 @@ import (
peer "github.com/ipfs/go-libp2p/p2p/peer" peer "github.com/ipfs/go-libp2p/p2p/peer"
ci "util/testutil/ci" ci "util/testutil/ci"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
context "golang.org/x/net/context" context "golang.org/x/net/context"
) )

View File

@@ -16,14 +16,14 @@ import (
transport "github.com/ipfs/go-libp2p/p2p/net/transport" transport "github.com/ipfs/go-libp2p/p2p/net/transport"
peer "github.com/ipfs/go-libp2p/p2p/peer" peer "github.com/ipfs/go-libp2p/p2p/peer"
ma "github.com/jbenet/go-multiaddr" mafilter "QmVdADza4QFVAR9xqAxRQjt9vTZJ6UrVLgBstKua1Xg7he/multiaddr-filter"
ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
ps "github.com/jbenet/go-peerstream" ps "github.com/jbenet/go-peerstream"
pst "github.com/jbenet/go-stream-muxer" pst "github.com/jbenet/go-stream-muxer"
psmss "github.com/jbenet/go-stream-muxer/multistream" psmss "github.com/jbenet/go-stream-muxer/multistream"
"github.com/jbenet/goprocess" "github.com/jbenet/goprocess"
goprocessctx "github.com/jbenet/goprocess/context" goprocessctx "github.com/jbenet/goprocess/context"
prom "github.com/prometheus/client_golang/prometheus" prom "github.com/prometheus/client_golang/prometheus"
mafilter "github.com/whyrusleeping/multiaddr-filter"
context "golang.org/x/net/context" context "golang.org/x/net/context"
logging "QmWRypnfEwrgH4k93KEHN5hng7VjKYkWmzDYRuTZeh2Mgh/go-log" logging "QmWRypnfEwrgH4k93KEHN5hng7VjKYkWmzDYRuTZeh2Mgh/go-log"

View File

@@ -4,7 +4,7 @@ import (
conn "github.com/ipfs/go-libp2p/p2p/net/conn" conn "github.com/ipfs/go-libp2p/p2p/net/conn"
addrutil "github.com/ipfs/go-libp2p/p2p/net/swarm/addr" addrutil "github.com/ipfs/go-libp2p/p2p/net/swarm/addr"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
) )
// ListenAddresses returns a list of addresses at which this swarm listens. // ListenAddresses returns a list of addresses at which this swarm listens.

View File

@@ -8,7 +8,7 @@ import (
peer "github.com/ipfs/go-libp2p/p2p/peer" peer "github.com/ipfs/go-libp2p/p2p/peer"
testutil "util/testutil" testutil "util/testutil"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
context "golang.org/x/net/context" context "golang.org/x/net/context"
) )

View File

@@ -8,7 +8,7 @@ import (
conn "github.com/ipfs/go-libp2p/p2p/net/conn" conn "github.com/ipfs/go-libp2p/p2p/net/conn"
peer "github.com/ipfs/go-libp2p/p2p/peer" peer "github.com/ipfs/go-libp2p/p2p/peer"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
ps "github.com/jbenet/go-peerstream" ps "github.com/jbenet/go-peerstream"
context "golang.org/x/net/context" context "golang.org/x/net/context"
) )

View File

@@ -8,13 +8,13 @@ import (
"sync" "sync"
"time" "time"
"github.com/jbenet/go-multiaddr-net" "QmanZCL6SXRfafiUEMCBLq2QR171uQSdXQ8YAdHXLd8Cwr/go-multiaddr-net"
conn "github.com/ipfs/go-libp2p/p2p/net/conn" conn "github.com/ipfs/go-libp2p/p2p/net/conn"
addrutil "github.com/ipfs/go-libp2p/p2p/net/swarm/addr" addrutil "github.com/ipfs/go-libp2p/p2p/net/swarm/addr"
peer "github.com/ipfs/go-libp2p/p2p/peer" peer "github.com/ipfs/go-libp2p/p2p/peer"
lgbl "util/eventlog/loggables" lgbl "util/eventlog/loggables"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
context "golang.org/x/net/context" context "golang.org/x/net/context"
) )

View File

@@ -9,7 +9,7 @@ import (
transport "github.com/ipfs/go-libp2p/p2p/net/transport" transport "github.com/ipfs/go-libp2p/p2p/net/transport"
lgbl "util/eventlog/loggables" lgbl "util/eventlog/loggables"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
ps "github.com/jbenet/go-peerstream" ps "github.com/jbenet/go-peerstream"
context "golang.org/x/net/context" context "golang.org/x/net/context"
) )

View File

@@ -8,7 +8,7 @@ import (
metrics "github.com/ipfs/go-libp2p/p2p/metrics" metrics "github.com/ipfs/go-libp2p/p2p/metrics"
inet "github.com/ipfs/go-libp2p/p2p/net" inet "github.com/ipfs/go-libp2p/p2p/net"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
"github.com/jbenet/goprocess" "github.com/jbenet/goprocess"
context "golang.org/x/net/context" context "golang.org/x/net/context"
) )

View File

@@ -4,7 +4,7 @@ import (
"testing" "testing"
"time" "time"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
context "golang.org/x/net/context" context "golang.org/x/net/context"
inet "github.com/ipfs/go-libp2p/p2p/net" inet "github.com/ipfs/go-libp2p/p2p/net"

View File

@@ -14,7 +14,7 @@ import (
peer "github.com/ipfs/go-libp2p/p2p/peer" peer "github.com/ipfs/go-libp2p/p2p/peer"
testutil "util/testutil" testutil "util/testutil"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
context "golang.org/x/net/context" context "golang.org/x/net/context"
) )

View File

@@ -6,8 +6,8 @@ import (
"sync" "sync"
"time" "time"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
manet "github.com/jbenet/go-multiaddr-net" manet "QmanZCL6SXRfafiUEMCBLq2QR171uQSdXQ8YAdHXLd8Cwr/go-multiaddr-net"
reuseport "github.com/jbenet/go-reuseport" reuseport "github.com/jbenet/go-reuseport"
context "golang.org/x/net/context" context "golang.org/x/net/context"
lgbl "util/eventlog/loggables" lgbl "util/eventlog/loggables"

View File

@@ -5,8 +5,8 @@ import (
"time" "time"
logging "QmWRypnfEwrgH4k93KEHN5hng7VjKYkWmzDYRuTZeh2Mgh/go-log" logging "QmWRypnfEwrgH4k93KEHN5hng7VjKYkWmzDYRuTZeh2Mgh/go-log"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
manet "github.com/jbenet/go-multiaddr-net" manet "QmanZCL6SXRfafiUEMCBLq2QR171uQSdXQ8YAdHXLd8Cwr/go-multiaddr-net"
) )
var log = logging.Logger("transport") var log = logging.Logger("transport")

View File

@@ -2,7 +2,7 @@
package addr package addr
import ( import (
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
) )
// AddrSource is a source of addresses. It allows clients to retrieve // AddrSource is a source of addresses. It allows clients to retrieve

View File

@@ -4,7 +4,7 @@ import (
"fmt" "fmt"
"testing" "testing"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
) )
func newAddrOrFatal(t *testing.T, s string) ma.Multiaddr { func newAddrOrFatal(t *testing.T, s string) ma.Multiaddr {

View File

@@ -4,7 +4,7 @@ import (
"sync" "sync"
"time" "time"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
) )
const ( const (

View File

@@ -4,7 +4,7 @@ import (
"testing" "testing"
"time" "time"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
) )
func IDS(t *testing.T, ids string) ID { func IDS(t *testing.T, ids string) ID {

View File

@@ -7,9 +7,9 @@ import (
"fmt" "fmt"
"strings" "strings"
b58 "github.com/jbenet/go-base58" b58 "QmNsoHoCVhgXcv1Yg45jtkMgimxorTAN36fV9AQMFXHHAQ/go-base58"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
mh "github.com/jbenet/go-multihash" mh "QmdeauTdyf38KDQB4Cc4CurPWRRb5pej27NCXPA7kbPTJy/go-multihash"
logging "QmWRypnfEwrgH4k93KEHN5hng7VjKYkWmzDYRuTZeh2Mgh/go-log" logging "QmWRypnfEwrgH4k93KEHN5hng7VjKYkWmzDYRuTZeh2Mgh/go-log"
ic "github.com/ipfs/go-libp2p/p2p/crypto" ic "github.com/ipfs/go-libp2p/p2p/crypto"

View File

@@ -11,7 +11,7 @@ import (
u "util" u "util"
tu "util/testutil" tu "util/testutil"
b58 "github.com/jbenet/go-base58" b58 "QmNsoHoCVhgXcv1Yg45jtkMgimxorTAN36fV9AQMFXHHAQ/go-base58"
) )
var gen1 keyset // generated var gen1 keyset // generated

View File

@@ -7,9 +7,9 @@ import (
ic "github.com/ipfs/go-libp2p/p2p/crypto" ic "github.com/ipfs/go-libp2p/p2p/crypto"
ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
ds "github.com/jbenet/go-datastore" ds "github.com/jbenet/go-datastore"
dssync "github.com/jbenet/go-datastore/sync" dssync "github.com/jbenet/go-datastore/sync"
ma "github.com/jbenet/go-multiaddr"
) )
const ( const (

View File

@@ -7,7 +7,6 @@ import (
"time" "time"
peer "github.com/ipfs/go-libp2p/p2p/peer" peer "github.com/ipfs/go-libp2p/p2p/peer"
key "github.com/whyrusleeping/go-key"
u "util" u "util"
context "golang.org/x/net/context" context "golang.org/x/net/context"
@@ -28,7 +27,7 @@ func TestQueue(t *testing.T) {
// [78 135 26 216 178 181 224 181 234 117 2 248 152 115 255 103 244 34 4 152 193 88 9 225 8 127 216 158 226 8 236 246] // [78 135 26 216 178 181 224 181 234 117 2 248 152 115 255 103 244 34 4 152 193 88 9 225 8 127 216 158 226 8 236 246]
// [125 135 124 6 226 160 101 94 192 57 39 12 18 79 121 140 190 154 147 55 44 83 101 151 63 255 94 179 51 203 241 51] // [125 135 124 6 226 160 101 94 192 57 39 12 18 79 121 140 190 154 147 55 44 83 101 151 63 255 94 179 51 203 241 51]
pq := NewXORDistancePQ(key.Key("11140beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a31")) pq := NewXORDistancePQ("11140beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a31")
pq.Enqueue(p3) pq.Enqueue(p3)
pq.Enqueue(p1) pq.Enqueue(p1)
pq.Enqueue(p2) pq.Enqueue(p2)
@@ -82,7 +81,7 @@ func TestSyncQueue(t *testing.T) {
} }
ctx := context.Background() ctx := context.Background()
pq := NewXORDistancePQ(key.Key("11140beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a31")) pq := NewXORDistancePQ("11140beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a31")
cq := NewChanQueue(ctx, pq) cq := NewChanQueue(ctx, pq)
wg := sync.WaitGroup{} wg := sync.WaitGroup{}

View File

@@ -4,9 +4,9 @@ import (
"strings" "strings"
"sync" "sync"
ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
semver "github.com/coreos/go-semver/semver" semver "github.com/coreos/go-semver/semver"
ggio "github.com/gogo/protobuf/io" ggio "github.com/gogo/protobuf/io"
ma "github.com/jbenet/go-multiaddr"
msmux "github.com/whyrusleeping/go-multistream" msmux "github.com/whyrusleeping/go-multistream"
context "golang.org/x/net/context" context "golang.org/x/net/context"

View File

@@ -9,7 +9,7 @@ import (
identify "github.com/ipfs/go-libp2p/p2p/protocol/identify" identify "github.com/ipfs/go-libp2p/p2p/protocol/identify"
testutil "github.com/ipfs/go-libp2p/p2p/test/util" testutil "github.com/ipfs/go-libp2p/p2p/test/util"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
context "golang.org/x/net/context" context "golang.org/x/net/context"
) )

View File

@@ -6,7 +6,7 @@ import (
peer "github.com/ipfs/go-libp2p/p2p/peer" peer "github.com/ipfs/go-libp2p/p2p/peer"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
) )
// ObservedAddr is an entry for an address reported by our peers. // ObservedAddr is an entry for an address reported by our peers.

View File

@@ -4,7 +4,7 @@ import (
"testing" "testing"
"time" "time"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
) )
// TestObsAddrSet // TestObsAddrSet

View File

@@ -4,13 +4,13 @@ import (
"fmt" "fmt"
"io" "io"
mh "github.com/jbenet/go-multihash" mh "QmdeauTdyf38KDQB4Cc4CurPWRRb5pej27NCXPA7kbPTJy/go-multihash"
logging "QmWRypnfEwrgH4k93KEHN5hng7VjKYkWmzDYRuTZeh2Mgh/go-log"
host "github.com/ipfs/go-libp2p/p2p/host" host "github.com/ipfs/go-libp2p/p2p/host"
inet "github.com/ipfs/go-libp2p/p2p/net" inet "github.com/ipfs/go-libp2p/p2p/net"
peer "github.com/ipfs/go-libp2p/p2p/peer" peer "github.com/ipfs/go-libp2p/p2p/peer"
protocol "github.com/ipfs/go-libp2p/p2p/protocol" protocol "github.com/ipfs/go-libp2p/p2p/protocol"
logging "QmWRypnfEwrgH4k93KEHN5hng7VjKYkWmzDYRuTZeh2Mgh/go-log"
) )
var log = logging.Logger("github.com/ipfs/go-libp2p/p2p/protocol/relay") var log = logging.Logger("github.com/ipfs/go-libp2p/p2p/protocol/relay")

View File

@@ -5,14 +5,14 @@ import (
"io" "io"
"testing" "testing"
logging "QmWRypnfEwrgH4k93KEHN5hng7VjKYkWmzDYRuTZeh2Mgh/go-log"
u "util" u "util"
testutil "util/testutil" testutil "util/testutil"
logging "QmWRypnfEwrgH4k93KEHN5hng7VjKYkWmzDYRuTZeh2Mgh/go-log"
ic "github.com/ipfs/go-libp2p/p2p/crypto" ic "github.com/ipfs/go-libp2p/p2p/crypto"
peer "github.com/ipfs/go-libp2p/p2p/peer" peer "github.com/ipfs/go-libp2p/p2p/peer"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
) )
var log = logging.Logger("boguskey") var log = logging.Logger("boguskey")

View File

@@ -10,7 +10,7 @@ import (
peer "github.com/ipfs/go-libp2p/p2p/peer" peer "github.com/ipfs/go-libp2p/p2p/peer"
tu "util/testutil" tu "util/testutil"
ma "github.com/jbenet/go-multiaddr" ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
context "golang.org/x/net/context" context "golang.org/x/net/context"
) )

View File

@@ -12,6 +12,16 @@
"name": "go-keyspace", "name": "go-keyspace",
"hash": "Qma4vHVBYKDiKS5VpvtLNJHHDbL7S6VRsvxxmBnBFfKP3k", "hash": "Qma4vHVBYKDiKS5VpvtLNJHHDbL7S6VRsvxxmBnBFfKP3k",
"version": "1.0.0" "version": "1.0.0"
},
{
"name": "go-multiaddr-net",
"hash": "QmanZCL6SXRfafiUEMCBLq2QR171uQSdXQ8YAdHXLd8Cwr",
"version": "1.0.0"
},
{
"name": "multiaddr-filter",
"hash": "QmVdADza4QFVAR9xqAxRQjt9vTZJ6UrVLgBstKua1Xg7he",
"version": "1.0.0"
} }
], ],
"language": "go" "language": "go"

View File

@@ -0,0 +1,13 @@
Copyright (c) 2013 Conformal Systems LLC.
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

View File

@@ -0,0 +1,66 @@
# go-base58
I extracted this package from https://github.com/conformal/btcutil to provide a simple base58 package that
- defaults to base58-check (btc)
- and allows using different alphabets.
## Usage
```go
package main
import (
"fmt"
b58 "github.com/jbenet/go-base58"
)
func main() {
buf := []byte{255, 254, 253, 252}
fmt.Printf("buffer: %v\n", buf)
str := b58.Encode(buf)
fmt.Printf("encoded: %s\n", str)
buf2 := b58.Decode(str)
fmt.Printf("decoded: %v\n", buf2)
}
```
### Another alphabet
```go
package main
import (
"fmt"
b58 "github.com/jbenet/go-base58"
)
const BogusAlphabet = "ZYXWVUTSRQPNMLKJHGFEDCBAzyxwvutsrqponmkjihgfedcba987654321"
func encdec(alphabet string) {
fmt.Printf("using: %s\n", alphabet)
buf := []byte{255, 254, 253, 252}
fmt.Printf("buffer: %v\n", buf)
str := b58.EncodeAlphabet(buf, alphabet)
fmt.Printf("encoded: %s\n", str)
buf2 := b58.DecodeAlphabet(str, alphabet)
fmt.Printf("decoded: %v\n\n", buf2)
}
func main() {
encdec(b58.BTCAlphabet)
encdec(b58.FlickrAlphabet)
encdec(BogusAlphabet)
}
```
## License
Package base58 (and the original btcutil) are licensed under the ISC License.

View File

@@ -0,0 +1,90 @@
// Copyright (c) 2013-2014 Conformal Systems LLC.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
// Modified by Juan Benet (juan@benet.ai)
package base58
import (
"math/big"
"strings"
)
// alphabet is the modified base58 alphabet used by Bitcoin.
const BTCAlphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
const FlickrAlphabet = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
var bigRadix = big.NewInt(58)
var bigZero = big.NewInt(0)
// Decode decodes a modified base58 string to a byte slice, using BTCAlphabet
func Decode(b string) []byte {
return DecodeAlphabet(b, BTCAlphabet)
}
// Encode encodes a byte slice to a modified base58 string, using BTCAlphabet
func Encode(b []byte) string {
return EncodeAlphabet(b, BTCAlphabet)
}
// DecodeAlphabet decodes a modified base58 string to a byte slice, using alphabet.
func DecodeAlphabet(b, alphabet string) []byte {
answer := big.NewInt(0)
j := big.NewInt(1)
for i := len(b) - 1; i >= 0; i-- {
tmp := strings.IndexAny(alphabet, string(b[i]))
if tmp == -1 {
return []byte("")
}
idx := big.NewInt(int64(tmp))
tmp1 := big.NewInt(0)
tmp1.Mul(j, idx)
answer.Add(answer, tmp1)
j.Mul(j, bigRadix)
}
tmpval := answer.Bytes()
var numZeros int
for numZeros = 0; numZeros < len(b); numZeros++ {
if b[numZeros] != alphabet[0] {
break
}
}
flen := numZeros + len(tmpval)
val := make([]byte, flen, flen)
copy(val[numZeros:], tmpval)
return val
}
// Encode encodes a byte slice to a modified base58 string, using alphabet
func EncodeAlphabet(b []byte, alphabet string) string {
x := new(big.Int)
x.SetBytes(b)
answer := make([]byte, 0, len(b)*136/100)
for x.Cmp(bigZero) > 0 {
mod := new(big.Int)
x.DivMod(x, bigRadix, mod)
answer = append(answer, alphabet[mod.Int64()])
}
// leading zero bytes
for _, i := range b {
if i != 0 {
break
}
answer = append(answer, alphabet[0])
}
// reverse
alen := len(answer)
for i := 0; i < alen/2; i++ {
answer[i], answer[alen-1-i] = answer[alen-1-i], answer[i]
}
return string(answer)
}

View File

@@ -0,0 +1,130 @@
// Copyright (c) 2013-2014 Conformal Systems LLC.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package base58
import (
"bytes"
"encoding/hex"
"testing"
)
var stringTests = []struct {
in string
out string
}{
{"", ""},
{" ", "Z"},
{"-", "n"},
{"0", "q"},
{"1", "r"},
{"-1", "4SU"},
{"11", "4k8"},
{"abc", "ZiCa"},
{"1234598760", "3mJr7AoUXx2Wqd"},
{"abcdefghijklmnopqrstuvwxyz", "3yxU3u1igY8WkgtjK92fbJQCd4BZiiT1v25f"},
{"00000000000000000000000000000000000000000000000000000000000000", "3sN2THZeE9Eh9eYrwkvZqNstbHGvrxSAM7gXUXvyFQP8XvQLUqNCS27icwUeDT7ckHm4FUHM2mTVh1vbLmk7y"},
}
var invalidStringTests = []struct {
in string
out string
}{
{"0", ""},
{"O", ""},
{"I", ""},
{"l", ""},
{"3mJr0", ""},
{"O3yxU", ""},
{"3sNI", ""},
{"4kl8", ""},
{"0OIl", ""},
{"!@#$%^&*()-_=+~`", ""},
}
var hexTests = []struct {
in string
out string
}{
{"61", "2g"},
{"626262", "a3gV"},
{"636363", "aPEr"},
{"73696d706c792061206c6f6e6720737472696e67", "2cFupjhnEsSn59qHXstmK2ffpLv2"},
{"00eb15231dfceb60925886b67d065299925915aeb172c06647", "1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L"},
{"516b6fcd0f", "ABnLTmg"},
{"bf4f89001e670274dd", "3SEo3LWLoPntC"},
{"572e4794", "3EFU7m"},
{"ecac89cad93923c02321", "EJDM8drfXA6uyA"},
{"10c8511e", "Rt5zm"},
{"00000000000000000000", "1111111111"},
}
func TestBase58(t *testing.T) {
// Base58Encode tests
for x, test := range stringTests {
tmp := []byte(test.in)
if res := Encode(tmp); res != test.out {
t.Errorf("Base58Encode test #%d failed: got: %s want: %s",
x, res, test.out)
continue
}
}
// Base58Decode tests
for x, test := range hexTests {
b, err := hex.DecodeString(test.in)
if err != nil {
t.Errorf("hex.DecodeString failed failed #%d: got: %s", x, test.in)
continue
}
if res := Decode(test.out); bytes.Equal(res, b) != true {
t.Errorf("Base58Decode test #%d failed: got: %q want: %q",
x, res, test.in)
continue
}
}
// Base58Decode with invalid input
for x, test := range invalidStringTests {
if res := Decode(test.in); string(res) != test.out {
t.Errorf("Base58Decode invalidString test #%d failed: got: %q want: %q",
x, res, test.out)
continue
}
}
}
func BenchmarkDecodeShort(b *testing.B) {
const in = "1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L"
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_ = Decode(in)
}
}
func BenchmarkEncodeShort(b *testing.B) {
var in = []byte("00eb15231dfceb60925886b67d065299925915aeb172c06647")
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_ = Encode(in)
}
}
func BenchmarkDecodeOneKilo(b *testing.B) {
const in = "3GimCffBLAHhXMCeNxX2nST6dBem9pbUi3KVKykW73LmewcFtMk9oh9eNPdNR2eSzNqp7Z3E21vrWUkGHzJ7w2yqDUDJ4LKo1w5D6aafZ4SUoNQyrSVxyVG3pwgoZkKXMZVixRyiPZVUpekrsTvZuUoW7mB6BQgDTXbDuMMSRoNR7yiUTKpgwTD61DLmhNZopNxfFjn4avpYPgzsTB94iWueq1yU3EoruWCUMvp6fc1CEbDrZY3pkx9oUbUaSMC37rruBKSSGHh1ZE3XK3kQXBCFraMmUQf8dagofMEg5aTnDiLAZjLyWJMdnQwW1FqKKztP8KAQS2JX8GCCfc68KB4VGf2CfEGXtaapnsNWFrHuWi7Wo5vqyuHd21zGm1u5rsiR6tKNCsFC4nzf3WUNxJNoZrDSdF9KERqhTWWmmcM4qdKRCtBWKTrs1DJD2oiK6BK9BgwoW2dfQdKuxojFyFvmxqPKDDAEZPPpJ51wHoFzBFMM1tUBBkN15cT2GpNwKzDcjHPKJAQ6FNRgppfQytzqpq76sSeZaWAB8hhULMJCQGU57ZUjvP7xYAQwtACBnYrjdxA91XwXFbq5AsQJwAmLw6euKVWNyv11BuHrejVmnNViWg5kuZBrtgL6NtzRWHtdxngHDMtuyky3brqGXaGQhUyXrkSpeknkkHL6NLThHH5NPnfFMVPwn2xf5UM5R51X2nTBzADSVcpi4cT7i44dT7o3yRKWtKfUzZiuNyTcSSrfH8KVdLap5ZKLmdPuXM65M2Z5wJVh3Uc4iv6iZKk44RKikM7zs1hqC4sBxRwLZjxhKvvMXDjDcYFkzyUkues4y7fjdCnVTxc4vTYUqcbY2k2WMssyj9SDseVc7dVrEvWCLQtYy79mJFoz1Hmsfk5ynE28ipznzQ3yTBugLHA6j6qW3S74eY4pJ6iynFEuXT4RqqkLGFcMh3goqS7CkphUMzP4wuJyGnzqa5tCno4U3dJ2jUL7Povg8voRqYAfiHyXC8zuhn225EdmRcSnu2pAuutQVV9hN3bkjfzAFUhUWKki8SwXtFSjy6NJyrYUiaze4p7ApsjHQBCgg2zAoBaGCwVN8991Jny31B5vPyYHy1oRSE4xTVZ7tTw9FyQ7w9p1NSEF4sziCxZHh5rFWZKAajc5c7KaMNDvHPNV6S62MTFGTyuKPQNbv9yHRGN4eH6SnZGW6snvEVdYCspWZ1U3Nbxo6vCmBK95UyYpcxHgg1CCGdU4s3edju2NDQkMifyPkJdkabzzHVDhJJbChAJc1ACQfNW74VXXwrBZmeZyA2R28MBctDyXuSuffiwueys2LVowLu9wiTHUox7KQjtHK2c9howk9czzx2mpnYzkVYH42CYsWa5514EM4CJEXPJSSbXSgJJ"
b.SetBytes(int64(len(in))) // 1024
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_ = Decode(in)
}
}
func BenchmarkEncodeOneKilo(b *testing.B) {
var in = []byte("\x1f\x8b\x08\x00\x00\x09\x6e\x88\x00\xff\x00\x00\x04\xff\xfb\x63\xc9\x7e\x5f\x97\x68\xe5\x10\x08\xe5\xa5\x9a\x7c\x24\x75\x35\xbe\xaf\x37\x0b\xc3\xf4\x18\x62\x4a\xb7\x18\xd0\x10\x0b\x6b\x62\xe1\x36\x0f\x62\xa6\xeb\x78\xa5\xf3\x33\x52\xbc\xdf\x04\xcb\x37\xcf\x3d\x97\x5c\xb8\x75\x09\x1f\x18\x9f\xfc\xa9\xda\x1e\x59\x77\x09\x9c\x5d\xb6\xf2\x9e\x45\xb7\x5e\x5d\x11\xf1\x20\x14\x85\xf8\x54\x87\x8c\x1e\x2c\x2e\x15\x57\x89\xe7\x5d\x49\xb6\xae\x24\x3a\x20\x50\x0e\xa7\x5b\x10\xbf\x0a\xb4\x01\x42\xed\xce\x2d\x45\x21\xb6\xe8\x64\x73\x4e\x7e\x0a\x36\x1d\x57\x0a\x5e\x1c\x21\xc2\xb8\xe7\x89\x82\xe4\x04\x7e\x50\xff\xda\x4f\xfe\x11\x95\xfb\x35\xf9\x6d\x32\xce\xef\x8f\x3d\x1b\xdb\x38\xfa\xcd\x26\x36\x12\x93\xa0\x96\xea\x42\xbe\xd6\x85\x86\xc1\xc1\xe2\x55\x41\xd1\x7f\x8d\x0e\x00\x81\x58\xb4\x10\xbb\x64\x92\x05\x07\xa9\xd5\xd9\x40\x28\x8b\x9b\x4c\x8d\x8e\x4e\x69\xf9\xc9\x35\xea\xda\x2f\x61\x87\x35\x2d\x6b\x25\x32\xf0\x7e\x89\x1a\xcb\xc0\xea\x66\x88\x99\x39\xe0\x3b\x24\x3b\x05\x74\xd3\x72\xf6\x48\x15\xdc\x02\x0a\xbf\xc8\x49\x42\x10\x22\xeb\xe9\x44\x71\x55\xaf\x67\x67\xe6\x2a\x40\x31\x81\xb9\x6f\x65\x86\x0f\x0f\x9d\x58\x4c\x51\xc1\x2e\x4e\x60\x7e\xe8\x93\x39\x90\xda\xe5\xbe\xec\xe4\xdd\xbc\x1d\xba\x40\xa6\x85\xd9\xb2\xec\xb4\x26\x74\xee\xc1\xec\xe3\x40\xb9\x49\xa3\xe1\x26\x76\x8a\xeb\x95\xc8\x72\xb0\x85\x36\x19\x3f\x55\x06\x7b\xcd\x3e\xd0\xdf\x7e\x8d\x2a\xea\xa6\x24\xc6\xf6\xfb\xda\xe0\x45\xcf\x32\x0e\xbc\xf4\x41\x7d\x71\x3d\x86\xf9\xb4\xaf\x07\xa0\xd1\x34\x8a\x02\x28\x56\xd4\xcc\x36\x44\x98\x44\xcb\x9d\xc5\xfc\x45\x2d\xc4\x5c\xfe\xce\xaa\x44\xda\x66\x52\x2d\x32\x6e\x13\x32\xac\xaf\x13\x72\x87\x79\xd2\x92\x54\x9f\xc7\xb9\xf3\x21\xae\xdd\x69\x44\xe9\x46\x94\x1c\x62\x84\x03\xe0\xbf\x66\xfb\xe0\x79\xf9\x57\x9e\x22\x9e\x23\x2d\x2a\x73\xeb\x74\x38\xf0\xea\x5d\xb3\x8f\x87\x26\x3e\x3c\x54\x11\xb7\x98\xbd\x7f\x78\x64\xa3\xf1\x8f\xa9\x5e\x4f\x18\x3f\xa7\x1f\x3a\x29\x27\x27\xb7\x49\x40\x16\x18\x1f\xd3\xed\x86\x61\xbd\xc3\x4e\x4a\x53\x37\x78\x5c\x00\xd3\x50\x45\x1c\x55\xc0\x9b\xd7\x62\x29\x88\x2e\xa4\x0d\x6a\x15\x6c\x33\x3c\xe7\x31\xfa\xc1\xaf\xdf\x7a\x3e\x37\x3e\xe5\xbc\xfd\xfb\x9b\x72\x10\x35\x90\x25\x6e\x87\x0d\x74\x1c\xfd\xe3\x0b\xee\xf5\x92\x28\x8d\x22\x8a\x49\x7b\xcd\xbb\xd8\x24\x6b\x5e\x58\x40\xec\x1b\x6c\xed\x8e\xcb\x56\x62\xa6\xb4\x42\x3d\x7d\xa2\xef\x27\x27\x46\x50\xbc\x5e\x37\x9b\x27\x72\xf0\xea\xa7\xe7\x4d\xf4\xae\x7e\x95\x8f\x91\x2e\x58\xc4\x6a\x06\xda\x7a\x06\x5c\x8d\xfe\xef\xf5\xb3\x0f\xb4\x0a\x20\x53\xd8\x35\x80\x02\xca\x97\x81\xb6\x1c\x4b\x8f\xb7\xee\xd0\xc3\x88\x6c\x76\x3e\xb0\x28\xce\xa1\x9f\x76\x5f\xaa\xc3\x53\x44\x09\x70\xa3\x95\xd9\x8c\x54\xba\x8a\x9a\x6b\xce\xc3\x07\xdf\x13\x6d\xea\x0f\x51\x9c\xe2\x81\x87\xf6\x82\x7a\x70\xd8\xfa\xe2\xa8\x32\xc1\x5e\x53\xc2\x85\xe9\x61\x8a\x17\x82\x12\xab\x92\x79\x2b\xed\x07\xca\x1e\x93\x23\x9c\x4b\xd2\x89\x86\xac\x55\xf9\x50\x23\x8f\x9e\xd3\xab\x22\x57\x91\x5a\x0b\x48\xd7\xa2\xb8\x06\xbb\x74\xae\xe9\xca\x06\x41\x8d\x6a\x00\x42\xc4\x40\xa9\xfe\xae\x88\x42\xc2\x83\xe0\x8a\xd8\x5c\xbb\x5a\xb5\x9c\x1d\xa5\xbe\x67\x50\xb1\x4e\xec\x96\x65\xaa\x87\x5b\xb0\x76\x88\xe3\x1b\xcb\x38\x21\x02\x8e\xc9\xe7\xf5\xc7\xe1\x1d\xe8\xeb\x54\x0e\x0b\xea\xd1\x2e\xad\xbb\xec\x22\x21\xb3\x64\x36\x29\x34\x5e\x3a\x22\xe8\x03\x4b\x86\xb1\x67\x7d\x4f\x48\x6d\xfb\x4b\xde\xe6\x4c\xb0\xaf\x40\x66\xab\xe9\x1a\x4e\xae\x1a\x7e\x05\xc5\x67\x2a\x95\x6d\xc2\x61\x35\x20\xfe\x33\xc3\x2c\x7f\x9b\xbe\x9f\x9a\xd5\xf0\x63\x28\xa1\x94\xb1\x5c\xc1\x18\x6b\x5b\x33\xb4\x4d\xcf\xbe\xf7\xb2\x94\x58\xaa\xcf\xad\xc8\x75\x93\x1a\x08\xf4\xd2\xd9\xf6\x95\x03\x3b\xf3\x4e\xfb\x15\xe4\x28\xed\xd5\x79\xd9\xbf\xb7\x8f\xb2\x70\x16\x4c\x2d\x65\xf6\xec\x33\x1e\xaf\xea\x46\x69\xc6\x9a\x6b\xdd\xf3\x57\xe0\x1d\x28\xcd\xf8\x83\x3d\x94\x4c\x2f\x6e\xfd\x51\x3d\xa8\xff\xcb\x33\xad\x32\x42\x0e\xd3\x00\x0a\xe5\x71\x76\x3b\x83\xc9\x2a\x67\x50\xc3\xa5\xeb\x4d\x8d\x67\xd6\xd9\x1b\x9a\x5a\xbe\xdd\xc5\x15\x00\xcf\x97\x0f\x47\x44\x34\x1d\x4e\xb6\x6f\x91\x31\xf3\x45\x0f\x59\x48\x10\x23\x53\x40\x49\x83\xe6\xc8\xdf\x51\x6c\xa8\x9f\x3a\x43\x3d\xb9\xd4\xea\x30\x4d\xe0\xd2\xb8\x44\xf3\x91\x20\x79\xdb\x7b\xe6\x50\xf9\x0f\xfb\x4c\xac\x79\x93\xf6\xf8\x96\x0d\x55\x7c\x41\x9b\x1a\x86\xad\x4b\xd1\xf9\x5d\xed\x3a\x4f\xc9\x64\x72\xd4\x22\x53\x59\x2f\x01\x00\x00\xff\xff\xc6\xfd\xa0\x37\x00\x04\x00\x00")
b.SetBytes(int64(len(in))) // 1024
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_ = Encode(in)
}
}

View File

@@ -0,0 +1,20 @@
// Copyright (c) 2013-2014 Conformal Systems LLC.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
/*
Package base58 provides base58-check encoding.
The alphabet is modifyiable for
Base58 Usage
To decode a base58 string:
rawData := base58.Base58Decode(encodedData)
Similarly, to encode the same data:
encodedData := base58.Base58Encode(rawData)
*/
package base58

View File

@@ -0,0 +1,9 @@
{
"name": "go-base58",
"author": "whyrusleeping",
"version": "1.0.0",
"language": "go",
"gx": {
"dvcsimport": "github.com/jbenet/go-base58"
}
}

View File

@@ -0,0 +1,362 @@
Mozilla Public License, version 2.0
1. Definitions
1.1. "Contributor"
means each individual or legal entity that creates, contributes to the
creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used by a
Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached the
notice in Exhibit A, the Executable Form of such Source Code Form, and
Modifications of such Source Code Form, in each case including portions
thereof.
1.5. "Incompatible With Secondary Licenses"
means
a. that the initial Contributor has attached the notice described in
Exhibit B to the Covered Software; or
b. that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the terms of
a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in a
separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible, whether
at the time of the initial grant or subsequently, any and all of the
rights conveyed by this License.
1.10. "Modifications"
means any of the following:
a. any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered Software; or
b. any new file in Source Code Form that contains any Covered Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the License,
by the making, using, selling, offering for sale, having made, import,
or transfer of either its Contributions or its Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU Lesser
General Public License, Version 2.1, the GNU Affero General Public
License, Version 3.0, or any later versions of those licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that controls, is
controlled by, or is under common control with You. For purposes of this
definition, "control" means (a) the power, direct or indirect, to cause
the direction or management of such entity, whether by contract or
otherwise, or (b) ownership of more than fifty percent (50%) of the
outstanding shares or beneficial ownership of such entity.
2. License Grants and Conditions
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
a. under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
b. under Patent Claims of such Contributor to make, use, sell, offer for
sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
a. for any code that a Contributor has removed from Covered Software; or
b. for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
c. under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights to
grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
Section 2.1.
3. Responsibilities
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
a. such Covered Software must also be made available in Source Code Form,
as described in Section 3.1, and You must inform recipients of the
Executable Form how they can obtain a copy of such Source Code Form by
reasonable means in a timely manner, at a charge no more than the cost
of distribution to the recipient; and
b. You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter the
recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty, or
limitations of liability) contained within the Source Code Form of the
Covered Software, except that You may alter any license notices to the
extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
If it is impossible for You to comply with any of the terms of this License
with respect to some or all of the Covered Software due to statute,
judicial order, or regulation then You must: (a) comply with the terms of
this License to the maximum extent possible; and (b) describe the
limitations and the code they affect. Such description must be placed in a
text file included with all distributions of the Covered Software under
this License. Except to the extent prohibited by statute or regulation,
such description must be sufficiently detailed for a recipient of ordinary
skill to be able to understand it.
5. Termination
5.1. The rights granted under this License will terminate automatically if You
fail to comply with any of its terms. However, if You become compliant,
then the rights granted under this License from a particular Contributor
are reinstated (a) provisionally, unless and until such Contributor
explicitly and finally terminates Your grants, and (b) on an ongoing
basis, if such Contributor fails to notify You of the non-compliance by
some reasonable means prior to 60 days after You have come back into
compliance. Moreover, Your grants from a particular Contributor are
reinstated on an ongoing basis if such Contributor notifies You of the
non-compliance by some reasonable means, this is the first time You have
received notice of non-compliance with this License from such
Contributor, and You become compliant prior to 30 days after Your receipt
of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
license agreements (excluding distributors and resellers) which have been
validly granted by You or Your distributors under this License prior to
termination shall survive termination.
6. Disclaimer of Warranty
Covered Software is provided under this License on an "as is" basis,
without warranty of any kind, either expressed, implied, or statutory,
including, without limitation, warranties that the Covered Software is free
of defects, merchantable, fit for a particular purpose or non-infringing.
The entire risk as to the quality and performance of the Covered Software
is with You. Should any Covered Software prove defective in any respect,
You (not any Contributor) assume the cost of any necessary servicing,
repair, or correction. This disclaimer of warranty constitutes an essential
part of this License. No use of any Covered Software is authorized under
this License except under this disclaimer.
7. Limitation of Liability
Under no circumstances and under no legal theory, whether tort (including
negligence), contract, or otherwise, shall any Contributor, or anyone who
distributes Covered Software as permitted above, be liable to You for any
direct, indirect, special, incidental, or consequential damages of any
character including, without limitation, damages for lost profits, loss of
goodwill, work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses, even if such party shall have been
informed of the possibility of such damages. This limitation of liability
shall not apply to liability for death or personal injury resulting from
such party's negligence to the extent applicable law prohibits such
limitation. Some jurisdictions do not allow the exclusion or limitation of
incidental or consequential damages, so this exclusion and limitation may
not apply to You.
8. Litigation
Any litigation relating to this License may be brought only in the courts
of a jurisdiction where the defendant maintains its principal place of
business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions. Nothing
in this Section shall prevent a party's ability to bring cross-claims or
counter-claims.
9. Miscellaneous
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides that
the language of a contract shall be construed against the drafter shall not
be used to construe this License against a Contributor.
10. Versions of the License
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses If You choose to distribute Source Code Form that is
Incompatible With Secondary Licenses under the terms of this version of
the License, the notice described in Exhibit B of this License must be
attached.
Exhibit A - Source Code Form License Notice
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular file,
then You may include the notice in a location (such as a LICENSE file in a
relevant directory) where a recipient would be likely to look for such a
notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
This Source Code Form is "Incompatible
With Secondary Licenses", as defined by
the Mozilla Public License, v. 2.0.

View File

@@ -0,0 +1,19 @@
# utp
[![GoDoc](https://godoc.org/github.com/anacrolix/utp?status.svg)](https://godoc.org/github.com/anacrolix/utp)
[![Build Status](https://drone.io/github.com/anacrolix/utp/status.png)](https://drone.io/github.com/anacrolix/utp/latest)
Package utp implements uTP, the micro transport protocol as used with Bittorrent. It opts for simplicity and reliability over strict adherence to the (poor) spec.
## Supported
* Multiple uTP connections switched on a single PacketConn, including those initiated locally.
* Raw access to the PacketConn for non-uTP purposes, like sharing the PacketConn with a DHT implementation.
## Implementation characteristics
* Receive window size is used to limit out of order packets received.
* There is no MTU path discovery. The minimum size is always used.
* A fixed 64 slot selective ack window is used in both sending and receiving.
* All received non-ACK packets are ACKed in response.
Patches welcomed.

View File

@@ -0,0 +1,76 @@
package main
import (
"flag"
"fmt"
"io"
"log"
"net"
"os"
"os/signal"
"QmWsa476RGjb9scWzcRVts3QZsYjU5Kt6Y9qe8Q3vc5FHR/envpprof"
"QmVBEPpwYNGb5xQW6jPzYgV86KSPRrzhe4hA7o7mtAHZsT/go-utp"
)
func main() {
defer envpprof.Stop()
listen := flag.Bool("l", false, "listen")
port := flag.Int("p", 0, "port to listen on")
flag.Parse()
var (
conn net.Conn
err error
)
if *listen {
s, err := utp.NewSocket("udp", fmt.Sprintf(":%d", *port))
if err != nil {
log.Fatal(err)
}
defer s.Close()
conn, err = s.Accept()
if err != nil {
log.Fatal(err)
}
} else {
conn, err = utp.Dial(net.JoinHostPort(flag.Arg(0), flag.Arg(1)))
if err != nil {
log.Fatal(err)
}
}
defer conn.Close()
go func() {
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt)
<-sig
conn.Close()
}()
writerDone := make(chan struct{})
readerDone := make(chan struct{})
go func() {
defer close(writerDone)
written, err := io.Copy(conn, os.Stdin)
if err != nil {
conn.Close()
log.Fatalf("error after writing %d bytes: %s", written, err)
}
log.Printf("wrote %d bytes", written)
conn.Close()
}()
go func() {
defer close(readerDone)
n, err := io.Copy(os.Stdout, conn)
if err != nil {
log.Fatal(err)
}
log.Printf("received %d bytes", n)
}()
// Technically we should wait until both reading and writing are done. But
// ucat-style binaries terminate abrubtly when read or write is completed,
// and no state remains to clean-up the peer neatly.
select {
case <-writerDone:
case <-readerDone:
}
}

View File

@@ -0,0 +1,21 @@
{
"name": "go-utp",
"author": "whyrusleeping",
"version": "1.0.0",
"gxDependencies": [
{
"name": "jitter",
"hash": "QmbDXAJ4Fzpmqw9kTVPtPGZEsgyn33ipbUQEe8vMUZLnTS",
"version": "1.0.0"
},
{
"name": "envpprof",
"hash": "QmWsa476RGjb9scWzcRVts3QZsYjU5Kt6Y9qe8Q3vc5FHR",
"version": "1.0.0"
}
],
"language": "go",
"gx": {
"dvcsimport": "github.com/anacrolix/utp"
}
}

View File

@@ -0,0 +1,68 @@
# This shell script uses nc-like executables to send and receive the file at
# $1, and prints the checksums. 3 such executables are
# github.com/h2so5/utp/ucat, invoked as h2so5-ucat, libutp-ucat, which is the
# ucat or ucat-static generated by the C++ libutp, and lastly, ./cmd/ucat from
# this repository. A good file in my experiments is no more than a few 100MB,
# or you'll be waiting a while.
set -eu
# set -x
# Passed to invocations of godo for package ./cmd/ucat.
#GODOFLAGS=-race
#export GO_UTP_PACKET_DROP=0.1
export GOPPROF=
# Invokes the implementation to test against. If there's an arg, then it's
# expected to listen.
function other_ucat() {
if [[ $# != 0 ]]; then
libutp-ucat -l -p "$port"
# h2so5-ucat -l :"$port"
else
libutp-ucat localhost "$port"
# h2so5-ucat localhost:"$port"
fi
}
function md5cmd() {
(which md5sum > /dev/null && md5sum "$@") || (which md5 > /dev/null && md5 "$@") || md5sum "$@"
}
# Check what the correct result is.
md5cmd "$1"
rate() {
pv -a -W -b
}
port=4000
echo 'utp->other_ucat'
# Send from this uTP implementation to another client.
other_ucat -l | rate | md5cmd &
# sleep 1
godo ${GODOFLAGS-} ./cmd/ucat localhost "$port" < "$1"
wait
echo 'other_ucat->utp'
# Send from the other implementation, to this one.
GO_UTP_LOGGING=0 godo ${GODOFLAGS-} ./cmd/ucat -l -p "$port" | rate | md5cmd &
# Never receive from h2so5's ucat without a small sleep first. Don't know why.
sleep 1
other_ucat < "$1"
wait
echo 'libutp->libutp'
libutp-ucat -l -p "$port" | rate | md5cmd &
libutp-ucat localhost "$port" < "$1"
wait
echo 'utp->utp'
godo ./cmd/ucat -l -p "$port" | rate | md5cmd &
sleep 1
godo ./cmd/ucat localhost "$port" < "$1"
wait
# Now check the hashes match (yes you).

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,484 @@
package utp
import (
"fmt"
"io"
"io/ioutil"
"log"
"net"
"runtime"
"sync"
"testing"
"time"
_ "QmWsa476RGjb9scWzcRVts3QZsYjU5Kt6Y9qe8Q3vc5FHR/envpprof"
"github.com/anacrolix/missinggo"
"github.com/bradfitz/iter"
"github.com/stretchr/testify/require"
)
func init() {
log.SetFlags(log.Flags() | log.Lshortfile)
writeTimeout = 1 * time.Second
initialLatency = 10 * time.Millisecond
packetReadTimeout = 2 * time.Second
}
func TestUTPPingPong(t *testing.T) {
defer goroutineLeakCheck(t)()
s, err := NewSocket("udp", "localhost:0")
require.NoError(t, err)
defer s.Close()
pingerClosed := make(chan struct{})
go func() {
defer close(pingerClosed)
b, err := Dial(s.Addr().String())
require.NoError(t, err)
defer b.Close()
n, err := b.Write([]byte("ping"))
require.NoError(t, err)
require.EqualValues(t, 4, n)
buf := make([]byte, 4)
b.Read(buf)
require.EqualValues(t, "pong", buf)
log.Printf("got pong")
}()
a, err := s.Accept()
require.NoError(t, err)
defer a.Close()
log.Printf("accepted %s", a)
buf := make([]byte, 42)
n, err := a.Read(buf)
require.NoError(t, err)
require.EqualValues(t, "ping", buf[:n])
log.Print("got ping")
n, err = a.Write([]byte("pong"))
require.NoError(t, err)
require.Equal(t, 4, n)
log.Print("waiting for pinger to close")
<-pingerClosed
}
func goroutineLeakCheck(t testing.TB) func() {
if !testing.Verbose() {
return func() {}
}
numStart := runtime.NumGoroutine()
return func() {
var numNow int
for range iter.N(1) {
numNow = runtime.NumGoroutine()
if numNow == numStart {
return
}
time.Sleep(10 * time.Millisecond)
}
// I'd print stacks, or treat this as fatal, but I think
// runtime.NumGoroutine is including system routines for which we are
// not provided the stacks, and are spawned unpredictably.
t.Logf("have %d goroutines, started with %d", numNow, numStart)
}
}
func TestDialTimeout(t *testing.T) {
defer goroutineLeakCheck(t)()
s, _ := NewSocket("udp", "localhost:0")
defer s.Close()
conn, err := DialTimeout(s.Addr().String(), 10*time.Millisecond)
if err == nil {
conn.Close()
t.Fatal("expected timeout")
}
t.Log(err)
}
func TestMinMaxHeaderType(t *testing.T) {
require.Equal(t, stSyn, stMax)
}
func TestUTPRawConn(t *testing.T) {
l, err := NewSocket("udp", "")
require.NoError(t, err)
defer l.Close()
go func() {
for {
_, err := l.Accept()
if err != nil {
break
}
}
}()
// Connect a UTP peer to see if the RawConn will still work.
log.Print("dialing")
utpPeer := func() net.Conn {
s, _ := NewSocket("udp", "")
defer s.Close()
ret, err := s.Dial(fmt.Sprintf("localhost:%d", missinggo.AddrPort(l.Addr())))
require.NoError(t, err)
return ret
}()
log.Print("dial returned")
if err != nil {
t.Fatalf("error dialing utp listener: %s", err)
}
defer utpPeer.Close()
peer, err := net.ListenPacket("udp", ":0")
if err != nil {
t.Fatal(err)
}
defer peer.Close()
msgsReceived := 0
const N = 5000 // How many messages to send.
readerStopped := make(chan struct{})
// The reader goroutine.
go func() {
defer close(readerStopped)
b := make([]byte, 500)
for i := 0; i < N; i++ {
n, _, err := l.ReadFrom(b)
if err != nil {
t.Fatalf("error reading from raw conn: %s", err)
}
msgsReceived++
var d int
fmt.Sscan(string(b[:n]), &d)
if d != i {
log.Printf("got wrong number: expected %d, got %d", i, d)
}
}
}()
udpAddr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("localhost:%d", missinggo.AddrPort(l.Addr())))
if err != nil {
t.Fatal(err)
}
for i := 0; i < N; i++ {
_, err := peer.WriteTo([]byte(fmt.Sprintf("%d", i)), udpAddr)
if err != nil {
t.Fatal(err)
}
time.Sleep(10 * time.Microsecond)
}
select {
case <-readerStopped:
case <-time.After(time.Second):
t.Fatal("reader timed out")
}
if msgsReceived != N {
t.Fatalf("messages received: %d", msgsReceived)
}
}
func TestConnReadDeadline(t *testing.T) {
t.Parallel()
ls, _ := NewSocket("udp", "localhost:0")
ds, _ := NewSocket("udp", "localhost:0")
dcReadErr := make(chan error)
go func() {
c, _ := ds.Dial(ls.Addr().String())
defer c.Close()
_, err := c.Read(nil)
dcReadErr <- err
}()
c, _ := ls.Accept()
dl := time.Now().Add(time.Millisecond)
c.SetReadDeadline(dl)
_, err := c.Read(nil)
require.Equal(t, errTimeout, err)
// The deadline has passed.
if !time.Now().After(dl) {
t.FailNow()
}
// Returns timeout on subsequent read.
_, err = c.Read(nil)
require.Equal(t, errTimeout, err)
// Disable the deadline.
c.SetReadDeadline(time.Time{})
readReturned := make(chan struct{})
go func() {
c.Read(nil)
close(readReturned)
}()
select {
case <-readReturned:
// Read returned but shouldn't have.
t.FailNow()
case <-time.After(time.Millisecond):
}
c.Close()
if err := <-dcReadErr; err != io.EOF {
t.Fatalf("dial conn read returned %s", err)
}
select {
case <-readReturned:
case <-time.After(time.Millisecond):
t.Fatal("read should return after Conn is closed")
}
}
func connectSelfLots(n int, t testing.TB) {
defer goroutineLeakCheck(t)()
s, err := NewSocket("udp", "localhost:0")
if err != nil {
t.Fatal(err)
}
go func() {
for range iter.N(n) {
c, err := s.Accept()
if err != nil {
log.Fatal(err)
}
defer c.Close()
}
}()
dialErr := make(chan error)
connCh := make(chan net.Conn)
dialSema := make(chan struct{}, backlog)
for range iter.N(n) {
go func() {
dialSema <- struct{}{}
c, err := s.Dial(s.Addr().String())
<-dialSema
if err != nil {
dialErr <- err
return
}
connCh <- c
}()
}
conns := make([]net.Conn, 0, n)
for range iter.N(n) {
select {
case c := <-connCh:
conns = append(conns, c)
case err := <-dialErr:
t.Fatal(err)
}
}
for _, c := range conns {
if c != nil {
c.Close()
}
}
s.mu.Lock()
for len(s.conns) != 0 {
// log.Print(len(s.conns))
s.event.Wait()
}
s.mu.Unlock()
s.Close()
}
// Connect to ourself heaps.
func TestConnectSelf(t *testing.T) {
t.Parallel()
// A rough guess says that at worst, I can only have 0x10000/3 connections
// to the same socket, due to fragmentation in the assigned connection
// IDs.
connectSelfLots(0x1000, t)
}
func BenchmarkConnectSelf(b *testing.B) {
for range iter.N(b.N) {
connectSelfLots(2, b)
}
}
func BenchmarkNewCloseSocket(b *testing.B) {
for range iter.N(b.N) {
s, err := NewSocket("udp", "localhost:0")
if err != nil {
b.Fatal(err)
}
err = s.Close()
if err != nil {
b.Fatal(err)
}
}
}
func TestRejectDialBacklogFilled(t *testing.T) {
s, err := NewSocket("udp", "localhost:0")
if err != nil {
t.Fatal(err)
}
errChan := make(chan error, 1)
dial := func() {
_, err := s.Dial(s.Addr().String())
if err != nil {
errChan <- err
}
}
// Fill the backlog.
for range iter.N(backlog + 1) {
go dial()
}
s.mu.Lock()
for len(s.backlog) < backlog {
s.event.Wait()
}
s.mu.Unlock()
select {
case <-errChan:
t.FailNow()
default:
}
// One more connection should cause a dial attempt to get reset.
go dial()
err = <-errChan
if err.Error() != "peer reset" {
t.FailNow()
}
s.Close()
}
// Make sure that we can reset AfterFunc timers, so we don't have to create
// brand new ones everytime they fire. Specifically for the Conn resend timer.
func TestResetAfterFuncTimer(t *testing.T) {
t.Parallel()
fired := make(chan struct{})
timer := time.AfterFunc(time.Millisecond, func() {
fired <- struct{}{}
})
<-fired
if timer.Reset(time.Millisecond) {
// The timer should have expired
t.FailNow()
}
<-fired
}
func connPair() (initer, accepted net.Conn) {
s, err := NewSocket("udp", "localhost:0")
if err != nil {
panic(err)
}
defer s.Close()
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
var err error
initer, err = Dial(s.Addr().String())
if err != nil {
panic(err)
}
}()
accepted, err = s.Accept()
if err != nil {
panic(err)
}
wg.Wait()
return
}
// Check that peer sending FIN doesn't cause unread data to be dropped in a
// receiver.
func TestReadFinishedConn(t *testing.T) {
a, b := connPair()
defer a.Close()
defer b.Close()
mu.Lock()
originalAPDC := artificialPacketDropChance
artificialPacketDropChance = 1
mu.Unlock()
n, err := a.Write([]byte("hello"))
require.Equal(t, 5, n)
require.NoError(t, err)
n, err = a.Write([]byte("world"))
require.Equal(t, 5, n)
require.NoError(t, err)
mu.Lock()
artificialPacketDropChance = originalAPDC
mu.Unlock()
a.Close()
all, err := ioutil.ReadAll(b)
require.NoError(t, err)
require.EqualValues(t, "helloworld", all)
}
func TestCloseDetachesQuickly(t *testing.T) {
t.Parallel()
s, _ := NewSocket("udp", "localhost:0")
defer s.Close()
go func() {
a, _ := s.Dial(s.Addr().String())
log.Print("close a")
a.Close()
log.Print("closed a")
}()
b, _ := s.Accept()
b.Close()
s.mu.Lock()
for len(s.conns) != 0 {
log.Print(len(s.conns))
s.event.Wait()
}
s.mu.Unlock()
}
// Check that closing, and resulting detach of a Conn doesn't close the parent
// Socket. We Accept, then close the connection and ensure it's detached. Then
// Accept again to check the Socket is still functional and unclosed.
func TestConnCloseUnclosedSocket(t *testing.T) {
t.Parallel()
s, err := NewSocket("udp", "localhost:0")
require.NoError(t, err)
defer func() {
require.NoError(t, s.Close())
}()
// Prevents the dialing goroutine from closing its end of the Conn before
// we can check that it has been registered in the listener.
dialerSync := make(chan struct{})
go func() {
for range iter.N(2) {
c, err := Dial(s.Addr().String())
require.NoError(t, err)
<-dialerSync
err = c.Close()
require.NoError(t, err)
}
}()
for range iter.N(2) {
a, err := s.Accept()
require.NoError(t, err)
// We do this in a closure because we need to unlock Server.mu if the
// test failure exception is thrown. "Do as we say, not as we do" -Go
// team.
func() {
s.mu.Lock()
defer s.mu.Unlock()
require.Len(t, s.conns, 1)
}()
dialerSync <- struct{}{}
require.NoError(t, a.Close())
func() {
s.mu.Lock()
defer s.mu.Unlock()
for len(s.conns) != 0 {
s.event.Wait()
}
}()
}
}
func TestAcceptGone(t *testing.T) {
s, _ := NewSocket("udp", "localhost:0")
_, err := DialTimeout(s.Addr().String(), time.Millisecond)
require.Error(t, err)
c, _ := s.Accept()
c.SetReadDeadline(time.Now().Add(time.Millisecond))
c.Read(nil)
// select {}
}
func TestPacketReadTimeout(t *testing.T) {
t.Parallel()
a, b := connPair()
_, err := a.Read(nil)
require.Contains(t, err.Error(), "timeout")
t.Log(err)
t.Log(a.Close())
t.Log(b.Close())
}

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2015 Jeromy Johnson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,15 @@
# go-multiaddr-filter -- CIDR netmasks with multiaddr
This module creates very simple [multiaddr](https://github.com/jbenet/go-multiaddr) formatted cidr netmasks.
It doesn't do full multiaddr parsing to save on vendoring things and perf. The `net` package will take care of verifying the validity of the network part anyway.
## Usage
```go
import filter "github.com/whyrusleeping/multiaddr-filter"
filter.NewMask("/ip4/192.168.0.0/24") // ipv4
filter.NewMask("/ip6/fe80::/64") // ipv6
```

View File

@@ -0,0 +1,47 @@
package mask
import (
"errors"
"fmt"
"net"
"strings"
manet "QmanZCL6SXRfafiUEMCBLq2QR171uQSdXQ8YAdHXLd8Cwr/go-multiaddr-net"
)
var ErrInvalidFormat = errors.New("invalid multiaddr-filter format")
func NewMask(a string) (*net.IPNet, error) {
parts := strings.Split(a, "/")
if parts[0] != "" {
return nil, ErrInvalidFormat
}
if len(parts) != 5 {
return nil, ErrInvalidFormat
}
// check it's a valid filter address. ip + cidr
isip := parts[1] == "ip4" || parts[1] == "ip6"
iscidr := parts[3] == "ipcidr"
if !isip || !iscidr {
return nil, ErrInvalidFormat
}
_, ipn, err := net.ParseCIDR(parts[2] + "/" + parts[4])
if err != nil {
return nil, err
}
return ipn, nil
}
func ConvertIPNet(n *net.IPNet) (string, error) {
addr, err := manet.FromIP(n.IP)
if err != nil {
return "", err
}
b, _ := n.Mask.Size()
return fmt.Sprintf("%s/ipcidr/%d", addr, b), nil
}

View File

@@ -0,0 +1,132 @@
package mask
import (
"net"
"testing"
)
func TestValidMasks(t *testing.T) {
cidrOrFatal := func(s string) *net.IPNet {
_, ipn, err := net.ParseCIDR(s)
if err != nil {
t.Fatal(err)
}
return ipn
}
testCases := map[string]*net.IPNet{
"/ip4/1.2.3.4/ipcidr/0": cidrOrFatal("1.2.3.4/0"),
"/ip4/1.2.3.4/ipcidr/32": cidrOrFatal("1.2.3.4/32"),
"/ip4/1.2.3.4/ipcidr/24": cidrOrFatal("1.2.3.4/24"),
"/ip4/192.168.0.0/ipcidr/28": cidrOrFatal("192.168.0.0/28"),
"/ip6/fe80::/ipcidr/0": cidrOrFatal("fe80::/0"),
"/ip6/fe80::/ipcidr/64": cidrOrFatal("fe80::/64"),
"/ip6/fe80::/ipcidr/128": cidrOrFatal("fe80::/128"),
}
for s, m1 := range testCases {
m2, err := NewMask(s)
if err != nil {
t.Error("should be invalid:", s)
continue
}
if m1.String() != m2.String() {
t.Error("masks not equal:", m1, m2)
}
}
}
func TestInvalidMasks(t *testing.T) {
testCases := []string{
"/",
"/ip4/10.1.2.3",
"/ip6/::",
"/ip4/1.2.3.4/cidr/24",
"/ip6/fe80::/cidr/24",
"/eth/aa:aa:aa:aa:aa/ipcidr/24",
"foobar/ip4/1.2.3.4/ipcidr/32",
}
for _, s := range testCases {
_, err := NewMask(s)
if err != ErrInvalidFormat {
t.Error("should be invalid:", s)
}
}
testCases2 := []string{
"/ip4/1.2.3.4/ipcidr/33",
"/ip4/192.168.0.0/ipcidr/-1",
"/ip6/fe80::/ipcidr/129",
}
for _, s := range testCases2 {
_, err := NewMask(s)
if err == nil {
t.Error("should be invalid:", s)
}
}
}
func TestFiltered(t *testing.T) {
var tests = map[string]map[string]bool{
"/ip4/10.0.0.0/ipcidr/8": map[string]bool{
"10.3.3.4": true,
"10.3.4.4": true,
"10.4.4.4": true,
"15.52.34.3": false,
},
"/ip4/192.168.0.0/ipcidr/16": map[string]bool{
"192.168.0.0": true,
"192.168.1.0": true,
"192.1.0.0": false,
"10.4.4.4": false,
},
}
for mask, set := range tests {
m, err := NewMask(mask)
if err != nil {
t.Fatal(err)
}
for addr, val := range set {
ip := net.ParseIP(addr)
if m.Contains(ip) != val {
t.Fatalf("expected contains(%s, %s) == %s", mask, addr, val)
}
}
}
}
func TestParsing(t *testing.T) {
var addrs = map[string]string{
"/ip4/192.168.0.0/ipcidr/16": "192.168.0.0/16",
"/ip4/192.0.0.0/ipcidr/8": "192.0.0.0/8",
"/ip6/2001:db8::/ipcidr/32": "2001:db8::/32",
}
for k, v := range addrs {
m, err := NewMask(k)
if err != nil {
t.Fatal(err)
}
if m.String() != v {
t.Fatalf("mask is wrong: ", m, v)
}
orig, err := ConvertIPNet(m)
if err != nil {
t.Fatal(err)
}
if orig != k {
t.Fatal("backwards conversion failed: ", orig, k)
}
}
}

View File

@@ -0,0 +1,16 @@
{
"name": "multiaddr-filter",
"author": "whyrusleeping",
"version": "1.0.0",
"gxDependencies": [
{
"name": "go-multiaddr-net",
"hash": "QmanZCL6SXRfafiUEMCBLq2QR171uQSdXQ8YAdHXLd8Cwr",
"version": "1.0.0"
}
],
"language": "go",
"gx": {
"dvcsimport": "github.com/whyrusleeping/multiaddr-filter"
}
}

View File

@@ -0,0 +1,92 @@
package envpprof
import (
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
_ "net/http/pprof"
"os"
"path/filepath"
"runtime"
"runtime/pprof"
"strings"
)
var (
pprofDir = filepath.Join(os.Getenv("HOME"), "pprof")
heap bool
)
func writeHeapProfile() {
os.Mkdir(pprofDir, 0750)
f, err := ioutil.TempFile(pprofDir, "heap")
if err != nil {
log.Printf("error creating heap profile file: %s", err)
return
}
defer f.Close()
pprof.WriteHeapProfile(f)
log.Printf("wrote heap profile to %q", f.Name())
}
func Stop() {
pprof.StopCPUProfile()
if heap {
writeHeapProfile()
}
}
func init() {
for _, item := range strings.Split(os.Getenv("GOPPROF"), ",") {
equalsPos := strings.IndexByte(item, '=')
var key, value string
if equalsPos < 0 {
key = item
} else {
key = item[:equalsPos]
value = item[equalsPos+1:]
}
if value != "" {
log.Printf("values not yet supported")
}
switch key {
case "http":
go func() {
var l net.Listener
for port := uint16(6061); port != 6060; port++ {
var err error
l, err = net.Listen("tcp", fmt.Sprintf("localhost:%d", port))
if err == nil {
break
}
}
if l == nil {
log.Print("unable to create envpprof listener for http")
return
}
defer l.Close()
log.Printf("envpprof serving http://%s", l.Addr())
log.Printf("error serving http on envpprof listener: %s", http.Serve(l, nil))
}()
case "cpu":
os.Mkdir(pprofDir, 0750)
f, err := ioutil.TempFile(pprofDir, "cpu")
if err != nil {
log.Printf("error creating cpu pprof file: %s", err)
break
}
err = pprof.StartCPUProfile(f)
if err != nil {
log.Printf("error starting cpu profiling: %s", err)
break
}
log.Printf("cpu profiling to file %q", f.Name())
case "block":
runtime.SetBlockProfileRate(1)
case "heap":
heap = true
}
}
}

View File

@@ -0,0 +1,9 @@
{
"name": "envpprof",
"author": "whyrusleeping",
"version": "1.0.0",
"language": "go",
"gx": {
"dvcsimport": "github.com/anacrolix/envpprof"
}
}

View File

@@ -0,0 +1,66 @@
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package sha3 implements the SHA-3 fixed-output-length hash functions and
// the SHAKE variable-output-length hash functions defined by FIPS-202.
//
// Both types of hash function use the "sponge" construction and the Keccak
// permutation. For a detailed specification see http://keccak.noekeon.org/
//
//
// Guidance
//
// If you aren't sure what function you need, use SHAKE256 with at least 64
// bytes of output. The SHAKE instances are faster than the SHA3 instances;
// the latter have to allocate memory to conform to the hash.Hash interface.
//
// If you need a secret-key MAC (message authentication code), prepend the
// secret key to the input, hash with SHAKE256 and read at least 32 bytes of
// output.
//
//
// Security strengths
//
// The SHA3-x (x equals 224, 256, 384, or 512) functions have a security
// strength against preimage attacks of x bits. Since they only produce "x"
// bits of output, their collision-resistance is only "x/2" bits.
//
// The SHAKE-256 and -128 functions have a generic security strength of 256 and
// 128 bits against all attacks, provided that at least 2x bits of their output
// is used. Requesting more than 64 or 32 bytes of output, respectively, does
// not increase the collision-resistance of the SHAKE functions.
//
//
// The sponge construction
//
// A sponge builds a pseudo-random function from a public pseudo-random
// permutation, by applying the permutation to a state of "rate + capacity"
// bytes, but hiding "capacity" of the bytes.
//
// A sponge starts out with a zero state. To hash an input using a sponge, up
// to "rate" bytes of the input are XORed into the sponge's state. The sponge
// is then "full" and the permutation is applied to "empty" it. This process is
// repeated until all the input has been "absorbed". The input is then padded.
// The digest is "squeezed" from the sponge in the same way, except that output
// output is copied out instead of input being XORed in.
//
// A sponge is parameterized by its generic security strength, which is equal
// to half its capacity; capacity + rate is equal to the permutation's width.
// Since the KeccakF-1600 permutation is 1600 bits (200 bytes) wide, this means
// that the security strength of a sponge instance is equal to (1600 - bitrate) / 2.
//
//
// Recommendations
//
// The SHAKE functions are recommended for most new uses. They can produce
// output of arbitrary length. SHAKE256, with an output length of at least
// 64 bytes, provides 256-bit security against all attacks. The Keccak team
// recommends it for most applications upgrading from SHA2-512. (NIST chose a
// much stronger, but much slower, sponge instance for SHA3-512.)
//
// The SHA-3 functions are "drop-in" replacements for the SHA-2 functions.
// They produce output of the same length, with the same security strengths
// against all attacks. This means, in particular, that SHA3-256 only has
// 128-bit collision resistance, because its output length is 32 bytes.
package sha3 // import "golang.org/x/crypto/sha3"

View File

@@ -0,0 +1,65 @@
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package sha3
// This file provides functions for creating instances of the SHA-3
// and SHAKE hash functions, as well as utility functions for hashing
// bytes.
import (
"hash"
)
// New224 creates a new SHA3-224 hash.
// Its generic security strength is 224 bits against preimage attacks,
// and 112 bits against collision attacks.
func New224() hash.Hash { return &state{rate: 144, outputLen: 28, dsbyte: 0x06} }
// New256 creates a new SHA3-256 hash.
// Its generic security strength is 256 bits against preimage attacks,
// and 128 bits against collision attacks.
func New256() hash.Hash { return &state{rate: 136, outputLen: 32, dsbyte: 0x06} }
// New384 creates a new SHA3-384 hash.
// Its generic security strength is 384 bits against preimage attacks,
// and 192 bits against collision attacks.
func New384() hash.Hash { return &state{rate: 104, outputLen: 48, dsbyte: 0x06} }
// New512 creates a new SHA3-512 hash.
// Its generic security strength is 512 bits against preimage attacks,
// and 256 bits against collision attacks.
func New512() hash.Hash { return &state{rate: 72, outputLen: 64, dsbyte: 0x06} }
// Sum224 returns the SHA3-224 digest of the data.
func Sum224(data []byte) (digest [28]byte) {
h := New224()
h.Write(data)
h.Sum(digest[:0])
return
}
// Sum256 returns the SHA3-256 digest of the data.
func Sum256(data []byte) (digest [32]byte) {
h := New256()
h.Write(data)
h.Sum(digest[:0])
return
}
// Sum384 returns the SHA3-384 digest of the data.
func Sum384(data []byte) (digest [48]byte) {
h := New384()
h.Write(data)
h.Sum(digest[:0])
return
}
// Sum512 returns the SHA3-512 digest of the data.
func Sum512(data []byte) (digest [64]byte) {
h := New512()
h.Write(data)
h.Sum(digest[:0])
return
}

View File

@@ -0,0 +1,410 @@
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package sha3
// rc stores the round constants for use in the ι step.
var rc = [24]uint64{
0x0000000000000001,
0x0000000000008082,
0x800000000000808A,
0x8000000080008000,
0x000000000000808B,
0x0000000080000001,
0x8000000080008081,
0x8000000000008009,
0x000000000000008A,
0x0000000000000088,
0x0000000080008009,
0x000000008000000A,
0x000000008000808B,
0x800000000000008B,
0x8000000000008089,
0x8000000000008003,
0x8000000000008002,
0x8000000000000080,
0x000000000000800A,
0x800000008000000A,
0x8000000080008081,
0x8000000000008080,
0x0000000080000001,
0x8000000080008008,
}
// keccakF1600 applies the Keccak permutation to a 1600b-wide
// state represented as a slice of 25 uint64s.
func keccakF1600(a *[25]uint64) {
// Implementation translated from Keccak-inplace.c
// in the keccak reference code.
var t, bc0, bc1, bc2, bc3, bc4, d0, d1, d2, d3, d4 uint64
for i := 0; i < 24; i += 4 {
// Combines the 5 steps in each round into 2 steps.
// Unrolls 4 rounds per loop and spreads some steps across rounds.
// Round 1
bc0 = a[0] ^ a[5] ^ a[10] ^ a[15] ^ a[20]
bc1 = a[1] ^ a[6] ^ a[11] ^ a[16] ^ a[21]
bc2 = a[2] ^ a[7] ^ a[12] ^ a[17] ^ a[22]
bc3 = a[3] ^ a[8] ^ a[13] ^ a[18] ^ a[23]
bc4 = a[4] ^ a[9] ^ a[14] ^ a[19] ^ a[24]
d0 = bc4 ^ (bc1<<1 | bc1>>63)
d1 = bc0 ^ (bc2<<1 | bc2>>63)
d2 = bc1 ^ (bc3<<1 | bc3>>63)
d3 = bc2 ^ (bc4<<1 | bc4>>63)
d4 = bc3 ^ (bc0<<1 | bc0>>63)
bc0 = a[0] ^ d0
t = a[6] ^ d1
bc1 = t<<44 | t>>(64-44)
t = a[12] ^ d2
bc2 = t<<43 | t>>(64-43)
t = a[18] ^ d3
bc3 = t<<21 | t>>(64-21)
t = a[24] ^ d4
bc4 = t<<14 | t>>(64-14)
a[0] = bc0 ^ (bc2 &^ bc1) ^ rc[i]
a[6] = bc1 ^ (bc3 &^ bc2)
a[12] = bc2 ^ (bc4 &^ bc3)
a[18] = bc3 ^ (bc0 &^ bc4)
a[24] = bc4 ^ (bc1 &^ bc0)
t = a[10] ^ d0
bc2 = t<<3 | t>>(64-3)
t = a[16] ^ d1
bc3 = t<<45 | t>>(64-45)
t = a[22] ^ d2
bc4 = t<<61 | t>>(64-61)
t = a[3] ^ d3
bc0 = t<<28 | t>>(64-28)
t = a[9] ^ d4
bc1 = t<<20 | t>>(64-20)
a[10] = bc0 ^ (bc2 &^ bc1)
a[16] = bc1 ^ (bc3 &^ bc2)
a[22] = bc2 ^ (bc4 &^ bc3)
a[3] = bc3 ^ (bc0 &^ bc4)
a[9] = bc4 ^ (bc1 &^ bc0)
t = a[20] ^ d0
bc4 = t<<18 | t>>(64-18)
t = a[1] ^ d1
bc0 = t<<1 | t>>(64-1)
t = a[7] ^ d2
bc1 = t<<6 | t>>(64-6)
t = a[13] ^ d3
bc2 = t<<25 | t>>(64-25)
t = a[19] ^ d4
bc3 = t<<8 | t>>(64-8)
a[20] = bc0 ^ (bc2 &^ bc1)
a[1] = bc1 ^ (bc3 &^ bc2)
a[7] = bc2 ^ (bc4 &^ bc3)
a[13] = bc3 ^ (bc0 &^ bc4)
a[19] = bc4 ^ (bc1 &^ bc0)
t = a[5] ^ d0
bc1 = t<<36 | t>>(64-36)
t = a[11] ^ d1
bc2 = t<<10 | t>>(64-10)
t = a[17] ^ d2
bc3 = t<<15 | t>>(64-15)
t = a[23] ^ d3
bc4 = t<<56 | t>>(64-56)
t = a[4] ^ d4
bc0 = t<<27 | t>>(64-27)
a[5] = bc0 ^ (bc2 &^ bc1)
a[11] = bc1 ^ (bc3 &^ bc2)
a[17] = bc2 ^ (bc4 &^ bc3)
a[23] = bc3 ^ (bc0 &^ bc4)
a[4] = bc4 ^ (bc1 &^ bc0)
t = a[15] ^ d0
bc3 = t<<41 | t>>(64-41)
t = a[21] ^ d1
bc4 = t<<2 | t>>(64-2)
t = a[2] ^ d2
bc0 = t<<62 | t>>(64-62)
t = a[8] ^ d3
bc1 = t<<55 | t>>(64-55)
t = a[14] ^ d4
bc2 = t<<39 | t>>(64-39)
a[15] = bc0 ^ (bc2 &^ bc1)
a[21] = bc1 ^ (bc3 &^ bc2)
a[2] = bc2 ^ (bc4 &^ bc3)
a[8] = bc3 ^ (bc0 &^ bc4)
a[14] = bc4 ^ (bc1 &^ bc0)
// Round 2
bc0 = a[0] ^ a[5] ^ a[10] ^ a[15] ^ a[20]
bc1 = a[1] ^ a[6] ^ a[11] ^ a[16] ^ a[21]
bc2 = a[2] ^ a[7] ^ a[12] ^ a[17] ^ a[22]
bc3 = a[3] ^ a[8] ^ a[13] ^ a[18] ^ a[23]
bc4 = a[4] ^ a[9] ^ a[14] ^ a[19] ^ a[24]
d0 = bc4 ^ (bc1<<1 | bc1>>63)
d1 = bc0 ^ (bc2<<1 | bc2>>63)
d2 = bc1 ^ (bc3<<1 | bc3>>63)
d3 = bc2 ^ (bc4<<1 | bc4>>63)
d4 = bc3 ^ (bc0<<1 | bc0>>63)
bc0 = a[0] ^ d0
t = a[16] ^ d1
bc1 = t<<44 | t>>(64-44)
t = a[7] ^ d2
bc2 = t<<43 | t>>(64-43)
t = a[23] ^ d3
bc3 = t<<21 | t>>(64-21)
t = a[14] ^ d4
bc4 = t<<14 | t>>(64-14)
a[0] = bc0 ^ (bc2 &^ bc1) ^ rc[i+1]
a[16] = bc1 ^ (bc3 &^ bc2)
a[7] = bc2 ^ (bc4 &^ bc3)
a[23] = bc3 ^ (bc0 &^ bc4)
a[14] = bc4 ^ (bc1 &^ bc0)
t = a[20] ^ d0
bc2 = t<<3 | t>>(64-3)
t = a[11] ^ d1
bc3 = t<<45 | t>>(64-45)
t = a[2] ^ d2
bc4 = t<<61 | t>>(64-61)
t = a[18] ^ d3
bc0 = t<<28 | t>>(64-28)
t = a[9] ^ d4
bc1 = t<<20 | t>>(64-20)
a[20] = bc0 ^ (bc2 &^ bc1)
a[11] = bc1 ^ (bc3 &^ bc2)
a[2] = bc2 ^ (bc4 &^ bc3)
a[18] = bc3 ^ (bc0 &^ bc4)
a[9] = bc4 ^ (bc1 &^ bc0)
t = a[15] ^ d0
bc4 = t<<18 | t>>(64-18)
t = a[6] ^ d1
bc0 = t<<1 | t>>(64-1)
t = a[22] ^ d2
bc1 = t<<6 | t>>(64-6)
t = a[13] ^ d3
bc2 = t<<25 | t>>(64-25)
t = a[4] ^ d4
bc3 = t<<8 | t>>(64-8)
a[15] = bc0 ^ (bc2 &^ bc1)
a[6] = bc1 ^ (bc3 &^ bc2)
a[22] = bc2 ^ (bc4 &^ bc3)
a[13] = bc3 ^ (bc0 &^ bc4)
a[4] = bc4 ^ (bc1 &^ bc0)
t = a[10] ^ d0
bc1 = t<<36 | t>>(64-36)
t = a[1] ^ d1
bc2 = t<<10 | t>>(64-10)
t = a[17] ^ d2
bc3 = t<<15 | t>>(64-15)
t = a[8] ^ d3
bc4 = t<<56 | t>>(64-56)
t = a[24] ^ d4
bc0 = t<<27 | t>>(64-27)
a[10] = bc0 ^ (bc2 &^ bc1)
a[1] = bc1 ^ (bc3 &^ bc2)
a[17] = bc2 ^ (bc4 &^ bc3)
a[8] = bc3 ^ (bc0 &^ bc4)
a[24] = bc4 ^ (bc1 &^ bc0)
t = a[5] ^ d0
bc3 = t<<41 | t>>(64-41)
t = a[21] ^ d1
bc4 = t<<2 | t>>(64-2)
t = a[12] ^ d2
bc0 = t<<62 | t>>(64-62)
t = a[3] ^ d3
bc1 = t<<55 | t>>(64-55)
t = a[19] ^ d4
bc2 = t<<39 | t>>(64-39)
a[5] = bc0 ^ (bc2 &^ bc1)
a[21] = bc1 ^ (bc3 &^ bc2)
a[12] = bc2 ^ (bc4 &^ bc3)
a[3] = bc3 ^ (bc0 &^ bc4)
a[19] = bc4 ^ (bc1 &^ bc0)
// Round 3
bc0 = a[0] ^ a[5] ^ a[10] ^ a[15] ^ a[20]
bc1 = a[1] ^ a[6] ^ a[11] ^ a[16] ^ a[21]
bc2 = a[2] ^ a[7] ^ a[12] ^ a[17] ^ a[22]
bc3 = a[3] ^ a[8] ^ a[13] ^ a[18] ^ a[23]
bc4 = a[4] ^ a[9] ^ a[14] ^ a[19] ^ a[24]
d0 = bc4 ^ (bc1<<1 | bc1>>63)
d1 = bc0 ^ (bc2<<1 | bc2>>63)
d2 = bc1 ^ (bc3<<1 | bc3>>63)
d3 = bc2 ^ (bc4<<1 | bc4>>63)
d4 = bc3 ^ (bc0<<1 | bc0>>63)
bc0 = a[0] ^ d0
t = a[11] ^ d1
bc1 = t<<44 | t>>(64-44)
t = a[22] ^ d2
bc2 = t<<43 | t>>(64-43)
t = a[8] ^ d3
bc3 = t<<21 | t>>(64-21)
t = a[19] ^ d4
bc4 = t<<14 | t>>(64-14)
a[0] = bc0 ^ (bc2 &^ bc1) ^ rc[i+2]
a[11] = bc1 ^ (bc3 &^ bc2)
a[22] = bc2 ^ (bc4 &^ bc3)
a[8] = bc3 ^ (bc0 &^ bc4)
a[19] = bc4 ^ (bc1 &^ bc0)
t = a[15] ^ d0
bc2 = t<<3 | t>>(64-3)
t = a[1] ^ d1
bc3 = t<<45 | t>>(64-45)
t = a[12] ^ d2
bc4 = t<<61 | t>>(64-61)
t = a[23] ^ d3
bc0 = t<<28 | t>>(64-28)
t = a[9] ^ d4
bc1 = t<<20 | t>>(64-20)
a[15] = bc0 ^ (bc2 &^ bc1)
a[1] = bc1 ^ (bc3 &^ bc2)
a[12] = bc2 ^ (bc4 &^ bc3)
a[23] = bc3 ^ (bc0 &^ bc4)
a[9] = bc4 ^ (bc1 &^ bc0)
t = a[5] ^ d0
bc4 = t<<18 | t>>(64-18)
t = a[16] ^ d1
bc0 = t<<1 | t>>(64-1)
t = a[2] ^ d2
bc1 = t<<6 | t>>(64-6)
t = a[13] ^ d3
bc2 = t<<25 | t>>(64-25)
t = a[24] ^ d4
bc3 = t<<8 | t>>(64-8)
a[5] = bc0 ^ (bc2 &^ bc1)
a[16] = bc1 ^ (bc3 &^ bc2)
a[2] = bc2 ^ (bc4 &^ bc3)
a[13] = bc3 ^ (bc0 &^ bc4)
a[24] = bc4 ^ (bc1 &^ bc0)
t = a[20] ^ d0
bc1 = t<<36 | t>>(64-36)
t = a[6] ^ d1
bc2 = t<<10 | t>>(64-10)
t = a[17] ^ d2
bc3 = t<<15 | t>>(64-15)
t = a[3] ^ d3
bc4 = t<<56 | t>>(64-56)
t = a[14] ^ d4
bc0 = t<<27 | t>>(64-27)
a[20] = bc0 ^ (bc2 &^ bc1)
a[6] = bc1 ^ (bc3 &^ bc2)
a[17] = bc2 ^ (bc4 &^ bc3)
a[3] = bc3 ^ (bc0 &^ bc4)
a[14] = bc4 ^ (bc1 &^ bc0)
t = a[10] ^ d0
bc3 = t<<41 | t>>(64-41)
t = a[21] ^ d1
bc4 = t<<2 | t>>(64-2)
t = a[7] ^ d2
bc0 = t<<62 | t>>(64-62)
t = a[18] ^ d3
bc1 = t<<55 | t>>(64-55)
t = a[4] ^ d4
bc2 = t<<39 | t>>(64-39)
a[10] = bc0 ^ (bc2 &^ bc1)
a[21] = bc1 ^ (bc3 &^ bc2)
a[7] = bc2 ^ (bc4 &^ bc3)
a[18] = bc3 ^ (bc0 &^ bc4)
a[4] = bc4 ^ (bc1 &^ bc0)
// Round 4
bc0 = a[0] ^ a[5] ^ a[10] ^ a[15] ^ a[20]
bc1 = a[1] ^ a[6] ^ a[11] ^ a[16] ^ a[21]
bc2 = a[2] ^ a[7] ^ a[12] ^ a[17] ^ a[22]
bc3 = a[3] ^ a[8] ^ a[13] ^ a[18] ^ a[23]
bc4 = a[4] ^ a[9] ^ a[14] ^ a[19] ^ a[24]
d0 = bc4 ^ (bc1<<1 | bc1>>63)
d1 = bc0 ^ (bc2<<1 | bc2>>63)
d2 = bc1 ^ (bc3<<1 | bc3>>63)
d3 = bc2 ^ (bc4<<1 | bc4>>63)
d4 = bc3 ^ (bc0<<1 | bc0>>63)
bc0 = a[0] ^ d0
t = a[1] ^ d1
bc1 = t<<44 | t>>(64-44)
t = a[2] ^ d2
bc2 = t<<43 | t>>(64-43)
t = a[3] ^ d3
bc3 = t<<21 | t>>(64-21)
t = a[4] ^ d4
bc4 = t<<14 | t>>(64-14)
a[0] = bc0 ^ (bc2 &^ bc1) ^ rc[i+3]
a[1] = bc1 ^ (bc3 &^ bc2)
a[2] = bc2 ^ (bc4 &^ bc3)
a[3] = bc3 ^ (bc0 &^ bc4)
a[4] = bc4 ^ (bc1 &^ bc0)
t = a[5] ^ d0
bc2 = t<<3 | t>>(64-3)
t = a[6] ^ d1
bc3 = t<<45 | t>>(64-45)
t = a[7] ^ d2
bc4 = t<<61 | t>>(64-61)
t = a[8] ^ d3
bc0 = t<<28 | t>>(64-28)
t = a[9] ^ d4
bc1 = t<<20 | t>>(64-20)
a[5] = bc0 ^ (bc2 &^ bc1)
a[6] = bc1 ^ (bc3 &^ bc2)
a[7] = bc2 ^ (bc4 &^ bc3)
a[8] = bc3 ^ (bc0 &^ bc4)
a[9] = bc4 ^ (bc1 &^ bc0)
t = a[10] ^ d0
bc4 = t<<18 | t>>(64-18)
t = a[11] ^ d1
bc0 = t<<1 | t>>(64-1)
t = a[12] ^ d2
bc1 = t<<6 | t>>(64-6)
t = a[13] ^ d3
bc2 = t<<25 | t>>(64-25)
t = a[14] ^ d4
bc3 = t<<8 | t>>(64-8)
a[10] = bc0 ^ (bc2 &^ bc1)
a[11] = bc1 ^ (bc3 &^ bc2)
a[12] = bc2 ^ (bc4 &^ bc3)
a[13] = bc3 ^ (bc0 &^ bc4)
a[14] = bc4 ^ (bc1 &^ bc0)
t = a[15] ^ d0
bc1 = t<<36 | t>>(64-36)
t = a[16] ^ d1
bc2 = t<<10 | t>>(64-10)
t = a[17] ^ d2
bc3 = t<<15 | t>>(64-15)
t = a[18] ^ d3
bc4 = t<<56 | t>>(64-56)
t = a[19] ^ d4
bc0 = t<<27 | t>>(64-27)
a[15] = bc0 ^ (bc2 &^ bc1)
a[16] = bc1 ^ (bc3 &^ bc2)
a[17] = bc2 ^ (bc4 &^ bc3)
a[18] = bc3 ^ (bc0 &^ bc4)
a[19] = bc4 ^ (bc1 &^ bc0)
t = a[20] ^ d0
bc3 = t<<41 | t>>(64-41)
t = a[21] ^ d1
bc4 = t<<2 | t>>(64-2)
t = a[22] ^ d2
bc0 = t<<62 | t>>(64-62)
t = a[23] ^ d3
bc1 = t<<55 | t>>(64-55)
t = a[24] ^ d4
bc2 = t<<39 | t>>(64-39)
a[20] = bc0 ^ (bc2 &^ bc1)
a[21] = bc1 ^ (bc3 &^ bc2)
a[22] = bc2 ^ (bc4 &^ bc3)
a[23] = bc3 ^ (bc0 &^ bc4)
a[24] = bc4 ^ (bc1 &^ bc0)
}
}

View File

@@ -0,0 +1,9 @@
{
"name": "crypto-sha3",
"author": "whyrusleeping",
"version": "1.0.0",
"language": "go",
"gx": {
"dvcsimport": "golang.org/x/crypto/sha3"
}
}

View File

@@ -0,0 +1,18 @@
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build go1.4
package sha3
import (
"crypto"
)
func init() {
crypto.RegisterHash(crypto.SHA3_224, New224)
crypto.RegisterHash(crypto.SHA3_256, New256)
crypto.RegisterHash(crypto.SHA3_384, New384)
crypto.RegisterHash(crypto.SHA3_512, New512)
}

View File

@@ -0,0 +1,193 @@
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package sha3
// spongeDirection indicates the direction bytes are flowing through the sponge.
type spongeDirection int
const (
// spongeAbsorbing indicates that the sponge is absorbing input.
spongeAbsorbing spongeDirection = iota
// spongeSqueezing indicates that the sponge is being squeezed.
spongeSqueezing
)
const (
// maxRate is the maximum size of the internal buffer. SHAKE-256
// currently needs the largest buffer.
maxRate = 168
)
type state struct {
// Generic sponge components.
a [25]uint64 // main state of the hash
buf []byte // points into storage
rate int // the number of bytes of state to use
// dsbyte contains the "domain separation" bits and the first bit of
// the padding. Sections 6.1 and 6.2 of [1] separate the outputs of the
// SHA-3 and SHAKE functions by appending bitstrings to the message.
// Using a little-endian bit-ordering convention, these are "01" for SHA-3
// and "1111" for SHAKE, or 00000010b and 00001111b, respectively. Then the
// padding rule from section 5.1 is applied to pad the message to a multiple
// of the rate, which involves adding a "1" bit, zero or more "0" bits, and
// a final "1" bit. We merge the first "1" bit from the padding into dsbyte,
// giving 00000110b (0x06) and 00011111b (0x1f).
// [1] http://csrc.nist.gov/publications/drafts/fips-202/fips_202_draft.pdf
// "Draft FIPS 202: SHA-3 Standard: Permutation-Based Hash and
// Extendable-Output Functions (May 2014)"
dsbyte byte
storage [maxRate]byte
// Specific to SHA-3 and SHAKE.
fixedOutput bool // whether this is a fixed-ouput-length instance
outputLen int // the default output size in bytes
state spongeDirection // whether the sponge is absorbing or squeezing
}
// BlockSize returns the rate of sponge underlying this hash function.
func (d *state) BlockSize() int { return d.rate }
// Size returns the output size of the hash function in bytes.
func (d *state) Size() int { return d.outputLen }
// Reset clears the internal state by zeroing the sponge state and
// the byte buffer, and setting Sponge.state to absorbing.
func (d *state) Reset() {
// Zero the permutation's state.
for i := range d.a {
d.a[i] = 0
}
d.state = spongeAbsorbing
d.buf = d.storage[:0]
}
func (d *state) clone() *state {
ret := *d
if ret.state == spongeAbsorbing {
ret.buf = ret.storage[:len(ret.buf)]
} else {
ret.buf = ret.storage[d.rate-cap(d.buf) : d.rate]
}
return &ret
}
// permute applies the KeccakF-1600 permutation. It handles
// any input-output buffering.
func (d *state) permute() {
switch d.state {
case spongeAbsorbing:
// If we're absorbing, we need to xor the input into the state
// before applying the permutation.
xorIn(d, d.buf)
d.buf = d.storage[:0]
keccakF1600(&d.a)
case spongeSqueezing:
// If we're squeezing, we need to apply the permutatin before
// copying more output.
keccakF1600(&d.a)
d.buf = d.storage[:d.rate]
copyOut(d, d.buf)
}
}
// pads appends the domain separation bits in dsbyte, applies
// the multi-bitrate 10..1 padding rule, and permutes the state.
func (d *state) padAndPermute(dsbyte byte) {
if d.buf == nil {
d.buf = d.storage[:0]
}
// Pad with this instance's domain-separator bits. We know that there's
// at least one byte of space in d.buf because, if it were full,
// permute would have been called to empty it. dsbyte also contains the
// first one bit for the padding. See the comment in the state struct.
d.buf = append(d.buf, dsbyte)
zerosStart := len(d.buf)
d.buf = d.storage[:d.rate]
for i := zerosStart; i < d.rate; i++ {
d.buf[i] = 0
}
// This adds the final one bit for the padding. Because of the way that
// bits are numbered from the LSB upwards, the final bit is the MSB of
// the last byte.
d.buf[d.rate-1] ^= 0x80
// Apply the permutation
d.permute()
d.state = spongeSqueezing
d.buf = d.storage[:d.rate]
copyOut(d, d.buf)
}
// Write absorbs more data into the hash's state. It produces an error
// if more data is written to the ShakeHash after writing
func (d *state) Write(p []byte) (written int, err error) {
if d.state != spongeAbsorbing {
panic("sha3: write to sponge after read")
}
if d.buf == nil {
d.buf = d.storage[:0]
}
written = len(p)
for len(p) > 0 {
if len(d.buf) == 0 && len(p) >= d.rate {
// The fast path; absorb a full "rate" bytes of input and apply the permutation.
xorIn(d, p[:d.rate])
p = p[d.rate:]
keccakF1600(&d.a)
} else {
// The slow path; buffer the input until we can fill the sponge, and then xor it in.
todo := d.rate - len(d.buf)
if todo > len(p) {
todo = len(p)
}
d.buf = append(d.buf, p[:todo]...)
p = p[todo:]
// If the sponge is full, apply the permutation.
if len(d.buf) == d.rate {
d.permute()
}
}
}
return
}
// Read squeezes an arbitrary number of bytes from the sponge.
func (d *state) Read(out []byte) (n int, err error) {
// If we're still absorbing, pad and apply the permutation.
if d.state == spongeAbsorbing {
d.padAndPermute(d.dsbyte)
}
n = len(out)
// Now, do the squeezing.
for len(out) > 0 {
n := copy(out, d.buf)
d.buf = d.buf[n:]
out = out[n:]
// Apply the permutation if we've squeezed the sponge dry.
if len(d.buf) == 0 {
d.permute()
}
}
return
}
// Sum applies padding to the hash state and then squeezes out the desired
// number of output bytes.
func (d *state) Sum(in []byte) []byte {
// Make a copy of the original hash so that caller can keep writing
// and summing.
dup := d.clone()
hash := make([]byte, dup.outputLen)
dup.Read(hash)
return append(in, hash...)
}

View File

@@ -0,0 +1,306 @@
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package sha3
// Tests include all the ShortMsgKATs provided by the Keccak team at
// https://github.com/gvanas/KeccakCodePackage
//
// They only include the zero-bit case of the bitwise testvectors
// published by NIST in the draft of FIPS-202.
import (
"bytes"
"compress/flate"
"encoding/hex"
"encoding/json"
"hash"
"os"
"strings"
"testing"
)
const (
testString = "brekeccakkeccak koax koax"
katFilename = "testdata/keccakKats.json.deflate"
)
// Internal-use instances of SHAKE used to test against KATs.
func newHashShake128() hash.Hash {
return &state{rate: 168, dsbyte: 0x1f, outputLen: 512}
}
func newHashShake256() hash.Hash {
return &state{rate: 136, dsbyte: 0x1f, outputLen: 512}
}
// testDigests contains functions returning hash.Hash instances
// with output-length equal to the KAT length for both SHA-3 and
// SHAKE instances.
var testDigests = map[string]func() hash.Hash{
"SHA3-224": New224,
"SHA3-256": New256,
"SHA3-384": New384,
"SHA3-512": New512,
"SHAKE128": newHashShake128,
"SHAKE256": newHashShake256,
}
// testShakes contains functions that return ShakeHash instances for
// testing the ShakeHash-specific interface.
var testShakes = map[string]func() ShakeHash{
"SHAKE128": NewShake128,
"SHAKE256": NewShake256,
}
// decodeHex converts a hex-encoded string into a raw byte string.
func decodeHex(s string) []byte {
b, err := hex.DecodeString(s)
if err != nil {
panic(err)
}
return b
}
// structs used to marshal JSON test-cases.
type KeccakKats struct {
Kats map[string][]struct {
Digest string `json:"digest"`
Length int64 `json:"length"`
Message string `json:"message"`
}
}
func testUnalignedAndGeneric(t *testing.T, testf func(impl string)) {
xorInOrig, copyOutOrig := xorIn, copyOut
xorIn, copyOut = xorInGeneric, copyOutGeneric
testf("generic")
if xorImplementationUnaligned != "generic" {
xorIn, copyOut = xorInUnaligned, copyOutUnaligned
testf("unaligned")
}
xorIn, copyOut = xorInOrig, copyOutOrig
}
// TestKeccakKats tests the SHA-3 and Shake implementations against all the
// ShortMsgKATs from https://github.com/gvanas/KeccakCodePackage
// (The testvectors are stored in keccakKats.json.deflate due to their length.)
func TestKeccakKats(t *testing.T) {
testUnalignedAndGeneric(t, func(impl string) {
// Read the KATs.
deflated, err := os.Open(katFilename)
if err != nil {
t.Errorf("error opening %s: %s", katFilename, err)
}
file := flate.NewReader(deflated)
dec := json.NewDecoder(file)
var katSet KeccakKats
err = dec.Decode(&katSet)
if err != nil {
t.Errorf("error decoding KATs: %s", err)
}
// Do the KATs.
for functionName, kats := range katSet.Kats {
d := testDigests[functionName]()
for _, kat := range kats {
d.Reset()
in, err := hex.DecodeString(kat.Message)
if err != nil {
t.Errorf("error decoding KAT: %s", err)
}
d.Write(in[:kat.Length/8])
got := strings.ToUpper(hex.EncodeToString(d.Sum(nil)))
if got != kat.Digest {
t.Errorf("function=%s, implementation=%s, length=%d\nmessage:\n %s\ngot:\n %s\nwanted:\n %s",
functionName, impl, kat.Length, kat.Message, got, kat.Digest)
t.Logf("wanted %+v", kat)
t.FailNow()
}
continue
}
}
})
}
// TestUnalignedWrite tests that writing data in an arbitrary pattern with
// small input buffers.
func testUnalignedWrite(t *testing.T) {
testUnalignedAndGeneric(t, func(impl string) {
buf := sequentialBytes(0x10000)
for alg, df := range testDigests {
d := df()
d.Reset()
d.Write(buf)
want := d.Sum(nil)
d.Reset()
for i := 0; i < len(buf); {
// Cycle through offsets which make a 137 byte sequence.
// Because 137 is prime this sequence should exercise all corner cases.
offsets := [17]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1}
for _, j := range offsets {
if v := len(buf) - i; v < j {
j = v
}
d.Write(buf[i : i+j])
i += j
}
}
got := d.Sum(nil)
if !bytes.Equal(got, want) {
t.Errorf("Unaligned writes, implementation=%s, alg=%s\ngot %q, want %q", impl, alg, got, want)
}
}
})
}
// TestAppend checks that appending works when reallocation is necessary.
func TestAppend(t *testing.T) {
testUnalignedAndGeneric(t, func(impl string) {
d := New224()
for capacity := 2; capacity <= 66; capacity += 64 {
// The first time around the loop, Sum will have to reallocate.
// The second time, it will not.
buf := make([]byte, 2, capacity)
d.Reset()
d.Write([]byte{0xcc})
buf = d.Sum(buf)
expected := "0000DF70ADC49B2E76EEE3A6931B93FA41841C3AF2CDF5B32A18B5478C39"
if got := strings.ToUpper(hex.EncodeToString(buf)); got != expected {
t.Errorf("got %s, want %s", got, expected)
}
}
})
}
// TestAppendNoRealloc tests that appending works when no reallocation is necessary.
func TestAppendNoRealloc(t *testing.T) {
testUnalignedAndGeneric(t, func(impl string) {
buf := make([]byte, 1, 200)
d := New224()
d.Write([]byte{0xcc})
buf = d.Sum(buf)
expected := "00DF70ADC49B2E76EEE3A6931B93FA41841C3AF2CDF5B32A18B5478C39"
if got := strings.ToUpper(hex.EncodeToString(buf)); got != expected {
t.Errorf("%s: got %s, want %s", impl, got, expected)
}
})
}
// TestSqueezing checks that squeezing the full output a single time produces
// the same output as repeatedly squeezing the instance.
func TestSqueezing(t *testing.T) {
testUnalignedAndGeneric(t, func(impl string) {
for functionName, newShakeHash := range testShakes {
d0 := newShakeHash()
d0.Write([]byte(testString))
ref := make([]byte, 32)
d0.Read(ref)
d1 := newShakeHash()
d1.Write([]byte(testString))
var multiple []byte
for _ = range ref {
one := make([]byte, 1)
d1.Read(one)
multiple = append(multiple, one...)
}
if !bytes.Equal(ref, multiple) {
t.Errorf("%s (%s): squeezing %d bytes one at a time failed", functionName, impl, len(ref))
}
}
})
}
// sequentialBytes produces a buffer of size consecutive bytes 0x00, 0x01, ..., used for testing.
func sequentialBytes(size int) []byte {
result := make([]byte, size)
for i := range result {
result[i] = byte(i)
}
return result
}
// BenchmarkPermutationFunction measures the speed of the permutation function
// with no input data.
func BenchmarkPermutationFunction(b *testing.B) {
b.SetBytes(int64(200))
var lanes [25]uint64
for i := 0; i < b.N; i++ {
keccakF1600(&lanes)
}
}
// benchmarkHash tests the speed to hash num buffers of buflen each.
func benchmarkHash(b *testing.B, h hash.Hash, size, num int) {
b.StopTimer()
h.Reset()
data := sequentialBytes(size)
b.SetBytes(int64(size * num))
b.StartTimer()
var state []byte
for i := 0; i < b.N; i++ {
for j := 0; j < num; j++ {
h.Write(data)
}
state = h.Sum(state[:0])
}
b.StopTimer()
h.Reset()
}
// benchmarkShake is specialized to the Shake instances, which don't
// require a copy on reading output.
func benchmarkShake(b *testing.B, h ShakeHash, size, num int) {
b.StopTimer()
h.Reset()
data := sequentialBytes(size)
d := make([]byte, 32)
b.SetBytes(int64(size * num))
b.StartTimer()
for i := 0; i < b.N; i++ {
h.Reset()
for j := 0; j < num; j++ {
h.Write(data)
}
h.Read(d)
}
}
func BenchmarkSha3_512_MTU(b *testing.B) { benchmarkHash(b, New512(), 1350, 1) }
func BenchmarkSha3_384_MTU(b *testing.B) { benchmarkHash(b, New384(), 1350, 1) }
func BenchmarkSha3_256_MTU(b *testing.B) { benchmarkHash(b, New256(), 1350, 1) }
func BenchmarkSha3_224_MTU(b *testing.B) { benchmarkHash(b, New224(), 1350, 1) }
func BenchmarkShake128_MTU(b *testing.B) { benchmarkShake(b, NewShake128(), 1350, 1) }
func BenchmarkShake256_MTU(b *testing.B) { benchmarkShake(b, NewShake256(), 1350, 1) }
func BenchmarkShake256_16x(b *testing.B) { benchmarkShake(b, NewShake256(), 16, 1024) }
func BenchmarkShake256_1MiB(b *testing.B) { benchmarkShake(b, NewShake256(), 1024, 1024) }
func BenchmarkSha3_512_1MiB(b *testing.B) { benchmarkHash(b, New512(), 1024, 1024) }
func Example_sum() {
buf := []byte("some data to hash")
// A hash needs to be 64 bytes long to have 256-bit collision resistance.
h := make([]byte, 64)
// Compute a 64-byte hash of buf and put it in h.
ShakeSum256(h, buf)
}
func Example_mac() {
k := []byte("this is a secret key; you should generate a strong random key that's at least 32 bytes long")
buf := []byte("and this is some data to authenticate")
// A MAC with 32 bytes of output has 256-bit security strength -- if you use at least a 32-byte-long key.
h := make([]byte, 32)
d := NewShake256()
// Write the key into the hash.
d.Write(k)
// Now write the data.
d.Write(buf)
// Read 32 bytes of output from the hash into h.
d.Read(h)
}

View File

@@ -0,0 +1,60 @@
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package sha3
// This file defines the ShakeHash interface, and provides
// functions for creating SHAKE instances, as well as utility
// functions for hashing bytes to arbitrary-length output.
import (
"io"
)
// ShakeHash defines the interface to hash functions that
// support arbitrary-length output.
type ShakeHash interface {
// Write absorbs more data into the hash's state. It panics if input is
// written to it after output has been read from it.
io.Writer
// Read reads more output from the hash; reading affects the hash's
// state. (ShakeHash.Read is thus very different from Hash.Sum)
// It never returns an error.
io.Reader
// Clone returns a copy of the ShakeHash in its current state.
Clone() ShakeHash
// Reset resets the ShakeHash to its initial state.
Reset()
}
func (d *state) Clone() ShakeHash {
return d.clone()
}
// NewShake128 creates a new SHAKE128 variable-output-length ShakeHash.
// Its generic security strength is 128 bits against all attacks if at
// least 32 bytes of its output are used.
func NewShake128() ShakeHash { return &state{rate: 168, dsbyte: 0x1f} }
// NewShake256 creates a new SHAKE128 variable-output-length ShakeHash.
// Its generic security strength is 256 bits against all attacks if
// at least 64 bytes of its output are used.
func NewShake256() ShakeHash { return &state{rate: 136, dsbyte: 0x1f} }
// ShakeSum128 writes an arbitrary-length digest of data into hash.
func ShakeSum128(hash, data []byte) {
h := NewShake128()
h.Write(data)
h.Read(hash)
}
// ShakeSum256 writes an arbitrary-length digest of data into hash.
func ShakeSum256(hash, data []byte) {
h := NewShake256()
h.Write(data)
h.Read(hash)
}

View File

@@ -0,0 +1,16 @@
// Copyright 2015 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 !amd64,!386 appengine
package sha3
var (
xorIn = xorInGeneric
copyOut = copyOutGeneric
xorInUnaligned = xorInGeneric
copyOutUnaligned = copyOutGeneric
)
const xorImplementationUnaligned = "generic"

View File

@@ -0,0 +1,28 @@
// Copyright 2015 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 sha3
import "encoding/binary"
// xorInGeneric xors the bytes in buf into the state; it
// makes no non-portable assumptions about memory layout
// or alignment.
func xorInGeneric(d *state, buf []byte) {
n := len(buf) / 8
for i := 0; i < n; i++ {
a := binary.LittleEndian.Uint64(buf)
d.a[i] ^= a
buf = buf[8:]
}
}
// copyOutGeneric copies ulint64s to a byte buffer.
func copyOutGeneric(d *state, b []byte) {
for i := 0; len(b) >= 8; i++ {
binary.LittleEndian.PutUint64(b, d.a[i])
b = b[8:]
}
}

View File

@@ -0,0 +1,58 @@
// Copyright 2015 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 amd64 386
// +build !appengine
package sha3
import "unsafe"
func xorInUnaligned(d *state, buf []byte) {
bw := (*[maxRate / 8]uint64)(unsafe.Pointer(&buf[0]))
n := len(buf)
if n >= 72 {
d.a[0] ^= bw[0]
d.a[1] ^= bw[1]
d.a[2] ^= bw[2]
d.a[3] ^= bw[3]
d.a[4] ^= bw[4]
d.a[5] ^= bw[5]
d.a[6] ^= bw[6]
d.a[7] ^= bw[7]
d.a[8] ^= bw[8]
}
if n >= 104 {
d.a[9] ^= bw[9]
d.a[10] ^= bw[10]
d.a[11] ^= bw[11]
d.a[12] ^= bw[12]
}
if n >= 136 {
d.a[13] ^= bw[13]
d.a[14] ^= bw[14]
d.a[15] ^= bw[15]
d.a[16] ^= bw[16]
}
if n >= 144 {
d.a[17] ^= bw[17]
}
if n >= 168 {
d.a[18] ^= bw[18]
d.a[19] ^= bw[19]
d.a[20] ^= bw[20]
}
}
func copyOutUnaligned(d *state, buf []byte) {
ab := (*[maxRate]uint8)(unsafe.Pointer(&d.a[0]))
copy(buf, ab[:])
}
var (
xorIn = xorInUnaligned
copyOut = copyOutUnaligned
)
const xorImplementationUnaligned = "unaligned"

View File

@@ -0,0 +1,9 @@
language: go
go:
- 1.3
- release
- tip
script:
- go test -race -cpu=5 -v ./...

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014 Juan Batiz-Benet
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,58 @@
# go-multiaddr
[multiaddr](https://github.com/jbenet/multiaddr) implementation in Go.
## Example
### Simple
```go
import ma "github.com/jbenet/go-multiaddr"
// construct from a string (err signals parse failure)
m1, err := ma.NewMultiaddr("/ip4/127.0.0.1/udp/1234")
// construct from bytes (err signals parse failure)
m2, err := ma.NewMultiaddrBytes(m1.Bytes())
// true
strings.Equal(m1.String(), "/ip4/127.0.0.1/udp/1234")
strings.Equal(m1.String(), m2.String())
bytes.Equal(m1.Bytes(), m2.Bytes())
m1.Equal(m2)
m2.Equal(m1)
```
### Protocols
```go
// get the multiaddr protocol description objects
addr.Protocols()
// []Protocol{
// Protocol{ Code: 4, Name: 'ip4', Size: 32},
// Protocol{ Code: 17, Name: 'udp', Size: 16},
// }
```
### En/decapsulate
```go
m.Encapsulate(ma.NewMultiaddr("/sctp/5678"))
// <Multiaddr /ip4/127.0.0.1/udp/1234/sctp/5678>
m.Decapsulate(ma.NewMultiaddr("/udp")) // up to + inc last occurrence of subaddr
// <Multiaddr /ip4/127.0.0.1>
```
### Tunneling
Multiaddr allows expressing tunnels very nicely.
```js
printer, _ := ma.NewMultiaddr("/ip4/192.168.0.13/tcp/80")
proxy, _ := ma.NewMultiaddr("/ip4/10.20.30.40/tcp/443")
printerOverProxy := proxy.Encapsulate(printer)
// /ip4/10.20.30.40/tcp/443/ip4/192.168.0.13/tcp/80
proxyAgain := printerOverProxy.Decapsulate(printer)
// /ip4/10.20.30.40/tcp/443
```

View File

@@ -0,0 +1,244 @@
package multiaddr
import (
"encoding/base32"
"encoding/binary"
"errors"
"fmt"
"net"
"strconv"
"strings"
mh "QmdeauTdyf38KDQB4Cc4CurPWRRb5pej27NCXPA7kbPTJy/go-multihash"
)
func stringToBytes(s string) ([]byte, error) {
// consume trailing slashes
s = strings.TrimRight(s, "/")
b := []byte{}
sp := strings.Split(s, "/")
if sp[0] != "" {
return nil, fmt.Errorf("invalid multiaddr, must begin with /")
}
// consume first empty elem
sp = sp[1:]
for len(sp) > 0 {
p := ProtocolWithName(sp[0])
if p.Code == 0 {
return nil, fmt.Errorf("no protocol with name %s", sp[0])
}
b = append(b, CodeToVarint(p.Code)...)
sp = sp[1:]
if p.Size == 0 { // no length.
continue
}
if len(sp) < 1 {
return nil, fmt.Errorf("protocol requires address, none given: %s", p.Name)
}
a, err := addressStringToBytes(p, sp[0])
if err != nil {
return nil, fmt.Errorf("failed to parse %s: %s %s", p.Name, sp[0], err)
}
b = append(b, a...)
sp = sp[1:]
}
return b, nil
}
func bytesToString(b []byte) (ret string, err error) {
// panic handler, in case we try accessing bytes incorrectly.
defer func() {
if e := recover(); e != nil {
ret = ""
switch e := e.(type) {
case error:
err = e
case string:
err = errors.New(e)
default:
err = fmt.Errorf("%v", e)
}
}
}()
s := ""
for len(b) > 0 {
code, n := ReadVarintCode(b)
b = b[n:]
p := ProtocolWithCode(code)
if p.Code == 0 {
return "", fmt.Errorf("no protocol with code %d", code)
}
s += "/" + p.Name
if p.Size == 0 {
continue
}
size := sizeForAddr(p, b)
a, err := addressBytesToString(p, b[:size])
if err != nil {
return "", err
}
if len(a) > 0 {
s += "/" + a
}
b = b[size:]
}
return s, nil
}
func sizeForAddr(p Protocol, b []byte) int {
switch {
case p.Size > 0:
return (p.Size / 8)
case p.Size == 0:
return 0
default:
size, n := ReadVarintCode(b)
return size + n
}
}
func bytesSplit(b []byte) (ret [][]byte, err error) {
// panic handler, in case we try accessing bytes incorrectly.
defer func() {
if e := recover(); e != nil {
ret = [][]byte{}
err = e.(error)
}
}()
ret = [][]byte{}
for len(b) > 0 {
code, n := ReadVarintCode(b)
p := ProtocolWithCode(code)
if p.Code == 0 {
return [][]byte{}, fmt.Errorf("no protocol with code %d", b[0])
}
size := sizeForAddr(p, b[n:])
length := n + size
ret = append(ret, b[:length])
b = b[length:]
}
return ret, nil
}
func addressStringToBytes(p Protocol, s string) ([]byte, error) {
switch p.Code {
case P_IP4: // ipv4
i := net.ParseIP(s).To4()
if i == nil {
return nil, fmt.Errorf("failed to parse ip4 addr: %s", s)
}
return i, nil
case P_IP6: // ipv6
i := net.ParseIP(s).To16()
if i == nil {
return nil, fmt.Errorf("failed to parse ip6 addr: %s", s)
}
return i, nil
// tcp udp dccp sctp
case P_TCP, P_UDP, P_DCCP, P_SCTP:
i, err := strconv.Atoi(s)
if err != nil {
return nil, fmt.Errorf("failed to parse %s addr: %s", p.Name, err)
}
if i >= 65536 {
return nil, fmt.Errorf("failed to parse %s addr: %s", p.Name, "greater than 65536")
}
b := make([]byte, 2)
binary.BigEndian.PutUint16(b, uint16(i))
return b, nil
case P_ONION:
addr := strings.Split(s, ":")
if len(addr) != 2 {
return nil, fmt.Errorf("failed to parse %s addr: %s does not contain a port number.", p.Name, s)
}
// onion address without the ".onion" substring
if len(addr[0]) != 16 {
return nil, fmt.Errorf("failed to parse %s addr: %s not a Tor onion address.", p.Name, s)
}
onionHostBytes, err := base32.StdEncoding.DecodeString(strings.ToUpper(addr[0]))
if err != nil {
return nil, fmt.Errorf("failed to decode base32 %s addr: %s %s", p.Name, s, err)
}
// onion port number
i, err := strconv.Atoi(addr[1])
if err != nil {
return nil, fmt.Errorf("failed to parse %s addr: %s", p.Name, err)
}
if i >= 65536 {
return nil, fmt.Errorf("failed to parse %s addr: %s", p.Name, "port greater than 65536")
}
if i < 1 {
return nil, fmt.Errorf("failed to parse %s addr: %s", p.Name, "port less than 1")
}
onionPortBytes := make([]byte, 2)
binary.BigEndian.PutUint16(onionPortBytes, uint16(i))
bytes := []byte{}
bytes = append(bytes, onionHostBytes...)
bytes = append(bytes, onionPortBytes...)
return bytes, nil
case P_IPFS: // ipfs
// the address is a varint prefixed multihash string representation
m, err := mh.FromB58String(s)
if err != nil {
return nil, fmt.Errorf("failed to parse ipfs addr: %s %s", s, err)
}
size := CodeToVarint(len(m))
b := append(size, m...)
return b, nil
}
return []byte{}, fmt.Errorf("failed to parse %s addr: unknown", p.Name)
}
func addressBytesToString(p Protocol, b []byte) (string, error) {
switch p.Code {
// ipv4,6
case P_IP4, P_IP6:
return net.IP(b).String(), nil
// tcp udp dccp sctp
case P_TCP, P_UDP, P_DCCP, P_SCTP:
i := binary.BigEndian.Uint16(b)
return strconv.Itoa(int(i)), nil
case P_IPFS: // ipfs
// the address is a varint-prefixed multihash string representation
size, n := ReadVarintCode(b)
b = b[n:]
if len(b) != size {
panic("inconsistent lengths")
}
m, err := mh.Cast(b)
if err != nil {
return "", err
}
return m.B58String(), nil
}
return "", fmt.Errorf("unknown protocol")
}

View File

@@ -0,0 +1,36 @@
/*
Package multiaddr provides an implementation of the Multiaddr network
address format. Multiaddr emphasizes explicitness, self-description, and
portability. It allows applications to treat addresses as opaque tokens,
and to avoid making assumptions about the address representation (e.g. length).
Learn more at https://github.com/jbenet/multiaddr
Basic Use:
import (
"bytes"
"strings"
ma "github.com/jbenet/go-multiaddr"
)
// construct from a string (err signals parse failure)
m1, err := ma.NewMultiaddr("/ip4/127.0.0.1/udp/1234")
// construct from bytes (err signals parse failure)
m2, err := ma.NewMultiaddrBytes(m1.Bytes())
// true
strings.Equal(m1.String(), "/ip4/127.0.0.1/udp/1234")
strings.Equal(m1.String(), m2.String())
bytes.Equal(m1.Bytes(), m2.Bytes())
m1.Equal(m2)
m2.Equal(m1)
// tunneling (en/decap)
printer, _ := ma.NewMultiaddr("/ip4/192.168.0.13/tcp/80")
proxy, _ := ma.NewMultiaddr("/ip4/10.20.30.40/tcp/443")
printerOverProxy := proxy.Encapsulate(printer)
proxyAgain := printerOverProxy.Decapsulate(printer)
*/
package multiaddr

View File

@@ -0,0 +1,42 @@
package multiaddr
/*
Multiaddr is a cross-protocol, cross-platform format for representing
internet addresses. It emphasizes explicitness and self-description.
Learn more here: https://github.com/jbenet/multiaddr
Multiaddrs have both a binary and string representation.
import ma "github.com/jbenet/go-multiaddr"
addr, err := ma.NewMultiaddr("/ip4/1.2.3.4/tcp/80")
// err non-nil when parsing failed.
*/
type Multiaddr interface {
// Equal returns whether two Multiaddrs are exactly equal
Equal(Multiaddr) bool
// Bytes returns the []byte representation of this Multiaddr
Bytes() []byte
// String returns the string representation of this Multiaddr
// (may panic if internal state is corrupted)
String() string
// Protocols returns the list of Protocols this Multiaddr includes
// will panic if protocol code incorrect (and bytes accessed incorrectly)
Protocols() []Protocol
// Encapsulate wraps this Multiaddr around another. For example:
//
// /ip4/1.2.3.4 encapsulate /tcp/80 = /ip4/1.2.3.4/tcp/80
//
Encapsulate(Multiaddr) Multiaddr
// Decapsultate removes a Multiaddr wrapping. For example:
//
// /ip4/1.2.3.4/tcp/80 decapsulate /ip4/1.2.3.4 = /tcp/80
//
Decapsulate(Multiaddr) Multiaddr
}

View File

@@ -0,0 +1,115 @@
package multiaddr
import (
"bytes"
"fmt"
"strings"
)
// multiaddr is the data structure representing a Multiaddr
type multiaddr struct {
bytes []byte
}
// NewMultiaddr parses and validates an input string, returning a *Multiaddr
func NewMultiaddr(s string) (Multiaddr, error) {
b, err := stringToBytes(s)
if err != nil {
return nil, err
}
return &multiaddr{bytes: b}, nil
}
// NewMultiaddrBytes initializes a Multiaddr from a byte representation.
// It validates it as an input string.
func NewMultiaddrBytes(b []byte) (Multiaddr, error) {
s, err := bytesToString(b)
if err != nil {
return nil, err
}
return NewMultiaddr(s)
}
// Equal tests whether two multiaddrs are equal
func (m *multiaddr) Equal(m2 Multiaddr) bool {
return bytes.Equal(m.bytes, m2.Bytes())
}
// Bytes returns the []byte representation of this Multiaddr
func (m *multiaddr) Bytes() []byte {
// consider returning copy to prevent changing underneath us?
cpy := make([]byte, len(m.bytes))
copy(cpy, m.bytes)
return cpy
}
// String returns the string representation of a Multiaddr
func (m *multiaddr) String() string {
s, err := bytesToString(m.bytes)
if err != nil {
panic("multiaddr failed to convert back to string. corrupted?")
}
return s
}
// Protocols returns the list of protocols this Multiaddr has.
// will panic in case we access bytes incorrectly.
func (m *multiaddr) Protocols() []Protocol {
// panic handler, in case we try accessing bytes incorrectly.
defer func() {
if e := recover(); e != nil {
err := e.(error)
panic("Multiaddr.Protocols error: " + err.Error())
}
}()
size := 0
ps := []Protocol{}
b := m.bytes[:]
for len(b) > 0 {
code, n := ReadVarintCode(b)
p := ProtocolWithCode(code)
if p.Code == 0 {
// this is a panic (and not returning err) because this should've been
// caught on constructing the Multiaddr
panic(fmt.Errorf("no protocol with code %d", b[0]))
}
ps = append(ps, p)
b = b[n:]
size = sizeForAddr(p, b)
b = b[size:]
}
return ps
}
// Encapsulate wraps a given Multiaddr, returning the resulting joined Multiaddr
func (m *multiaddr) Encapsulate(o Multiaddr) Multiaddr {
mb := m.bytes
ob := o.Bytes()
b := make([]byte, len(mb)+len(ob))
copy(b, mb)
copy(b[len(mb):], ob)
return &multiaddr{bytes: b}
}
// Decapsulate unwraps Multiaddr up until the given Multiaddr is found.
func (m *multiaddr) Decapsulate(o Multiaddr) Multiaddr {
s1 := m.String()
s2 := o.String()
i := strings.LastIndex(s1, s2)
if i < 0 {
// if multiaddr not contained, returns a copy.
cpy := make([]byte, len(m.bytes))
copy(cpy, m.bytes)
return &multiaddr{bytes: cpy}
}
ma, err := NewMultiaddr(s1[:i])
if err != nil {
panic("Multiaddr.Decapsulate incorrect byte boundaries.")
}
return ma
}

View File

@@ -0,0 +1,302 @@
package multiaddr
import (
"bytes"
"encoding/hex"
"testing"
)
func newMultiaddr(t *testing.T, a string) Multiaddr {
m, err := NewMultiaddr(a)
if err != nil {
t.Error(err)
}
return m
}
func TestConstructFails(t *testing.T) {
cases := []string{
"/ip4",
"/ip4/::1",
"/ip4/fdpsofodsajfdoisa",
"/ip6",
"/udp",
"/tcp",
"/sctp",
"/udp/65536",
"/tcp/65536",
"/onion/9imaq4ygg2iegci7:80",
"/onion/aaimaq4ygg2iegci7:80",
"/onion/timaq4ygg2iegci7:0",
"/onion/timaq4ygg2iegci7:-1",
"/onion/timaq4ygg2iegci7",
"/onion/timaq4ygg2iegci@:666",
"/udp/1234/sctp",
"/udp/1234/udt/1234",
"/udp/1234/utp/1234",
"/ip4/127.0.0.1/udp/jfodsajfidosajfoidsa",
"/ip4/127.0.0.1/udp",
"/ip4/127.0.0.1/tcp/jfodsajfidosajfoidsa",
"/ip4/127.0.0.1/tcp",
"/ip4/127.0.0.1/ipfs",
"/ip4/127.0.0.1/ipfs/tcp",
}
for _, a := range cases {
if _, err := NewMultiaddr(a); err == nil {
t.Errorf("should have failed: %s - %s", a, err)
}
}
}
func TestConstructSucceeds(t *testing.T) {
cases := []string{
"/ip4/1.2.3.4",
"/ip4/0.0.0.0",
"/ip6/::1",
"/ip6/2601:9:4f81:9700:803e:ca65:66e8:c21",
"/onion/timaq4ygg2iegci7:1234",
"/onion/timaq4ygg2iegci7:80/http",
"/udp/0",
"/tcp/0",
"/sctp/0",
"/udp/1234",
"/tcp/1234",
"/sctp/1234",
"/udp/65535",
"/tcp/65535",
"/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC",
"/udp/1234/sctp/1234",
"/udp/1234/udt",
"/udp/1234/utp",
"/tcp/1234/http",
"/tcp/1234/https",
"/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC/tcp/1234",
"/ip4/127.0.0.1/udp/1234",
"/ip4/127.0.0.1/udp/0",
"/ip4/127.0.0.1/tcp/1234",
"/ip4/127.0.0.1/tcp/1234/",
"/ip4/127.0.0.1/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC",
"/ip4/127.0.0.1/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC/tcp/1234",
}
for _, a := range cases {
if _, err := NewMultiaddr(a); err != nil {
t.Errorf("should have succeeded: %s -- %s", a, err)
}
}
}
func TestEqual(t *testing.T) {
m1 := newMultiaddr(t, "/ip4/127.0.0.1/udp/1234")
m2 := newMultiaddr(t, "/ip4/127.0.0.1/tcp/1234")
m3 := newMultiaddr(t, "/ip4/127.0.0.1/tcp/1234")
m4 := newMultiaddr(t, "/ip4/127.0.0.1/tcp/1234/")
if m1.Equal(m2) {
t.Error("should not be equal")
}
if m2.Equal(m1) {
t.Error("should not be equal")
}
if !m2.Equal(m3) {
t.Error("should be equal")
}
if !m3.Equal(m2) {
t.Error("should be equal")
}
if !m1.Equal(m1) {
t.Error("should be equal")
}
if !m2.Equal(m4) {
t.Error("should be equal")
}
if !m4.Equal(m3) {
t.Error("should be equal")
}
}
func TestStringToBytes(t *testing.T) {
testString := func(s string, h string) {
b1, err := hex.DecodeString(h)
if err != nil {
t.Error("failed to decode hex", h)
}
b2, err := stringToBytes(s)
if err != nil {
t.Error("failed to convert", s)
}
if !bytes.Equal(b1, b2) {
t.Error("failed to convert", s, "to", b1, "got", b2)
}
}
testString("/ip4/127.0.0.1/udp/1234", "047f0000011104d2")
testString("/ip4/127.0.0.1/tcp/4321", "047f0000010610e1")
testString("/ip4/127.0.0.1/udp/1234/ip4/127.0.0.1/tcp/4321", "047f0000011104d2047f0000010610e1")
}
func TestBytesToString(t *testing.T) {
testString := func(s1 string, h string) {
b, err := hex.DecodeString(h)
if err != nil {
t.Error("failed to decode hex", h)
}
s2, err := bytesToString(b)
if err != nil {
t.Error("failed to convert", b)
}
if s1 != s2 {
t.Error("failed to convert", b, "to", s1, "got", s2)
}
}
testString("/ip4/127.0.0.1/udp/1234", "047f0000011104d2")
testString("/ip4/127.0.0.1/tcp/4321", "047f0000010610e1")
testString("/ip4/127.0.0.1/udp/1234/ip4/127.0.0.1/tcp/4321", "047f0000011104d2047f0000010610e1")
}
func TestBytesSplitAndJoin(t *testing.T) {
testString := func(s string, res []string) {
m, err := NewMultiaddr(s)
if err != nil {
t.Fatal("failed to convert", s, err)
}
split := Split(m)
if len(split) != len(res) {
t.Error("not enough split components", split)
return
}
for i, a := range split {
if a.String() != res[i] {
t.Errorf("split component failed: %s != %s", a, res[i])
}
}
joined := Join(split...)
if !m.Equal(joined) {
t.Errorf("joined components failed: %s != %s", m, joined)
}
// modifying underlying bytes is fine.
m2 := m.(*multiaddr)
for i := range m2.bytes {
m2.bytes[i] = 0
}
for i, a := range split {
if a.String() != res[i] {
t.Errorf("split component failed: %s != %s", a, res[i])
}
}
}
testString("/ip4/1.2.3.4/udp/1234", []string{"/ip4/1.2.3.4", "/udp/1234"})
testString("/ip4/1.2.3.4/tcp/1/ip4/2.3.4.5/udp/2",
[]string{"/ip4/1.2.3.4", "/tcp/1", "/ip4/2.3.4.5", "/udp/2"})
testString("/ip4/1.2.3.4/utp/ip4/2.3.4.5/udp/2/udt",
[]string{"/ip4/1.2.3.4", "/utp", "/ip4/2.3.4.5", "/udp/2", "/udt"})
}
func TestProtocols(t *testing.T) {
m, err := NewMultiaddr("/ip4/127.0.0.1/udp/1234")
if err != nil {
t.Error("failed to construct", "/ip4/127.0.0.1/udp/1234")
}
ps := m.Protocols()
if ps[0].Code != ProtocolWithName("ip4").Code {
t.Error(ps[0], ProtocolWithName("ip4"))
t.Error("failed to get ip4 protocol")
}
if ps[1].Code != ProtocolWithName("udp").Code {
t.Error(ps[1], ProtocolWithName("udp"))
t.Error("failed to get udp protocol")
}
}
func TestProtocolsWithString(t *testing.T) {
pwn := ProtocolWithName
good := map[string][]Protocol{
"/ip4": []Protocol{pwn("ip4")},
"/ip4/tcp": []Protocol{pwn("ip4"), pwn("tcp")},
"ip4/tcp/udp/ip6": []Protocol{pwn("ip4"), pwn("tcp"), pwn("udp"), pwn("ip6")},
"////////ip4/tcp": []Protocol{pwn("ip4"), pwn("tcp")},
"ip4/udp/////////": []Protocol{pwn("ip4"), pwn("udp")},
"////////ip4/tcp////////": []Protocol{pwn("ip4"), pwn("tcp")},
}
for s, ps1 := range good {
ps2, err := ProtocolsWithString(s)
if err != nil {
t.Error("ProtocolsWithString(%s) should have succeeded", s)
}
for i, ps1p := range ps1 {
ps2p := ps2[i]
if ps1p.Code != ps2p.Code {
t.Errorf("mismatch: %s != %s, %s", ps1p.Name, ps2p.Name, s)
}
}
}
bad := []string{
"dsijafd", // bogus proto
"/ip4/tcp/fidosafoidsa", // bogus proto
"////////ip4/tcp/21432141/////////", // bogus proto
"////////ip4///////tcp/////////", // empty protos in between
}
for _, s := range bad {
if _, err := ProtocolsWithString(s); err == nil {
t.Error("ProtocolsWithString(%s) should have failed", s)
}
}
}
func TestEncapsulate(t *testing.T) {
m, err := NewMultiaddr("/ip4/127.0.0.1/udp/1234")
if err != nil {
t.Error(err)
}
m2, err := NewMultiaddr("/udp/5678")
if err != nil {
t.Error(err)
}
b := m.Encapsulate(m2)
if s := b.String(); s != "/ip4/127.0.0.1/udp/1234/udp/5678" {
t.Error("encapsulate /ip4/127.0.0.1/udp/1234/udp/5678 failed.", s)
}
m3, _ := NewMultiaddr("/udp/5678")
c := b.Decapsulate(m3)
if s := c.String(); s != "/ip4/127.0.0.1/udp/1234" {
t.Error("decapsulate /udp failed.", "/ip4/127.0.0.1/udp/1234", s)
}
m4, _ := NewMultiaddr("/ip4/127.0.0.1")
d := c.Decapsulate(m4)
if s := d.String(); s != "" {
t.Error("decapsulate /ip4 failed.", "/", s)
}
}

View File

@@ -0,0 +1,16 @@
{
"name": "go-multiaddr",
"author": "whyrusleeping",
"version": "1.0.0",
"gxDependencies": [
{
"name": "go-multihash",
"hash": "QmdeauTdyf38KDQB4Cc4CurPWRRb5pej27NCXPA7kbPTJy",
"version": "1.0.0"
}
],
"language": "go",
"gx": {
"dvcsimport": "github.com/jbenet/go-multiaddr"
}
}

View File

@@ -0,0 +1,13 @@
code size name
4 32 ip4
6 16 tcp
17 16 udp
33 16 dccp
41 128 ip6
132 16 sctp
301 0 udt
302 0 utp
421 V ipfs
480 0 http
443 0 https
444 10 onion
1 code size name
2 4 32 ip4
3 6 16 tcp
4 17 16 udp
5 33 16 dccp
6 41 128 ip6
7 132 16 sctp
8 301 0 udt
9 302 0 utp
10 421 V ipfs
11 480 0 http
12 443 0 https
13 444 10 onion

View File

@@ -0,0 +1,118 @@
package multiaddr
import (
"encoding/binary"
"fmt"
"strings"
)
// Protocol is a Multiaddr protocol description structure.
type Protocol struct {
Code int
Size int // a size of -1 indicates a length-prefixed variable size
Name string
VCode []byte
}
// replicating table here to:
// 1. avoid parsing the csv
// 2. ensuring errors in the csv don't screw up code.
// 3. changing a number has to happen in two places.
const (
P_IP4 = 4
P_TCP = 6
P_UDP = 17
P_DCCP = 33
P_IP6 = 41
P_SCTP = 132
P_UTP = 301
P_UDT = 302
P_IPFS = 421
P_HTTP = 480
P_HTTPS = 443
P_ONION = 444
)
// These are special sizes
const (
LengthPrefixedVarSize = -1
)
// Protocols is the list of multiaddr protocols supported by this module.
var Protocols = []Protocol{
Protocol{P_IP4, 32, "ip4", CodeToVarint(P_IP4)},
Protocol{P_TCP, 16, "tcp", CodeToVarint(P_TCP)},
Protocol{P_UDP, 16, "udp", CodeToVarint(P_UDP)},
Protocol{P_DCCP, 16, "dccp", CodeToVarint(P_DCCP)},
Protocol{P_IP6, 128, "ip6", CodeToVarint(P_IP6)},
// these require varint:
Protocol{P_SCTP, 16, "sctp", CodeToVarint(P_SCTP)},
Protocol{P_ONION, 80, "onion", CodeToVarint(P_ONION)},
Protocol{P_UTP, 0, "utp", CodeToVarint(P_UTP)},
Protocol{P_UDT, 0, "udt", CodeToVarint(P_UDT)},
Protocol{P_HTTP, 0, "http", CodeToVarint(P_HTTP)},
Protocol{P_HTTPS, 0, "https", CodeToVarint(P_HTTPS)},
Protocol{P_IPFS, LengthPrefixedVarSize, "ipfs", CodeToVarint(P_IPFS)},
}
// ProtocolWithName returns the Protocol description with given string name.
func ProtocolWithName(s string) Protocol {
for _, p := range Protocols {
if p.Name == s {
return p
}
}
return Protocol{}
}
// ProtocolWithCode returns the Protocol description with given protocol code.
func ProtocolWithCode(c int) Protocol {
for _, p := range Protocols {
if p.Code == c {
return p
}
}
return Protocol{}
}
// ProtocolsWithString returns a slice of protocols matching given string.
func ProtocolsWithString(s string) ([]Protocol, error) {
s = strings.Trim(s, "/")
sp := strings.Split(s, "/")
if len(sp) == 0 {
return nil, nil
}
t := make([]Protocol, len(sp))
for i, name := range sp {
p := ProtocolWithName(name)
if p.Code == 0 {
return nil, fmt.Errorf("no protocol with name: %s", name)
}
t[i] = p
}
return t, nil
}
// CodeToVarint converts an integer to a varint-encoded []byte
func CodeToVarint(num int) []byte {
buf := make([]byte, (num/7)+1) // varint package is uint64
n := binary.PutUvarint(buf, uint64(num))
return buf[:n]
}
// VarintToCode converts a varint-encoded []byte to an integer protocol code
func VarintToCode(buf []byte) int {
num, _ := ReadVarintCode(buf)
return num
}
// ReadVarintCode reads a varint code from the beginning of buf.
// returns the code, and the number of bytes read.
func ReadVarintCode(buf []byte) (int, int) {
num, n := binary.Uvarint(buf)
if n < 0 {
panic("varints larger than uint64 not yet supported")
}
return int(num), n
}

View File

@@ -0,0 +1,56 @@
package multiaddr
import "fmt"
// Split returns the sub-address portions of a multiaddr.
func Split(m Multiaddr) []Multiaddr {
split, err := bytesSplit(m.Bytes())
if err != nil {
panic(fmt.Errorf("invalid multiaddr %s", m.String()))
}
addrs := make([]Multiaddr, len(split))
for i, addr := range split {
addrs[i] = &multiaddr{bytes: addr}
}
return addrs
}
// Join returns a combination of addresses.
func Join(ms ...Multiaddr) Multiaddr {
length := 0
bs := make([][]byte, len(ms))
for i, m := range ms {
bs[i] = m.Bytes()
length += len(bs[i])
}
bidx := 0
b := make([]byte, length)
for _, mb := range bs {
for i := range mb {
b[bidx] = mb[i]
bidx++
}
}
return &multiaddr{bytes: b}
}
// Cast re-casts a byte slice as a multiaddr. will panic if it fails to parse.
func Cast(b []byte) Multiaddr {
_, err := bytesToString(b)
if err != nil {
panic(fmt.Errorf("multiaddr failed to parse: %s", err))
}
return &multiaddr{bytes: b}
}
// StringCast like Cast, but parses a string. Will also panic if it fails to parse.
func StringCast(s string) Multiaddr {
m, err := NewMultiaddr(s)
if err != nil {
panic(fmt.Errorf("multiaddr failed to parse: %s", err))
}
return m
}

View File

@@ -0,0 +1,10 @@
language: go
go:
- 1.5.1
script:
- make test
env:
- TEST_VERBOSE=1 GO15VENDOREXPERIMENT=1

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014 Juan Batiz-Benet
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,14 @@
GO15VENDOREXPERIMENT=1
all: install
gx:
go get github.com/whyrusleeping/gx
go get github.com/whyrusleeping/gx-go
dep: gx
gx install
test:
go test -race -cpu=5 -v

View File

@@ -0,0 +1,11 @@
# multiaddr/net - Multiaddr friendly net
Package multiaddr/net provides [Multiaddr](http://github.com/jbenet/go-multiaddr) specific versions of common
functions in stdlib's net package. This means wrappers of
standard net symbols like net.Dial and net.Listen, as well
as conversion to/from net.Addr.
Docs:
- `multiaddr/net`: https://godoc.org/github.com/jbenet/go-multiaddr-net
- `multiaddr`: https://godoc.org/github.com/jbenet/go-multiaddr

View File

@@ -0,0 +1,172 @@
package manet
import (
"fmt"
"net"
"strings"
ma "QmaA6aDzeHjZiuqBtgYRz8ZXb1qMCoyMHgyDjBEYQniUKF/go-multiaddr"
utp "QmanZCL6SXRfafiUEMCBLq2QR171uQSdXQ8YAdHXLd8Cwr/go-multiaddr-net/utp"
)
var errIncorrectNetAddr = fmt.Errorf("incorrect network addr conversion")
// FromNetAddr converts a net.Addr type to a Multiaddr.
func FromNetAddr(a net.Addr) (ma.Multiaddr, error) {
if a == nil {
return nil, fmt.Errorf("nil multiaddr")
}
switch a.Network() {
case "tcp", "tcp4", "tcp6":
ac, ok := a.(*net.TCPAddr)
if !ok {
return nil, errIncorrectNetAddr
}
// Get IP Addr
ipm, err := FromIP(ac.IP)
if err != nil {
return nil, errIncorrectNetAddr
}
// Get TCP Addr
tcpm, err := ma.NewMultiaddr(fmt.Sprintf("/tcp/%d", ac.Port))
if err != nil {
return nil, errIncorrectNetAddr
}
// Encapsulate
return ipm.Encapsulate(tcpm), nil
case "udp", "upd4", "udp6":
ac, ok := a.(*net.UDPAddr)
if !ok {
return nil, errIncorrectNetAddr
}
// Get IP Addr
ipm, err := FromIP(ac.IP)
if err != nil {
return nil, errIncorrectNetAddr
}
// Get UDP Addr
udpm, err := ma.NewMultiaddr(fmt.Sprintf("/udp/%d", ac.Port))
if err != nil {
return nil, errIncorrectNetAddr
}
// Encapsulate
return ipm.Encapsulate(udpm), nil
case "utp", "utp4", "utp6":
acc, ok := a.(*utp.Addr)
if !ok {
return nil, errIncorrectNetAddr
}
// Get UDP Addr
ac, ok := acc.Child().(*net.UDPAddr)
if !ok {
return nil, errIncorrectNetAddr
}
// Get IP Addr
ipm, err := FromIP(ac.IP)
if err != nil {
return nil, errIncorrectNetAddr
}
// Get UDP Addr
utpm, err := ma.NewMultiaddr(fmt.Sprintf("/udp/%d/utp", ac.Port))
if err != nil {
return nil, errIncorrectNetAddr
}
// Encapsulate
return ipm.Encapsulate(utpm), nil
case "ip", "ip4", "ip6":
ac, ok := a.(*net.IPAddr)
if !ok {
return nil, errIncorrectNetAddr
}
return FromIP(ac.IP)
case "ip+net":
ac, ok := a.(*net.IPNet)
if !ok {
return nil, errIncorrectNetAddr
}
return FromIP(ac.IP)
default:
return nil, fmt.Errorf("unknown network %v", a.Network())
}
}
// ToNetAddr converts a Multiaddr to a net.Addr
// Must be ThinWaist. acceptable protocol stacks are:
// /ip{4,6}/{tcp, udp}
func ToNetAddr(maddr ma.Multiaddr) (net.Addr, error) {
network, host, err := DialArgs(maddr)
if err != nil {
return nil, err
}
switch network {
case "tcp", "tcp4", "tcp6":
return net.ResolveTCPAddr(network, host)
case "udp", "udp4", "udp6":
return net.ResolveUDPAddr(network, host)
case "utp", "utp4", "utp6":
return utp.ResolveAddr(network, host)
case "ip", "ip4", "ip6":
return net.ResolveIPAddr(network, host)
}
return nil, fmt.Errorf("network not supported: %s", network)
}
// FromIP converts a net.IP type to a Multiaddr.
func FromIP(ip net.IP) (ma.Multiaddr, error) {
switch {
case ip.To4() != nil:
return ma.NewMultiaddr("/ip4/" + ip.String())
case ip.To16() != nil:
return ma.NewMultiaddr("/ip6/" + ip.String())
default:
return nil, errIncorrectNetAddr
}
}
// DialArgs is a convenience function returning arguments for use in net.Dial
func DialArgs(m ma.Multiaddr) (string, string, error) {
if !IsThinWaist(m) {
return "", "", fmt.Errorf("%s is not a 'thin waist' address", m)
}
str := m.String()
parts := strings.Split(str, "/")[1:]
if len(parts) == 2 { // only IP
return parts[0], parts[1], nil
}
network := parts[2]
if parts[2] == "udp" && len(parts) > 4 && parts[4] == "utp" {
network = parts[4]
}
var host string
switch parts[0] {
case "ip4":
network = network + "4"
host = strings.Join([]string{parts[1], parts[3]}, ":")
case "ip6":
network = network + "6"
host = fmt.Sprintf("[%s]:%s", parts[1], parts[3])
}
return network, host, nil
}

Some files were not shown because too many files have changed in this diff Show More