-
Notifications
You must be signed in to change notification settings - Fork 0
/
platform.go
451 lines (380 loc) · 10.9 KB
/
platform.go
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
/*
Notice: This file has been modified for Hyperledger Fabric SDK Go usage.
Please review third_party pinning scripts and patches for more details.
*/
package golang
import (
"archive/tar"
"bytes"
"compress/gzip"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"runtime"
"sort"
"strings"
pb "github.com/hyperledger/fabric-protos-go/peer"
"github.com/pkg/errors"
"github.com/hellobchain/fabric-sdk-go/internal/github.com/hyperledger/fabric/core/chaincode/platforms/util"
"github.com/hellobchain/fabric-sdk-go/internal/github.com/hyperledger/fabric/sdkinternal/ccmetadata"
)
// Platform for chaincodes written in Go
type Platform struct{}
// Name returns the name of this platform.
func (p *Platform) Name() string {
return pb.ChaincodeSpec_GOLANG.String()
}
// ValidatePath is used to ensure that path provided points to something that
// looks like go chainccode.
//
// NOTE: this is only used at the _client_ side by the peer CLI.
func (p *Platform) ValidatePath(rawPath string) error {
_, err := DescribeCode(rawPath)
if err != nil {
return err
}
return nil
}
// NormalizePath is used to extract a relative module path from a module root.
// This should not impact legacy GOPATH chaincode.
//
// NOTE: this is only used at the _client_ side by the peer CLI.
func (p *Platform) NormalizePath(rawPath string) (string, error) {
modInfo, err := moduleInfo(rawPath)
if err != nil {
return "", err
}
// not a module
if modInfo == nil {
return rawPath, nil
}
return modInfo.ImportPath, nil
}
// ValidateCodePackage examines the chaincode archive to ensure it is valid.
//
// NOTE: this code is used in some transaction validation paths but can be changed
// post 2.0.
func (p *Platform) ValidateCodePackage(code []byte) error {
is := bytes.NewReader(code)
gr, err := gzip.NewReader(is)
if err != nil {
return fmt.Errorf("failure opening codepackage gzip stream: %s", err)
}
re := regexp.MustCompile(`^(src|META-INF)/`)
tr := tar.NewReader(gr)
for {
header, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return err
}
// maintain check for conforming paths for validation
if !re.MatchString(header.Name) {
return fmt.Errorf("illegal file name in payload: %s", header.Name)
}
// only files and directories; no links or special files
mode := header.FileInfo().Mode()
if mode&^(os.ModeDir|0777) != 0 {
return fmt.Errorf("illegal file mode in payload: %s", header.Name)
}
}
return nil
}
// Directory constant copied from tar package.
const c_ISDIR = 040000
// Default compression to use for production. Test packages disable compression.
var gzipCompressionLevel = gzip.DefaultCompression
// GetDeploymentPayload creates a gzip compressed tape archive that contains the
// required assets to build and run go chaincode.
//
// NOTE: this is only used at the _client_ side by the peer CLI.
func (p *Platform) GetDeploymentPayload(codepath string) ([]byte, error) {
codeDescriptor, err := DescribeCode(codepath)
if err != nil {
return nil, err
}
fileMap, err := findSource(codeDescriptor)
if err != nil {
return nil, err
}
var dependencyPackageInfo []PackageInfo
if !codeDescriptor.Module {
for _, dist := range distributions() {
pi, err := gopathDependencyPackageInfo(dist.goos, dist.goarch, codeDescriptor.Path)
if err != nil {
return nil, err
}
dependencyPackageInfo = append(dependencyPackageInfo, pi...)
}
}
for _, pkg := range dependencyPackageInfo {
for _, filename := range pkg.Files() {
sd := SourceDescriptor{
Name: path.Join("src", pkg.ImportPath, filename),
Path: filepath.Join(pkg.Dir, filename),
}
fileMap[sd.Name] = sd
}
}
payload := bytes.NewBuffer(nil)
gw, err := gzip.NewWriterLevel(payload, gzipCompressionLevel)
if err != nil {
return nil, err
}
tw := tar.NewWriter(gw)
// Create directories so they get sane ownership and permissions
for _, dirname := range fileMap.Directories() {
err := tw.WriteHeader(&tar.Header{
Typeflag: tar.TypeDir,
Name: dirname + "/",
Mode: c_ISDIR | 0755,
Uid: 500,
Gid: 500,
})
if err != nil {
return nil, err
}
}
for _, file := range fileMap.Sources() {
err = util.WriteFileToPackage(file.Path, file.Name, tw)
if err != nil {
return nil, fmt.Errorf("Error writing %s to tar: %s", file.Name, err)
}
}
err = tw.Close()
if err == nil {
err = gw.Close()
}
if err != nil {
return nil, errors.Wrapf(err, "failed to create tar for chaincode")
}
return payload.Bytes(), nil
}
// CodeDescriptor describes the code we're packaging.
type CodeDescriptor struct {
Source string // absolute path of the source to package
MetadataRoot string // absolute path META-INF
Path string // import path of the package
Module bool // does this represent a go module
}
func (cd CodeDescriptor) isMetadata(path string) bool {
return strings.HasPrefix(
filepath.Clean(path),
filepath.Clean(cd.MetadataRoot),
)
}
// DescribeCode returns GOPATH and package information.
func DescribeCode(path string) (*CodeDescriptor, error) {
if path == "" {
return nil, errors.New("cannot collect files from empty chaincode path")
}
// Use the module root as the source path for go modules
modInfo, err := moduleInfo(path)
if err != nil {
return nil, err
}
if modInfo != nil {
// calculate where the metadata should be relative to module root
relImport, err := filepath.Rel(modInfo.ModulePath, modInfo.ImportPath)
if err != nil {
return nil, err
}
return &CodeDescriptor{
Module: true,
MetadataRoot: filepath.Join(modInfo.Dir, relImport, "META-INF"),
Path: modInfo.ImportPath,
Source: modInfo.Dir,
}, nil
}
return describeGopath(path)
}
func describeGopath(importPath string) (*CodeDescriptor, error) {
output, err := exec.Command("go", "list", "-mod=vendor", "-f", "{{.Dir}}", importPath).Output()
if err != nil {
return nil, wrapExitErr(err, "'go list -mod=vendor' failed")
}
sourcePath := filepath.Clean(strings.TrimSpace(string(output)))
return &CodeDescriptor{
Path: importPath,
MetadataRoot: filepath.Join(sourcePath, "META-INF"),
Source: sourcePath,
}, nil
}
func regularFileExists(path string) (bool, error) {
fi, err := os.Stat(path)
switch {
case os.IsNotExist(err):
return false, nil
case err != nil:
return false, err
default:
return fi.Mode().IsRegular(), nil
}
}
func moduleInfo(path string) (*ModuleInfo, error) {
entryWD, err := os.Getwd()
if err != nil {
return nil, errors.Wrap(err, "failed to get working directory")
}
// directory doesn't exist so unlikely to be a module
if err := os.Chdir(path); err != nil {
return nil, nil
}
defer func() {
if err := os.Chdir(entryWD); err != nil {
panic(fmt.Sprintf("failed to restore working directory: %s", err))
}
}()
// Using `go list -m -f '{{ if .Main }}{{.GoMod}}{{ end }}' all` may try to
// generate a go.mod when a vendor tool is in use. To avoid that behavior
// we use `go env GOMOD` followed by an existence check.
cmd := exec.Command("go", "env", "GOMOD")
cmd.Env = append(os.Environ(), "GO111MODULE=on")
output, err := cmd.Output()
if err != nil {
return nil, wrapExitErr(err, "failed to determine module root")
}
modExists, err := regularFileExists(strings.TrimSpace(string(output)))
if err != nil {
return nil, err
}
if !modExists {
return nil, nil
}
return listModuleInfo()
}
type SourceDescriptor struct {
Name string
Path string
}
type Sources []SourceDescriptor
func (s Sources) Len() int { return len(s) }
func (s Sources) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s Sources) Less(i, j int) bool { return s[i].Name < s[j].Name }
type SourceMap map[string]SourceDescriptor
func (s SourceMap) Sources() Sources {
var sources Sources
for _, src := range s {
sources = append(sources, src)
}
sort.Sort(sources)
return sources
}
func (s SourceMap) Directories() []string {
dirMap := map[string]bool{}
for entryName := range s {
dir := path.Dir(entryName)
for dir != "." && !dirMap[dir] {
dirMap[dir] = true
dir = path.Dir(dir)
}
}
var dirs []string
for dir := range dirMap {
dirs = append(dirs, dir)
}
sort.Strings(dirs)
return dirs
}
func findSource(cd *CodeDescriptor) (SourceMap, error) {
sources := SourceMap{}
walkFn := func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
// Allow import of the top level chaincode directory into chaincode code package
if path == cd.Source {
return nil
}
// Allow import of META-INF metadata directories into chaincode code package tar.
// META-INF directories contain chaincode metadata artifacts such as statedb index definitions
if cd.isMetadata(path) {
return nil
}
// include everything except hidden dirs when we're not vendoring
if cd.Module && !strings.HasPrefix(info.Name(), ".") {
return nil
}
// Do not import any other directories into chaincode code package
return filepath.SkipDir
}
relativeRoot := cd.Source
if cd.isMetadata(path) {
relativeRoot = cd.MetadataRoot
}
name, err := filepath.Rel(relativeRoot, path)
if err != nil {
return errors.Wrapf(err, "failed to calculate relative path for %s", path)
}
switch {
case cd.isMetadata(path):
// Skip hidden files in metadata
if strings.HasPrefix(info.Name(), ".") {
return nil
}
name = filepath.Join("META-INF", name)
err := validateMetadata(name, path)
if err != nil {
return err
}
case cd.Module:
name = filepath.Join("src", name)
default:
// skip top level go.mod and go.sum when not in module mode
if name == "go.mod" || name == "go.sum" {
return nil
}
name = filepath.Join("src", cd.Path, name)
}
name = filepath.ToSlash(name)
sources[name] = SourceDescriptor{Name: name, Path: path}
return nil
}
if err := filepath.Walk(cd.Source, walkFn); err != nil {
return nil, errors.Wrap(err, "walk failed")
}
return sources, nil
}
func validateMetadata(name, path string) error {
contents, err := ioutil.ReadFile(path)
if err != nil {
return err
}
// Validate metadata file for inclusion in tar
// Validation is based on the passed filename with path
err = ccmetadata.ValidateMetadataFile(filepath.ToSlash(name), contents)
if err != nil {
return err
}
return nil
}
// dist holds go "distribution" information. The full list of distributions can
// be obtained with `go tool dist list.
type dist struct{ goos, goarch string }
// distributions returns the list of OS and ARCH combinations that we calcluate
// deps for.
func distributions() []dist {
// pre-populate linux architecutures
dists := map[dist]bool{
{goos: "linux", goarch: "amd64"}: true,
}
// add local OS and ARCH
dists[dist{goos: runtime.GOOS, goarch: runtime.GOARCH}] = true
var list []dist
for d := range dists {
list = append(list, d)
}
return list
}