12 var table = crc32.MakeTable(crc32.Castagnoli)
14 type peerPriority = uint32
21 func sameSubnet(ones, bits int, a, b net.IP) bool {
22 mask := net.CIDRMask(ones, bits)
23 return a.Mask(mask).Equal(b.Mask(mask))
26 func ipv4Mask(a, b net.IP) net.IPMask {
27 if !sameSubnet(16, 32, a, b) {
28 return net.IPv4Mask(0xff, 0xff, 0x55, 0x55)
30 if !sameSubnet(24, 32, a, b) {
31 return net.IPv4Mask(0xff, 0xff, 0xff, 0x55)
33 return net.IPv4Mask(0xff, 0xff, 0xff, 0xff)
36 func mask(prefix, bytes int) net.IPMask {
37 ret := make(net.IPMask, bytes)
41 for i := 0; i < prefix; i++ {
47 func ipv6Mask(a, b net.IP) net.IPMask {
48 for i := 6; i <= 16; i++ {
49 if !sameSubnet(i*8, 128, a, b) {
53 panic(fmt.Sprintf("%s %s", a, b))
56 func bep40PriorityBytes(a, b ipPort) []byte {
59 binary.BigEndian.PutUint16(ret[0:2], a.Port)
60 binary.BigEndian.PutUint16(ret[2:4], b.Port)
63 if a4, b4 := a.IP.To4(), b.IP.To4(); a4 != nil && b4 != nil {
64 m := ipv4Mask(a.IP, b.IP)
65 return append(a4.Mask(m), b4.Mask(m)...)
67 if a6, b6 := a.IP.To16(), b.IP.To16(); a6 != nil && b6 != nil {
68 m := ipv6Mask(a.IP, b.IP)
69 return append(a6.Mask(m), b6.Mask(m)...)
71 panic(fmt.Sprintf("%s %s", a.IP, b.IP))
74 func bep40Priority(a, b ipPort) peerPriority {
75 bs := bep40PriorityBytes(a, b)
77 _a, _b := bs[:i], bs[i:]
78 if bytes.Compare(_a, _b) > 0 {
79 bs = append(_b, _a...)
81 return crc32.Checksum(bs, table)