github.com/gobitfly/go-ethereum@v1.8.12/swarm/api/api.go (about)

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