aboutsummaryrefslogtreecommitdiff
path: root/models/infohash.go
blob: bb1bd816e1f19f5931354f2d77739784c18d1775 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package models

import (
	"crypto/sha1"
	"encoding/hex"
	"fmt"
	"io"
	"math/rand"
	"time"
)

const InfohashLength = 20

// Infohash is a 160 bit (20 byte) value
type Infohash []byte

// InfohashFromString converts a 40 digit hexadecimal string to an Infohash
func InfohashFromString(s string) (*Infohash, error) {
	switch len(s) {
	case 20:
		// Binary string
		ih := Infohash([]byte(s))
		return &ih, nil
	case 40:
		// Hex string
		b, err := hex.DecodeString(s)
		if err != nil {
			return nil, err
		}
		ih := Infohash(b)
		return &ih, nil
	default:
		return nil, fmt.Errorf("invalid length %d", len(s))
	}
}

func (ih Infohash) String() string {
	return hex.EncodeToString(ih)
}

func (ih Infohash) Bytes() []byte {
	return []byte(ih)
}

func (ih Infohash) Valid() bool {
	// TODO
	return len(ih) == 20
}

func (ih Infohash) Equal(other Infohash) bool {
	if len(ih) != len(other) {
		return false
	}
	for i := 0; i < len(ih); i++ {
		if ih[i] != other[i] {
			return false
		}
	}
	return true
}

// Distance determines the distance to another infohash as an integer
func (ih Infohash) Distance(other Infohash) int {
	i := 0
	for ; i < 20; i++ {
		if ih[i] != other[i] {
			break
		}
	}

	if i == 20 {
		return 160
	}

	xor := ih[i] ^ other[i]

	j := 0
	for (xor & 0x80) == 0 {
		xor <<= 1
		j++
	}
	return 8*i + j
}

func GenerateNeighbour(first, second Infohash) Infohash {
	s := append(second[:10], first[10:]...)
	return Infohash(s)
}

func GenInfohash() (ih Infohash) {
	random := rand.New(rand.NewSource(time.Now().UnixNano()))
	hash := sha1.New()
	io.WriteString(hash, time.Now().String())
	io.WriteString(hash, string(random.Int()))
	return Infohash(hash.Sum(nil))
}