resolver.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package resolver
  2. import (
  3. "encoding/binary"
  4. "fmt"
  5. // "net/url"
  6. "github.com/ethereum/go-ethereum/common"
  7. "github.com/ethereum/go-ethereum/crypto"
  8. "github.com/ethereum/go-ethereum/xeth"
  9. )
  10. /*
  11. Resolver implements the Ethereum DNS mapping
  12. NameReg : Domain Name (or Code hash of Contract) -> Content Hash
  13. UrlHint : Content Hash -> Url Hint
  14. The resolver is meant to be called by the roundtripper transport implementation
  15. of a url scheme
  16. */
  17. const (
  18. urlHintContractAddress = "urlhint"
  19. nameRegContractAddress = "nameReg"
  20. )
  21. type Resolver struct {
  22. xeth *xeth.XEth
  23. urlHintContractAddress string
  24. nameRegContractAddress string
  25. }
  26. func New(_xeth *xeth.XEth, uhca, nrca string) *Resolver {
  27. return &Resolver{_xeth, uhca, nrca}
  28. }
  29. func (self *Resolver) NameToContentHash(name string) (hash common.Hash, err error) {
  30. // look up in nameReg
  31. hashbytes := self.xeth.StorageAt(self.nameRegContractAddress, storageAddress(0, common.Hex2Bytes(name)))
  32. copy(hash[:], hashbytes[:32])
  33. return
  34. }
  35. func (self *Resolver) ContentHashToUrl(hash common.Hash) (uri string, err error) {
  36. // look up in nameReg
  37. urlHex := self.xeth.StorageAt(self.urlHintContractAddress, storageAddress(0, hash.Bytes()))
  38. uri = string(common.Hex2Bytes(urlHex))
  39. l := len(uri)
  40. for (l > 0) && (uri[l-1] == 0) {
  41. l--
  42. }
  43. uri = uri[:l]
  44. if l == 0 {
  45. err = fmt.Errorf("GetURLhint: URL hint not found")
  46. }
  47. // rawurl := fmt.Sprintf("bzz://%x/my/path/mycontract.s ud", hash[:])
  48. // mime type?
  49. return
  50. }
  51. func (self *Resolver) NameToUrl(name string) (uri string, hash common.Hash, err error) {
  52. // look up in urlHint
  53. hash, err = self.NameToContentHash(name)
  54. if err != nil {
  55. return
  56. }
  57. uri, err = self.ContentHashToUrl(hash)
  58. return
  59. }
  60. func storageAddress(varidx uint32, key []byte) string {
  61. data := make([]byte, 64)
  62. binary.BigEndian.PutUint32(data[28:32], varidx)
  63. copy(data[32:64], key[0:32])
  64. return common.Bytes2Hex(crypto.Sha3(data))
  65. }