-
Notifications
You must be signed in to change notification settings - Fork 1
/
couchdoc_conv.go
237 lines (199 loc) · 5.75 KB
/
couchdoc_conv.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
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package statecouchdb
import (
"bytes"
"encoding/json"
"strings"
"unicode/utf8"
"github.com/mcc-github/blockchain/core/ledger/kvledger/txmgmt/statedb"
"github.com/mcc-github/blockchain/core/ledger/kvledger/txmgmt/version"
"github.com/mcc-github/blockchain/core/ledger/util/couchdb"
"github.com/pkg/errors"
)
const (
binaryWrapper = "valueBytes"
idField = "_id"
revField = "_rev"
versionField = "~version"
deletedField = "_deleted"
)
type keyValue struct {
key string
*statedb.VersionedValue
}
type jsonValue map[string]interface{}
func tryCastingToJSON(b []byte) (isJSON bool, val jsonValue) {
var jsonVal map[string]interface{}
err := json.Unmarshal(b, &jsonVal)
return err == nil, jsonValue(jsonVal)
}
func castToJSON(b []byte) (jsonValue, error) {
var jsonVal map[string]interface{}
err := json.Unmarshal(b, &jsonVal)
err = errors.Wrap(err, "error unmarshalling json data")
return jsonVal, err
}
func (v jsonValue) checkReservedFieldsNotPresent() error {
for fieldName := range v {
if fieldName == versionField || strings.HasPrefix(fieldName, "_") {
return errors.Errorf("field [%s] is not valid for the CouchDB state database", fieldName)
}
}
return nil
}
func (v jsonValue) removeRevField() {
delete(v, revField)
}
func (v jsonValue) toBytes() ([]byte, error) {
jsonBytes, err := json.Marshal(v)
err = errors.Wrap(err, "error marshalling json data")
return jsonBytes, err
}
func couchDocToKeyValue(doc *couchdb.CouchDoc) (*keyValue, error) {
var returnValue []byte
var err error
jsonResult := make(map[string]interface{})
decoder := json.NewDecoder(bytes.NewBuffer(doc.JSONValue))
decoder.UseNumber()
if err = decoder.Decode(&jsonResult); err != nil {
return nil, err
}
if _, fieldFound := jsonResult[versionField]; !fieldFound {
return nil, errors.Errorf("version field %s was not found", versionField)
}
key := jsonResult[idField].(string)
returnVersion, returnMetadata, err := decodeVersionAndMetadata(jsonResult[versionField].(string))
if err != nil {
return nil, err
}
delete(jsonResult, idField)
delete(jsonResult, revField)
delete(jsonResult, versionField)
if doc.Attachments != nil {
for _, attachment := range doc.Attachments {
if attachment.Name == binaryWrapper {
returnValue = attachment.AttachmentBytes
}
}
} else {
if returnValue, err = json.Marshal(jsonResult); err != nil {
return nil, err
}
}
return &keyValue{key, &statedb.VersionedValue{
Value: returnValue,
Metadata: returnMetadata,
Version: returnVersion},
}, nil
}
func keyValToCouchDoc(kv *keyValue, revision string) (*couchdb.CouchDoc, error) {
type kvType int32
const (
kvTypeDelete = iota
kvTypeJSON
kvTypeAttachment
)
key, value, metadata, version := kv.key, kv.Value, kv.Metadata, kv.Version
jsonMap := make(jsonValue)
var kvtype kvType
switch {
case value == nil:
kvtype = kvTypeDelete
case json.Unmarshal(value, &jsonMap) == nil && jsonMap != nil:
kvtype = kvTypeJSON
if err := jsonMap.checkReservedFieldsNotPresent(); err != nil {
return nil, err
}
default:
if jsonMap == nil {
jsonMap = make(jsonValue)
}
kvtype = kvTypeAttachment
}
verAndMetadata, err := encodeVersionAndMetadata(version, metadata)
if err != nil {
return nil, err
}
jsonMap[versionField] = verAndMetadata
jsonMap[idField] = key
if revision != "" {
jsonMap[revField] = revision
}
if kvtype == kvTypeDelete {
jsonMap[deletedField] = true
}
jsonBytes, err := jsonMap.toBytes()
if err != nil {
return nil, err
}
couchDoc := &couchdb.CouchDoc{JSONValue: jsonBytes}
if kvtype == kvTypeAttachment {
attachment := &couchdb.AttachmentInfo{}
attachment.AttachmentBytes = value
attachment.ContentType = "application/octet-stream"
attachment.Name = binaryWrapper
attachments := append([]*couchdb.AttachmentInfo{}, attachment)
couchDoc.Attachments = attachments
}
return couchDoc, nil
}
type couchSavepointData struct {
BlockNum uint64 `json:"BlockNum"`
TxNum uint64 `json:"TxNum"`
}
func encodeSavepoint(height *version.Height) (*couchdb.CouchDoc, error) {
var err error
var savepointDoc couchSavepointData
savepointDoc.BlockNum = height.BlockNum
savepointDoc.TxNum = height.TxNum
savepointDocJSON, err := json.Marshal(savepointDoc)
if err != nil {
err = errors.Wrap(err, "failed to marshal savepoint data")
logger.Errorf("%+v", err)
return nil, err
}
return &couchdb.CouchDoc{JSONValue: savepointDocJSON, Attachments: nil}, nil
}
func decodeSavepoint(couchDoc *couchdb.CouchDoc) (*version.Height, error) {
savepointDoc := &couchSavepointData{}
if err := json.Unmarshal(couchDoc.JSONValue, &savepointDoc); err != nil {
err = errors.Wrap(err, "failed to unmarshal savepoint data")
logger.Errorf("%+v", err)
return nil, err
}
return &version.Height{BlockNum: savepointDoc.BlockNum, TxNum: savepointDoc.TxNum}, nil
}
func validateValue(value []byte) error {
isJSON, jsonVal := tryCastingToJSON(value)
if !isJSON {
return nil
}
return jsonVal.checkReservedFieldsNotPresent()
}
func validateKey(key string) error {
if !utf8.ValidString(key) {
return errors.Errorf("invalid key [%x], must be a UTF-8 string", key)
}
if strings.HasPrefix(key, "_") {
return errors.Errorf("invalid key [%s], cannot begin with \"_\"", key)
}
if key == "" {
return errors.New("invalid key. Empty string is not supported as a key by couchdb")
}
return nil
}
func removeJSONRevision(jsonValue *[]byte) error {
jsonVal, err := castToJSON(*jsonValue)
if err != nil {
logger.Errorf("Failed to unmarshal couchdb JSON data: %+v", err)
return err
}
jsonVal.removeRevField()
if *jsonValue, err = jsonVal.toBytes(); err != nil {
logger.Errorf("Failed to marshal couchdb JSON data: %+v", err)
}
return err
}