12 var table = crc32.MakeTable(crc32.Castagnoli)
14 type peerPriority = uint32
16 func sameSubnet(ones, bits int, a, b net.IP) bool {
17 mask := net.CIDRMask(ones, bits)
18 return a.Mask(mask).Equal(b.Mask(mask))
21 func ipv4Mask(a, b net.IP) net.IPMask {
22 if !sameSubnet(16, 32, a, b) {
23 return net.IPv4Mask(0xff, 0xff, 0x55, 0x55)
25 if !sameSubnet(24, 32, a, b) {
26 return net.IPv4Mask(0xff, 0xff, 0xff, 0x55)
28 return net.IPv4Mask(0xff, 0xff, 0xff, 0xff)
31 func mask(prefix, bytes int) net.IPMask {
32 ret := make(net.IPMask, bytes)
36 for i := 0; i < prefix; i++ {
42 func ipv6Mask(a, b net.IP) net.IPMask {
43 for i := 6; i <= 16; i++ {
44 if !sameSubnet(i*8, 128, a, b) {
48 panic(fmt.Sprintf("%s %s", a, b))
51 func bep40PriorityBytes(a, b IpPort) ([]byte, error) {
54 binary.BigEndian.PutUint16(ret[0:2], a.Port)
55 binary.BigEndian.PutUint16(ret[2:4], b.Port)
58 if a4, b4 := a.IP.To4(), b.IP.To4(); a4 != nil && b4 != nil {
59 m := ipv4Mask(a.IP, b.IP)
60 return append(a4.Mask(m), b4.Mask(m)...), nil
62 if a6, b6 := a.IP.To16(), b.IP.To16(); a6 != nil && b6 != nil {
63 m := ipv6Mask(a.IP, b.IP)
64 return append(a6.Mask(m), b6.Mask(m)...), nil
66 return nil, errors.New("incomparable IPs")
69 func bep40Priority(a, b IpPort) (peerPriority, error) {
70 bs, err := bep40PriorityBytes(a, b)
75 _a, _b := bs[:i], bs[i:]
76 if bytes.Compare(_a, _b) > 0 {
77 bs = append(_b, _a...)
79 return crc32.Checksum(bs, table), nil
82 func bep40PriorityIgnoreError(a, b IpPort) peerPriority {
83 prio, _ := bep40Priority(a, b)