github.com/adnan-c/fabric_e2e_couchdb@v0.6.1-preview.0.20170228180935-21ce6b23cf91/orderer/sbft/config.go (about)

     1  /*
     2  Copyright IBM Corp. 2016 All Rights Reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  		 http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package sbft
    18  
    19  import (
    20  	"encoding/json"
    21  	"fmt"
    22  	"io/ioutil"
    23  
    24  	"github.com/golang/protobuf/proto"
    25  	"github.com/hyperledger/fabric/orderer/sbft/crypto"
    26  	"github.com/hyperledger/fabric/orderer/sbft/persist"
    27  )
    28  
    29  func ReadJsonConfig(file string) (*ConsensusConfig, error) {
    30  	configData, err := ioutil.ReadFile(file)
    31  	if err != nil {
    32  		return nil, err
    33  	}
    34  
    35  	jconfig := &JsonConfig{}
    36  	err = json.Unmarshal(configData, jconfig)
    37  	if err != nil {
    38  		return nil, err
    39  	}
    40  
    41  	config := &ConsensusConfig{}
    42  	config.Consensus = jconfig.Consensus
    43  	config.Peers = make(map[string][]byte)
    44  	for n, p := range jconfig.Peers {
    45  		if p.Address == "" {
    46  			return nil, fmt.Errorf("The required peer address is missing (for peer %d)", n)
    47  		}
    48  		cert, err := crypto.ParseCertPEM(p.Cert)
    49  		if err != nil {
    50  			fmt.Println("exiting")
    51  			return nil, err
    52  		}
    53  		config.Peers[p.Address] = cert
    54  	}
    55  
    56  	// XXX check for duplicate cert
    57  	if config.Consensus.N != 0 && int(config.Consensus.N) != len(config.Peers) {
    58  		return nil, fmt.Errorf("peer config does not match pbft N")
    59  	}
    60  
    61  	config.Consensus.N = uint64(len(config.Peers))
    62  
    63  	return config, nil
    64  }
    65  
    66  func SaveConfig(p *persist.Persist, c *ConsensusConfig) error {
    67  	craw, err := proto.Marshal(c)
    68  	if err != nil {
    69  		return err
    70  	}
    71  	err = p.StoreState("config", craw)
    72  	return err
    73  }
    74  
    75  func RestoreConfig(p *persist.Persist) (*ConsensusConfig, error) {
    76  	raw, err := p.ReadState("config")
    77  	if err != nil {
    78  		return nil, err
    79  	}
    80  	config := &ConsensusConfig{}
    81  	err = proto.Unmarshal(raw, config)
    82  	if err != nil {
    83  		return nil, err
    84  	}
    85  	return config, nil
    86  }