api.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. // Copyright 2016 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package api
  17. import (
  18. "context"
  19. "fmt"
  20. "io"
  21. "math/big"
  22. "net/http"
  23. "path"
  24. "strings"
  25. "bytes"
  26. "mime"
  27. "path/filepath"
  28. "time"
  29. "github.com/ethereum/go-ethereum/common"
  30. "github.com/ethereum/go-ethereum/contracts/ens"
  31. "github.com/ethereum/go-ethereum/core/types"
  32. "github.com/ethereum/go-ethereum/metrics"
  33. "github.com/ethereum/go-ethereum/swarm/log"
  34. "github.com/ethereum/go-ethereum/swarm/multihash"
  35. "github.com/ethereum/go-ethereum/swarm/storage"
  36. "github.com/ethereum/go-ethereum/swarm/storage/mru"
  37. )
  38. var (
  39. apiResolveCount = metrics.NewRegisteredCounter("api.resolve.count", nil)
  40. apiResolveFail = metrics.NewRegisteredCounter("api.resolve.fail", nil)
  41. apiPutCount = metrics.NewRegisteredCounter("api.put.count", nil)
  42. apiPutFail = metrics.NewRegisteredCounter("api.put.fail", nil)
  43. apiGetCount = metrics.NewRegisteredCounter("api.get.count", nil)
  44. apiGetNotFound = metrics.NewRegisteredCounter("api.get.notfound", nil)
  45. apiGetHTTP300 = metrics.NewRegisteredCounter("api.get.http.300", nil)
  46. apiModifyCount = metrics.NewRegisteredCounter("api.modify.count", nil)
  47. apiModifyFail = metrics.NewRegisteredCounter("api.modify.fail", nil)
  48. apiAddFileCount = metrics.NewRegisteredCounter("api.addfile.count", nil)
  49. apiAddFileFail = metrics.NewRegisteredCounter("api.addfile.fail", nil)
  50. apiRmFileCount = metrics.NewRegisteredCounter("api.removefile.count", nil)
  51. apiRmFileFail = metrics.NewRegisteredCounter("api.removefile.fail", nil)
  52. apiAppendFileCount = metrics.NewRegisteredCounter("api.appendfile.count", nil)
  53. apiAppendFileFail = metrics.NewRegisteredCounter("api.appendfile.fail", nil)
  54. apiGetInvalid = metrics.NewRegisteredCounter("api.get.invalid", nil)
  55. )
  56. // Resolver interface resolve a domain name to a hash using ENS
  57. type Resolver interface {
  58. Resolve(string) (common.Hash, error)
  59. }
  60. // ResolveValidator is used to validate the contained Resolver
  61. type ResolveValidator interface {
  62. Resolver
  63. Owner(node [32]byte) (common.Address, error)
  64. HeaderByNumber(context.Context, *big.Int) (*types.Header, error)
  65. }
  66. // NoResolverError is returned by MultiResolver.Resolve if no resolver
  67. // can be found for the address.
  68. type NoResolverError struct {
  69. TLD string
  70. }
  71. // NewNoResolverError creates a NoResolverError for the given top level domain
  72. func NewNoResolverError(tld string) *NoResolverError {
  73. return &NoResolverError{TLD: tld}
  74. }
  75. // Error NoResolverError implements error
  76. func (e *NoResolverError) Error() string {
  77. if e.TLD == "" {
  78. return "no ENS resolver"
  79. }
  80. return fmt.Sprintf("no ENS endpoint configured to resolve .%s TLD names", e.TLD)
  81. }
  82. // MultiResolver is used to resolve URL addresses based on their TLDs.
  83. // Each TLD can have multiple resolvers, and the resoluton from the
  84. // first one in the sequence will be returned.
  85. type MultiResolver struct {
  86. resolvers map[string][]ResolveValidator
  87. nameHash func(string) common.Hash
  88. }
  89. // MultiResolverOption sets options for MultiResolver and is used as
  90. // arguments for its constructor.
  91. type MultiResolverOption func(*MultiResolver)
  92. // MultiResolverOptionWithResolver adds a Resolver to a list of resolvers
  93. // for a specific TLD. If TLD is an empty string, the resolver will be added
  94. // to the list of default resolver, the ones that will be used for resolution
  95. // of addresses which do not have their TLD resolver specified.
  96. func MultiResolverOptionWithResolver(r ResolveValidator, tld string) MultiResolverOption {
  97. return func(m *MultiResolver) {
  98. m.resolvers[tld] = append(m.resolvers[tld], r)
  99. }
  100. }
  101. // MultiResolverOptionWithNameHash is unused at the time of this writing
  102. func MultiResolverOptionWithNameHash(nameHash func(string) common.Hash) MultiResolverOption {
  103. return func(m *MultiResolver) {
  104. m.nameHash = nameHash
  105. }
  106. }
  107. // NewMultiResolver creates a new instance of MultiResolver.
  108. func NewMultiResolver(opts ...MultiResolverOption) (m *MultiResolver) {
  109. m = &MultiResolver{
  110. resolvers: make(map[string][]ResolveValidator),
  111. nameHash: ens.EnsNode,
  112. }
  113. for _, o := range opts {
  114. o(m)
  115. }
  116. return m
  117. }
  118. // Resolve resolves address by choosing a Resolver by TLD.
  119. // If there are more default Resolvers, or for a specific TLD,
  120. // the Hash from the the first one which does not return error
  121. // will be returned.
  122. func (m *MultiResolver) Resolve(addr string) (h common.Hash, err error) {
  123. rs, err := m.getResolveValidator(addr)
  124. if err != nil {
  125. return h, err
  126. }
  127. for _, r := range rs {
  128. h, err = r.Resolve(addr)
  129. if err == nil {
  130. return
  131. }
  132. }
  133. return
  134. }
  135. // ValidateOwner checks the ENS to validate that the owner of the given domain is the given eth address
  136. func (m *MultiResolver) ValidateOwner(name string, address common.Address) (bool, error) {
  137. rs, err := m.getResolveValidator(name)
  138. if err != nil {
  139. return false, err
  140. }
  141. var addr common.Address
  142. for _, r := range rs {
  143. addr, err = r.Owner(m.nameHash(name))
  144. // we hide the error if it is not for the last resolver we check
  145. if err == nil {
  146. return addr == address, nil
  147. }
  148. }
  149. return false, err
  150. }
  151. // HeaderByNumber uses the validator of the given domainname and retrieves the header for the given block number
  152. func (m *MultiResolver) HeaderByNumber(ctx context.Context, name string, blockNr *big.Int) (*types.Header, error) {
  153. rs, err := m.getResolveValidator(name)
  154. if err != nil {
  155. return nil, err
  156. }
  157. for _, r := range rs {
  158. var header *types.Header
  159. header, err = r.HeaderByNumber(ctx, blockNr)
  160. // we hide the error if it is not for the last resolver we check
  161. if err == nil {
  162. return header, nil
  163. }
  164. }
  165. return nil, err
  166. }
  167. // getResolveValidator uses the hostname to retrieve the resolver associated with the top level domain
  168. func (m *MultiResolver) getResolveValidator(name string) ([]ResolveValidator, error) {
  169. rs := m.resolvers[""]
  170. tld := path.Ext(name)
  171. if tld != "" {
  172. tld = tld[1:]
  173. rstld, ok := m.resolvers[tld]
  174. if ok {
  175. return rstld, nil
  176. }
  177. }
  178. if len(rs) == 0 {
  179. return rs, NewNoResolverError(tld)
  180. }
  181. return rs, nil
  182. }
  183. // SetNameHash sets the hasher function that hashes the domain into a name hash that ENS uses
  184. func (m *MultiResolver) SetNameHash(nameHash func(string) common.Hash) {
  185. m.nameHash = nameHash
  186. }
  187. /*
  188. API implements webserver/file system related content storage and retrieval
  189. on top of the FileStore
  190. it is the public interface of the FileStore which is included in the ethereum stack
  191. */
  192. type API struct {
  193. resource *mru.Handler
  194. fileStore *storage.FileStore
  195. dns Resolver
  196. }
  197. // NewAPI the api constructor initialises a new API instance.
  198. func NewAPI(fileStore *storage.FileStore, dns Resolver, resourceHandler *mru.Handler) (self *API) {
  199. self = &API{
  200. fileStore: fileStore,
  201. dns: dns,
  202. resource: resourceHandler,
  203. }
  204. return
  205. }
  206. // Upload to be used only in TEST
  207. func (a *API) Upload(uploadDir, index string, toEncrypt bool) (hash string, err error) {
  208. fs := NewFileSystem(a)
  209. hash, err = fs.Upload(uploadDir, index, toEncrypt)
  210. return hash, err
  211. }
  212. // Retrieve FileStore reader API
  213. func (a *API) Retrieve(addr storage.Address) (reader storage.LazySectionReader, isEncrypted bool) {
  214. return a.fileStore.Retrieve(addr)
  215. }
  216. // Store wraps the Store API call of the embedded FileStore
  217. func (a *API) Store(data io.Reader, size int64, toEncrypt bool) (addr storage.Address, wait func(), err error) {
  218. log.Debug("api.store", "size", size)
  219. return a.fileStore.Store(data, size, toEncrypt)
  220. }
  221. // ErrResolve is returned when an URI cannot be resolved from ENS.
  222. type ErrResolve error
  223. // Resolve resolves a URI to an Address using the MultiResolver.
  224. func (a *API) Resolve(uri *URI) (storage.Address, error) {
  225. apiResolveCount.Inc(1)
  226. log.Trace("resolving", "uri", uri.Addr)
  227. // if the URI is immutable, check if the address looks like a hash
  228. if uri.Immutable() {
  229. key := uri.Address()
  230. if key == nil {
  231. return nil, fmt.Errorf("immutable address not a content hash: %q", uri.Addr)
  232. }
  233. return key, nil
  234. }
  235. // if DNS is not configured, check if the address is a hash
  236. if a.dns == nil {
  237. key := uri.Address()
  238. if key == nil {
  239. apiResolveFail.Inc(1)
  240. return nil, fmt.Errorf("no DNS to resolve name: %q", uri.Addr)
  241. }
  242. return key, nil
  243. }
  244. // try and resolve the address
  245. resolved, err := a.dns.Resolve(uri.Addr)
  246. if err == nil {
  247. return resolved[:], nil
  248. }
  249. key := uri.Address()
  250. if key == nil {
  251. apiResolveFail.Inc(1)
  252. return nil, err
  253. }
  254. return key, nil
  255. }
  256. // Put provides singleton manifest creation on top of FileStore store
  257. func (a *API) Put(content, contentType string, toEncrypt bool) (k storage.Address, wait func(), err error) {
  258. apiPutCount.Inc(1)
  259. r := strings.NewReader(content)
  260. key, waitContent, err := a.fileStore.Store(r, int64(len(content)), toEncrypt)
  261. if err != nil {
  262. apiPutFail.Inc(1)
  263. return nil, nil, err
  264. }
  265. manifest := fmt.Sprintf(`{"entries":[{"hash":"%v","contentType":"%s"}]}`, key, contentType)
  266. r = strings.NewReader(manifest)
  267. key, waitManifest, err := a.fileStore.Store(r, int64(len(manifest)), toEncrypt)
  268. if err != nil {
  269. apiPutFail.Inc(1)
  270. return nil, nil, err
  271. }
  272. return key, func() {
  273. waitContent()
  274. waitManifest()
  275. }, nil
  276. }
  277. // Get uses iterative manifest retrieval and prefix matching
  278. // to resolve basePath to content using FileStore retrieve
  279. // it returns a section reader, mimeType, status, the key of the actual content and an error
  280. func (a *API) Get(manifestAddr storage.Address, path string) (reader storage.LazySectionReader, mimeType string, status int, contentAddr storage.Address, err error) {
  281. log.Debug("api.get", "key", manifestAddr, "path", path)
  282. apiGetCount.Inc(1)
  283. trie, err := loadManifest(a.fileStore, manifestAddr, nil)
  284. if err != nil {
  285. apiGetNotFound.Inc(1)
  286. status = http.StatusNotFound
  287. log.Warn(fmt.Sprintf("loadManifestTrie error: %v", err))
  288. return
  289. }
  290. log.Debug("trie getting entry", "key", manifestAddr, "path", path)
  291. entry, _ := trie.getEntry(path)
  292. if entry != nil {
  293. log.Debug("trie got entry", "key", manifestAddr, "path", path, "entry.Hash", entry.Hash)
  294. // we need to do some extra work if this is a mutable resource manifest
  295. if entry.ContentType == ResourceContentType {
  296. // get the resource root chunk key
  297. log.Trace("resource type", "key", manifestAddr, "hash", entry.Hash)
  298. ctx, cancel := context.WithCancel(context.Background())
  299. defer cancel()
  300. rsrc, err := a.resource.Load(storage.Address(common.FromHex(entry.Hash)))
  301. if err != nil {
  302. apiGetNotFound.Inc(1)
  303. status = http.StatusNotFound
  304. log.Debug(fmt.Sprintf("get resource content error: %v", err))
  305. return reader, mimeType, status, nil, err
  306. }
  307. // use this key to retrieve the latest update
  308. rsrc, err = a.resource.LookupLatest(ctx, rsrc.NameHash(), true, &mru.LookupParams{})
  309. if err != nil {
  310. apiGetNotFound.Inc(1)
  311. status = http.StatusNotFound
  312. log.Debug(fmt.Sprintf("get resource content error: %v", err))
  313. return reader, mimeType, status, nil, err
  314. }
  315. // if it's multihash, we will transparently serve the content this multihash points to
  316. // \TODO this resolve is rather expensive all in all, review to see if it can be achieved cheaper
  317. if rsrc.Multihash {
  318. // get the data of the update
  319. _, rsrcData, err := a.resource.GetContent(rsrc.NameHash().Hex())
  320. if err != nil {
  321. apiGetNotFound.Inc(1)
  322. status = http.StatusNotFound
  323. log.Warn(fmt.Sprintf("get resource content error: %v", err))
  324. return reader, mimeType, status, nil, err
  325. }
  326. // validate that data as multihash
  327. decodedMultihash, err := multihash.FromMultihash(rsrcData)
  328. if err != nil {
  329. apiGetInvalid.Inc(1)
  330. status = http.StatusUnprocessableEntity
  331. log.Warn("invalid resource multihash", "err", err)
  332. return reader, mimeType, status, nil, err
  333. }
  334. manifestAddr = storage.Address(decodedMultihash)
  335. log.Trace("resource is multihash", "key", manifestAddr)
  336. // get the manifest the multihash digest points to
  337. trie, err := loadManifest(a.fileStore, manifestAddr, nil)
  338. if err != nil {
  339. apiGetNotFound.Inc(1)
  340. status = http.StatusNotFound
  341. log.Warn(fmt.Sprintf("loadManifestTrie (resource multihash) error: %v", err))
  342. return reader, mimeType, status, nil, err
  343. }
  344. // finally, get the manifest entry
  345. // it will always be the entry on path ""
  346. entry, _ = trie.getEntry(path)
  347. if entry == nil {
  348. status = http.StatusNotFound
  349. apiGetNotFound.Inc(1)
  350. err = fmt.Errorf("manifest (resource multihash) entry for '%s' not found", path)
  351. log.Trace("manifest (resource multihash) entry not found", "key", manifestAddr, "path", path)
  352. return reader, mimeType, status, nil, err
  353. }
  354. } else {
  355. // data is returned verbatim since it's not a multihash
  356. return rsrc, "application/octet-stream", http.StatusOK, nil, nil
  357. }
  358. }
  359. // regardless of resource update manifests or normal manifests we will converge at this point
  360. // get the key the manifest entry points to and serve it if it's unambiguous
  361. contentAddr = common.Hex2Bytes(entry.Hash)
  362. status = entry.Status
  363. if status == http.StatusMultipleChoices {
  364. apiGetHTTP300.Inc(1)
  365. return nil, entry.ContentType, status, contentAddr, err
  366. }
  367. mimeType = entry.ContentType
  368. log.Debug("content lookup key", "key", contentAddr, "mimetype", mimeType)
  369. reader, _ = a.fileStore.Retrieve(contentAddr)
  370. } else {
  371. // no entry found
  372. status = http.StatusNotFound
  373. apiGetNotFound.Inc(1)
  374. err = fmt.Errorf("manifest entry for '%s' not found", path)
  375. log.Trace("manifest entry not found", "key", contentAddr, "path", path)
  376. }
  377. return
  378. }
  379. // Modify loads manifest and checks the content hash before recalculating and storing the manifest.
  380. func (a *API) Modify(addr storage.Address, path, contentHash, contentType string) (storage.Address, error) {
  381. apiModifyCount.Inc(1)
  382. quitC := make(chan bool)
  383. trie, err := loadManifest(a.fileStore, addr, quitC)
  384. if err != nil {
  385. apiModifyFail.Inc(1)
  386. return nil, err
  387. }
  388. if contentHash != "" {
  389. entry := newManifestTrieEntry(&ManifestEntry{
  390. Path: path,
  391. ContentType: contentType,
  392. }, nil)
  393. entry.Hash = contentHash
  394. trie.addEntry(entry, quitC)
  395. } else {
  396. trie.deleteEntry(path, quitC)
  397. }
  398. if err := trie.recalcAndStore(); err != nil {
  399. apiModifyFail.Inc(1)
  400. return nil, err
  401. }
  402. return trie.ref, nil
  403. }
  404. // AddFile creates a new manifest entry, adds it to swarm, then adds a file to swarm.
  405. func (a *API) AddFile(mhash, path, fname string, content []byte, nameresolver bool) (storage.Address, string, error) {
  406. apiAddFileCount.Inc(1)
  407. uri, err := Parse("bzz:/" + mhash)
  408. if err != nil {
  409. apiAddFileFail.Inc(1)
  410. return nil, "", err
  411. }
  412. mkey, err := a.Resolve(uri)
  413. if err != nil {
  414. apiAddFileFail.Inc(1)
  415. return nil, "", err
  416. }
  417. // trim the root dir we added
  418. if path[:1] == "/" {
  419. path = path[1:]
  420. }
  421. entry := &ManifestEntry{
  422. Path: filepath.Join(path, fname),
  423. ContentType: mime.TypeByExtension(filepath.Ext(fname)),
  424. Mode: 0700,
  425. Size: int64(len(content)),
  426. ModTime: time.Now(),
  427. }
  428. mw, err := a.NewManifestWriter(mkey, nil)
  429. if err != nil {
  430. apiAddFileFail.Inc(1)
  431. return nil, "", err
  432. }
  433. fkey, err := mw.AddEntry(bytes.NewReader(content), entry)
  434. if err != nil {
  435. apiAddFileFail.Inc(1)
  436. return nil, "", err
  437. }
  438. newMkey, err := mw.Store()
  439. if err != nil {
  440. apiAddFileFail.Inc(1)
  441. return nil, "", err
  442. }
  443. return fkey, newMkey.String(), nil
  444. }
  445. // RemoveFile removes a file entry in a manifest.
  446. func (a *API) RemoveFile(mhash, path, fname string, nameresolver bool) (string, error) {
  447. apiRmFileCount.Inc(1)
  448. uri, err := Parse("bzz:/" + mhash)
  449. if err != nil {
  450. apiRmFileFail.Inc(1)
  451. return "", err
  452. }
  453. mkey, err := a.Resolve(uri)
  454. if err != nil {
  455. apiRmFileFail.Inc(1)
  456. return "", err
  457. }
  458. // trim the root dir we added
  459. if path[:1] == "/" {
  460. path = path[1:]
  461. }
  462. mw, err := a.NewManifestWriter(mkey, nil)
  463. if err != nil {
  464. apiRmFileFail.Inc(1)
  465. return "", err
  466. }
  467. err = mw.RemoveEntry(filepath.Join(path, fname))
  468. if err != nil {
  469. apiRmFileFail.Inc(1)
  470. return "", err
  471. }
  472. newMkey, err := mw.Store()
  473. if err != nil {
  474. apiRmFileFail.Inc(1)
  475. return "", err
  476. }
  477. return newMkey.String(), nil
  478. }
  479. // AppendFile removes old manifest, appends file entry to new manifest and adds it to Swarm.
  480. func (a *API) AppendFile(mhash, path, fname string, existingSize int64, content []byte, oldAddr storage.Address, offset int64, addSize int64, nameresolver bool) (storage.Address, string, error) {
  481. apiAppendFileCount.Inc(1)
  482. buffSize := offset + addSize
  483. if buffSize < existingSize {
  484. buffSize = existingSize
  485. }
  486. buf := make([]byte, buffSize)
  487. oldReader, _ := a.Retrieve(oldAddr)
  488. io.ReadAtLeast(oldReader, buf, int(offset))
  489. newReader := bytes.NewReader(content)
  490. io.ReadAtLeast(newReader, buf[offset:], int(addSize))
  491. if buffSize < existingSize {
  492. io.ReadAtLeast(oldReader, buf[addSize:], int(buffSize))
  493. }
  494. combinedReader := bytes.NewReader(buf)
  495. totalSize := int64(len(buf))
  496. // TODO(jmozah): to append using pyramid chunker when it is ready
  497. //oldReader := a.Retrieve(oldKey)
  498. //newReader := bytes.NewReader(content)
  499. //combinedReader := io.MultiReader(oldReader, newReader)
  500. uri, err := Parse("bzz:/" + mhash)
  501. if err != nil {
  502. apiAppendFileFail.Inc(1)
  503. return nil, "", err
  504. }
  505. mkey, err := a.Resolve(uri)
  506. if err != nil {
  507. apiAppendFileFail.Inc(1)
  508. return nil, "", err
  509. }
  510. // trim the root dir we added
  511. if path[:1] == "/" {
  512. path = path[1:]
  513. }
  514. mw, err := a.NewManifestWriter(mkey, nil)
  515. if err != nil {
  516. apiAppendFileFail.Inc(1)
  517. return nil, "", err
  518. }
  519. err = mw.RemoveEntry(filepath.Join(path, fname))
  520. if err != nil {
  521. apiAppendFileFail.Inc(1)
  522. return nil, "", err
  523. }
  524. entry := &ManifestEntry{
  525. Path: filepath.Join(path, fname),
  526. ContentType: mime.TypeByExtension(filepath.Ext(fname)),
  527. Mode: 0700,
  528. Size: totalSize,
  529. ModTime: time.Now(),
  530. }
  531. fkey, err := mw.AddEntry(io.Reader(combinedReader), entry)
  532. if err != nil {
  533. apiAppendFileFail.Inc(1)
  534. return nil, "", err
  535. }
  536. newMkey, err := mw.Store()
  537. if err != nil {
  538. apiAppendFileFail.Inc(1)
  539. return nil, "", err
  540. }
  541. return fkey, newMkey.String(), nil
  542. }
  543. // BuildDirectoryTree used by swarmfs_unix
  544. func (a *API) BuildDirectoryTree(mhash string, nameresolver bool) (addr storage.Address, manifestEntryMap map[string]*manifestTrieEntry, err error) {
  545. uri, err := Parse("bzz:/" + mhash)
  546. if err != nil {
  547. return nil, nil, err
  548. }
  549. addr, err = a.Resolve(uri)
  550. if err != nil {
  551. return nil, nil, err
  552. }
  553. quitC := make(chan bool)
  554. rootTrie, err := loadManifest(a.fileStore, addr, quitC)
  555. if err != nil {
  556. return nil, nil, fmt.Errorf("can't load manifest %v: %v", addr.String(), err)
  557. }
  558. manifestEntryMap = map[string]*manifestTrieEntry{}
  559. err = rootTrie.listWithPrefix(uri.Path, quitC, func(entry *manifestTrieEntry, suffix string) {
  560. manifestEntryMap[suffix] = entry
  561. })
  562. if err != nil {
  563. return nil, nil, fmt.Errorf("list with prefix failed %v: %v", addr.String(), err)
  564. }
  565. return addr, manifestEntryMap, nil
  566. }
  567. // ResourceLookup Looks up mutable resource updates at specific periods and versions
  568. func (a *API) ResourceLookup(ctx context.Context, addr storage.Address, period uint32, version uint32, maxLookup *mru.LookupParams) (string, []byte, error) {
  569. var err error
  570. rsrc, err := a.resource.Load(addr)
  571. if err != nil {
  572. return "", nil, err
  573. }
  574. if version != 0 {
  575. if period == 0 {
  576. return "", nil, mru.NewError(mru.ErrInvalidValue, "Period can't be 0")
  577. }
  578. _, err = a.resource.LookupVersion(ctx, rsrc.NameHash(), period, version, true, maxLookup)
  579. } else if period != 0 {
  580. _, err = a.resource.LookupHistorical(ctx, rsrc.NameHash(), period, true, maxLookup)
  581. } else {
  582. _, err = a.resource.LookupLatest(ctx, rsrc.NameHash(), true, maxLookup)
  583. }
  584. if err != nil {
  585. return "", nil, err
  586. }
  587. var data []byte
  588. _, data, err = a.resource.GetContent(rsrc.NameHash().Hex())
  589. if err != nil {
  590. return "", nil, err
  591. }
  592. return rsrc.Name(), data, nil
  593. }
  594. // ResourceCreate creates Resource and returns its key
  595. func (a *API) ResourceCreate(ctx context.Context, name string, frequency uint64) (storage.Address, error) {
  596. key, _, err := a.resource.New(ctx, name, frequency)
  597. if err != nil {
  598. return nil, err
  599. }
  600. return key, nil
  601. }
  602. // ResourceUpdateMultihash updates a Mutable Resource and marks the update's content to be of multihash type, which will be recognized upon retrieval.
  603. // It will fail if the data is not a valid multihash.
  604. func (a *API) ResourceUpdateMultihash(ctx context.Context, name string, data []byte) (storage.Address, uint32, uint32, error) {
  605. return a.resourceUpdate(ctx, name, data, true)
  606. }
  607. // ResourceUpdate updates a Mutable Resource with arbitrary data.
  608. // Upon retrieval the update will be retrieved verbatim as bytes.
  609. func (a *API) ResourceUpdate(ctx context.Context, name string, data []byte) (storage.Address, uint32, uint32, error) {
  610. return a.resourceUpdate(ctx, name, data, false)
  611. }
  612. func (a *API) resourceUpdate(ctx context.Context, name string, data []byte, multihash bool) (storage.Address, uint32, uint32, error) {
  613. var addr storage.Address
  614. var err error
  615. if multihash {
  616. addr, err = a.resource.UpdateMultihash(ctx, name, data)
  617. } else {
  618. addr, err = a.resource.Update(ctx, name, data)
  619. }
  620. period, _ := a.resource.GetLastPeriod(name)
  621. version, _ := a.resource.GetVersion(name)
  622. return addr, period, version, err
  623. }
  624. // ResourceHashSize returned the size of the digest produced by the Mutable Resource hashing function
  625. func (a *API) ResourceHashSize() int {
  626. return a.resource.HashSize
  627. }
  628. // ResourceIsValidated checks if the Mutable Resource has an active content validator.
  629. func (a *API) ResourceIsValidated() bool {
  630. return a.resource.IsValidated()
  631. }
  632. // ResolveResourceManifest retrieves the Mutable Resource manifest for the given address, and returns the address of the metadata chunk.
  633. func (a *API) ResolveResourceManifest(addr storage.Address) (storage.Address, error) {
  634. trie, err := loadManifest(a.fileStore, addr, nil)
  635. if err != nil {
  636. return nil, fmt.Errorf("cannot load resource manifest: %v", err)
  637. }
  638. entry, _ := trie.getEntry("")
  639. if entry.ContentType != ResourceContentType {
  640. return nil, fmt.Errorf("not a resource manifest: %s", addr)
  641. }
  642. return storage.Address(common.FromHex(entry.Hash)), nil
  643. }